text:
Q: Why does adding mutable produce different hash values? I have a simple struct like this with no custom == or hash() methods:
struct IntroductionMessage
    message::String
end

When I call hash() both return the same value:
say_hello_introduction = IntroductionMessage("Hello World")
say_hello_introduction_alternate = IntroductionMessage("Hello World")

hash(say_hello_introduction))
hash(say_hello_introduction_alternate))

# Output:
3650104434
3650104434

When I add the mutable keyword, so it's now mutable struct IntroductionMessage, the hash() values are different:
2957940122
238434212

The string itself never changed, so why does adding mutable produce a different result?

A: By default immutable structs are hashed by value while mutable structs are hashed by reference. This matches the default equality operations.


text:
Q: how to display record on one page with continues record number and create new header column? I have a problem, on design lay out crystal report,
I want to display like this,
 lay out report image
I have been looking for on google, but not found. I confuse what is the right keyword in google. Please help me, thanks.

A: In Crystal Reports, create a running total that is based on the field you want to count. The type of summary will be count. Evaluate for each record and never reset. Add the field and running total to the report detail section. That will show you a count of all your records.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Image in horizontal scroll are stretched I have a gallery of images in a horizontal scroll.
The scroll got a fixed height and the image should take 100% of the scroll height.
Images got variable width but should keep his aspect ratio when they are in the scroll.
I made it simple in codepen but it was working without the toggle. Then I tested with my real spec:

*

*First, it's hidden

*Then on a user click on a button, the gallery becomes visible

Here is the codepen: https://codepen.io/Liroo/pen/zYYgGWz
The website where is the bug: http://framepictures.studio-push.com/photographie/making-of/#louis-vuitton
This simple (s)css:
&__gallery {
   border-bottom: solid 1px white;
   height: 32vw;

   &__image {
     height: 100%;
   }
}

may work (because sometimes it's not) in the codepen but if you check the website link, it is always buggy.
You can update it with playing with the off class of the #toggle div and you will see this weird behavior.
I already made a javascript version of this bug but I would like to know if there is any CSS solution. (here my previous solution: http://jensingvarsson.studio-push.com/)
EDIT:
Here you can find the bug in the gallery: http://framepictures.studio-push.com/photographie/making-of/#louis-vuitton
Sometimes it stretch, sometimes, just images are cut because the parent div is less wide.


text:
Q: Can't quite figure out how to take array from JS file to HTML I am using discord API to get all information about users and their guilds. But when I filter all information I need and try to show it on frond end of my aplication. It show as: Object, object , I was trying to do this for a long time, and it confuses me a lot. Please help. Thank you
I am using express.
HTML Code:

   <meta charset="UTF-8">

   <img src="https://cdn.discordapp.com/avatars/<%=id%>/<%=avatar%>">

Username: <%=username%>
ID: <%=id%>

My array looks like this:

[
  { name: ' • Ghost Community', id: '920369960419721267' },
  { name: 'KAROVICH', id: '951578230496850021' },
  { name: 'BOTTESTER V2', id: '977826403221385277' }
]


text:
Q: Xcode does not show @IBAction for UIButton When i ctrl-drag from a UIButton in storyboard to the viewcontroller class , Xcode is not showing the option to create an IBAction.

I think this something to do with the project setting because i try to open it to another pc it had the same problem.
SOLUTION
Apparently i created an extension of UIButton that causes this problem.

A: Try another way (my usual way), from code create your @IBAction :
@IBAction func myAction(){
  //here your code
}

Then CTRL - drag to this @IBAction myAction


text:
Q: Anchor Link to open a specific Tab on a Page (cbpFWTabs) I've been using tabs from codrops Tab Styles Inspiration and I need to be able to open specific tabs on urls.
Basically if I wanted to open tab3, I would link www.google.com/index#tab3.
Here is my code:

Overview

Register

Exhibitors

Test 1

Test 2

Test 3

And here is the javascript:
;( function( window ) {

'use strict';

function extend( a, b ) {
    for( var key in b ) {
        if( b.hasOwnProperty( key ) ) {
            a[key] = b[key];
        }
    }
    return a;
}

function CBPFWTabs( el, options ) {
    this.el = el;
    this.options = extend( {}, this.options );
    extend( this.options, options );
    this._init();
}

CBPFWTabs.prototype.options = {
    start : 0
};

CBPFWTabs.prototype._init = function() {
    // tabs elems
    this.tabs = [].slice.call( this.el.querySelectorAll( 'nav > ul > li' )         );
    // content items
    this.items = [].slice.call( this.el.querySelectorAll( '.content-wrap >  section' ) );
    // current index
    this.current = -1;
    // show current content item
    this._show();
    // init events
    this._initEvents();
};

CBPFWTabs.prototype._initEvents = function() {
    var self = this;
    this.tabs.forEach( function( tab, idx ) {
        tab.addEventListener( 'click', function( ev ) {
            ev.preventDefault();
            self._show( idx );
        } );
    } );
};

CBPFWTabs.prototype._show = function( idx ) {
    if( this.current >= 0 ) {
        this.tabs[ this.current ].className = this.items[ this.current   ].className = '';
    }
    // change current
    this.current = idx != undefined ? idx : this.options.start >= 0 &&         this.options.start < this.items.length ? this.options.start : 0;
    this.tabs[ this.current ].className = 'tab-current';
    this.items[ this.current ].className = 'content-current';
};

// add to global namespace
window.CBPFWTabs = CBPFWTabs;

})( window );

Sorry I'm not much a jquery guy and have been trying to find a solution all day and made an account just to ask this. Thanks in advance for your help.

A: Maybe just listen to window.hashchange event do the trick, no click handlers on nav > li > a!. The jQuery way:
$(function(){
    $(window).on('hashchange', function(e) {
        var hash = window.location.hash;

        // first reset classes
        $('nav li').removeClass('tab-current');
        $('.content-wrap section').removeClass('content-current');

        $('nav li a[href="' + hash + '"]').parents('li').addClass('tab-current');
        $('section[id="' + hash.replace('#', '') + '"]').addClass('content-current');
    });
});


text:
Q: tui-calendar doesn't display properly in ExtJS panel I've been looking at adding a simple calendar to an ExtJS app and like the features of the tui-calendar.
I've started with just trying to display a month in a panel. I've tried various layouts, length and width configs, but the calendar never fully displays. Here's a fiddle showing the results.
Any ideas what I'm missing?
Thanks in advance,
Gordon

A: You can use layout: 'fit' on the panel and set the div's width and height to 100% with html style, like

. This way you:

*

*tell the panel (which has a fixed size) that it will have one child that should occupy all available area,

*tell the div which contains the calendar to use 100% of the available place horizontally and vertically.

Ext.create('Ext.panel.Panel', {
    renderTo: document.body,
    height: 600,
    width: 600,
    layout: 'fit',
    tbar: [{
        xtype: 'button',
        text: 'Display Calendar',
        handler: function (button) {
            const container = document.getElementById('calendar');
            calendar = new tui.Calendar(container, options);
            calendar.setDate('2023-03-01');
        }
    }],
    items: [{
        html: '

',
        xtype: 'component'
    }]
});

I'd like to note that I am not sure that this way ExtJS will manage the life cycle of the calendar object. I would recommend to keep track of the created calendar object and destroy it when the panel is destroyed. To do so, add a destroy listener event to the panel and destroy the calendar object there.


text:
Q: Write a custom lookup script for MusicBrainz Picard I have a collection of music files (~200/batch) that I need to tag through Picard. The files have no metadata, and the fingerprinting tool is very inefficient (<50% mean accuracy).
However, the titles are like this: "(Song Name)-(Artist).(format)", and they are almost perfect. I can write a sed to extract these.
I need a way to be able to write a custom script that allows me to use the Picard's lookup feature, with the parameters I extract from sed (in-script) from the filename, and do a lookup. Is that possible?
I am looking for guidelines, but an example would be great.
As @terdon requested, more details:

*

*Picard has two modes of identifying a song: 1) Acoustic Fingerprinting, and 2) Lookup using existing metadata

*For some reason, the first method, ie Acoustic Fingerprinting is giving me very poor result on a certain set of songs

*However, my songs already have the correct Artist Name, Track Title in the filename, I just need to lookup the track to get Year, Cover Image etc.

*The default lookup script (internal to Picard?) is using the complete file name, which has garbage in it to do a lookup, leading to inferior results

*I would like to specify which part of the file name to use for the lookup, as I mention above.

Something like:
i="Track Name/ File Name"
$artist="sed -r 's/.../\1/'" $i
$track="sed -r 's/...\2/'" $i
lookup($i, $artist, $track)

Of course the scripting language for Picard may be different.

A: It's possible to use a script, but that's not necessary. Picard has a build-in Convert File Names to Tags for that and for a better recognition, write the tags to your files taken from your filenames.
Open picard and your music folder

and open Tools - Tags From File Names


text:
Q: Add class for all parents element on native JavaScript If I have some ".blocks"
body
    section
        .main-container
            .container
                .block
                .blcok

And I need add className for all parents block, div, section, body.
When I use jquwry I wrote like this:
    $(".block").parents().addClass('block-wrapp');

But now I must use native js.
window.onload = function() {

    let block = document.getElementsByClassName('block');

    for( let i = 0; i < block.length; i++ ) {
        block[i].parentNode.classList.add('block-wrapp');
    }
};

I try use
        let mainBlock = block[i].parentNode.className;
        console.log(mainBlock.parentNode);

But it doesn't work

A: Loop through all parents with a while statement:
// loop through selected elements
for( let i = 0; i < block.length; i++ ) {

    // get current looped element
    let node = block[i];

    // do this as long as we have a parent to go to
    while (let parent = node.parentNode) {

        // add class on parent
        parent.classList.add('block-wrapp');

        // move up the tree
        node = parent;
    }
}

You can improve a bit the performance so you don't visit the same parents and traverse the entire tree over and over again for sibling elements. For this, get a list of processed parents and skip them the next time you encounter them:
let visitedParents = [];
while (parent = node.parentNode && visitedParents.indexOf(parent) === -1) {
    // ...

    // mark this parent as visited
    visitedParents.push(parent);
}

Finally, you should also stop when reaching the body element, otherwise you'll reach html and the document, which I presume you don't want to:
while (node.parentNode !== document.body && .... ) { ... }

A: Try changing your parentNode to parentElement inside the loop


text:
Q: Color Marks for different rows in TABLEAU I am trying to color the price difference based on cluster
And the product IDs based on who pays for Logistics. But somehow I do not know how to apply two colour marks for two different rows. Can anyone help me with it? Screenshot is attached. enter image description here

A: As you want to colour a dimension column as well as a measure, the placeholder technique could be your best option. Create a dummy field
MIN(0)

Put this to Columns 4 times. Use these to create 2 dual axis columns. This enables putting any dimension / measure into the column and also to colour those by a different value.
It's a long topic, please refer to this URL for full guidance: https://tarsolutions.co.uk/blog/using-the-placeholder-for-advanced-tableau-tables/


text:
Q: Convert SVG to PDF with GhostScript/GhostPDL? Question:
It is possible to convert SVG to PDF using GhostPCL, like this:
gsvg.exe -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -sOutputFile=my.pdf t1.svg

The difficulty is getting gsvg.exe...
I managed to find the source from:
http://svn.ghostscript.com/ghostscript/trunk/
and it built and compiled and it works fine.
However, when I go to http://svn.ghostscript.com, then it states:

SVN is decprecated, Ghostscript and associated projects are now hosted
  only in git repositories, see:  http://git.ghostscript.com

So I tried to get the latest version by downloading from the git repository
git clone http://git.ghostscript.com/ghostpdl.git

It built fine, but it looks like gsvg is gone.
Unfortunately, it lacks a bit in the documentation department.
Does anybody know if this functionality has been integrated, deleted, or otherwise moved ?
If it has been integrated, how can I convert a svg to a pdf in the new version (using ghost*) ?

PS:
Yes, I know I can do it with inkscape or rsvg-convert, but they don't work fine for my SVGs (rsvg-convert removes all text), inkscape delivers poor quality svg conversion. CairoSVG seems to be the same as rsvg-convert.
Only ghostsvg works as required.

A: SVG input (gsvg) has been deprecated and removed from Ghostscript. It never worked well and there was not sufficient interest to bring it up to date and maintain it.
If you're really desperate you can probably take the gsvg sources and glue them together with the current graphics library and output devices, nothing has changed in the Ghostscript API so this 'should' all still work, but the directory structure has been reworked and the makefiles modified to match, so its not going to be simple.


text:
Q: AngularJS Firebase sendEmailVerification not working I want to send a verification email to the registering user using Firebase.
My registration controller is like the following:
app.controller("MyregisterCtrl", ["$scope", "firebase", "$firebaseAuth", "$location", function ($scope, firebase, $firebaseAuth, $location) {

    $scope.signUp = function () {
        var username = $scope.user.email;
        var password = $scope.user.password;

        if (username && password) {
            var auth = $firebaseAuth();
            var user = firebase.auth().currentUser;

            auth.$createUserWithEmailAndPassword(username, password)
            user.sendEmailVerification()
                .then(function () {
                    console.log("User signup success");
                    $scope.errMsg = false;
                    $location.path('/login.signin');
                }).catch(function (error) {
                $scope.errMsg = true;
                $scope.errorMessage = error.message;
            });
        }
    }

}]);

The user gets registered in the Firebase user database. But I have to click three times in a row on the submit button in order to get a verification email. Very strange.
Why doesn't it send it on the first submit click?
Here is the error screenshot:

A: Creating a user account is an operation that can take some time. If you call sendEmailVerification() before the operation is completed, you'll get the error message in your screenshot (for any future questions: don't post pictures of text please, post the actual text itself).
To solve the problem, you can wait until the account is created by waiting for the so-called promise to resolve:
auth.$createUserWithEmailAndPassword(username, password)
    .then(function(user) {
        user.sendEmailVerification()
    }).then(function () {
        console.log("User signup success");
        $scope.errMsg = false;
        $location.path('/login.signin');
    }).catch(function (error) {
        $scope.errMsg = true;
        $scope.errorMessage = error.message;
    });

So the sequence here:

*

*create the user account

*once this succeeds, send a verification email

*once this succeeds, log success and redirect

*if either 1 or 2 fails, show an error message


text:
Q: Application_Error no longer triggers when published to IIS OK I have the following code in my Global.asax file:
void Application_Error(object sender, EventArgs e)
{
    // Code that runs when an unhandled error occurs
        Exception objError = Server.GetLastError().GetBaseException();

        Response.Redirect(
            String.Format(
            "/Error/{0}/{1}",
            ((HttpException)objError).GetHttpCode(),
            Request.RawUrl));
}

To provide neat and tidy error urls like "/Error/404/TheNameOfTheRequestedPage". This works fine from VS 2008, but once published to my local machine, I get the default error page:

Error Summary
HTTP Error 404.0 - Not Found
The resource you are looking for has
  been removed, had its name changed, or
  is temporarily unavailable

Anyone know how to do this? I've chosen not to use system.web/customErrors because I don't have access to Server.GetLastError() from there (or at least it's never worked for me) and I want to get the http code.

A: This is most likely related to you triggering an IIS Http Error which is defined in the web.config under the nodes
<system.webServer>
    <httpErrors>
    </httpErrors>
<system.webServer>

If the issue is you're returning an a response code for 404 and getting the IIS 404 page the issue is you need to do
Response.TrySkipIisCustomErrors = true;

Before you let the response finish otherwise IIS will intercept the error.
This is completely beyond unintuitive especially if you set the status code yourself. I tried to figure a way to file a bug on Microsoft Connect that manually setting a http error code does not automatically set TrySkipIisCustomErrors but could not seem to figure out any relevant product to submit it to.

A: I had a similar problem, and a call to Server.ClearError() before the redirect did solve the problem.
In your case I would write
void Application_Error(object sender, EventArgs e)
{
    // Code that runs when an unhandled error occurs
        Exception objError = Server.GetLastError();
        if(objError is HttpException){
          //Need to clear the error, otherwise the buil-in redirect would occure
          Server.ClearError();
          Response.Redirect(
              String.Format(
              "/Error/{0}/{1}",
              ((HttpException)objError).GetHttpCode(),
              Request.RawUrl));
        }
}

Notice that Server.GetLastError().GetBaseException() returns the base exception, which isn't always the HttpException, the one you are looking for is just GetLastError().


text:
Q: What is the first fundamental form? In simple terms. How do you explain the meaning, nature and the use of first fundamental form in layman terms or simple terms? How to intuitively think about first fundamental form?

A: The first fundamental form provides a way of measuring the lengths of curves on a surface.  You can think of it as being related to the dot product.


text:
Q: Djnago signals how to delete old object if new object created? I am using django signals for showing notifications. If any post created in my blog then it will notify the blog author and pending for admin approval see the picture:

if admin approve the blog post then author will get another new notification. I want to delete old  pending notification of post1 if new notification created for post1. see the picture:

here is my signals code for create notification:
class Blog(models.Model):
      .....my fields
      #signals code
     def blog_notify(sender, instance, *args, **kwargs):
          blog = instance
          blog_title = blog.title
          sender = blog.author

          if sender == blog.author and blog.is_published == "published":
             notify = Notifications(blog=blog, sender=sender, user=sender,text_preview = blog_title[:250], notification_type="post approved")
             notify.save()

          if sender == blog.author and blog.is_published == "pending":
             notify = Notifications(blog=blog, sender=sender, user=sender,text_preview = blog_title[:250], notification_type="pending post")
             notify.save()
post_save.connect(Blog.blog_notify, sender=Blog)

#UPDATE QUESTION
Ajay saini tried to give solution what I wanted but I found an problems in Ajay saini solution. If any object don't have any previous notification for delete then it will raise error. His solution working for existing notification or old object.

A: Delete pending notification once published.
 def blog_notify(sender, instance, *args, **kwargs):
          blog = instance
          blog_title = blog.title
          sender = blog.author

          if sender == blog.author and blog.is_published == "published":
             notify = Notifications(blog=blog, sender=sender, user=sender,text_preview = blog_title[:250], notification_type="post approved")
             notify.save()

             # Delete all pending notifications for specific blog
             Notifications.objects.filter(blog=blog, sender=sender, user=sender, notification_type="pending post").delete()

          if sender == blog.author and blog.is_published == "pending":
             notify = Notifications(blog=blog, sender=sender, user=sender,text_preview = blog_title[:250], notification_type="pending post")
             notify.save()


text:
Q: Android Button change style on click How create buttons with underline light when is clicked.
like tabs but i need only for buttons.

A: Checkout these tutorial.You can use TabHost
http://www.learn-android-easily.com/2013/07/android-tabwidget-example.html
http://www.androidhive.info/2011/08/android-tab-layout-tutorial/

A: You need to use a custom Selector (similar to Tabs Selector) as background to your Button.
<Button
     android:id="@+id/button"
     android:background="@drawable/button_background"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="My button" />

Your button_background.xml :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Non focused states -->
    <item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/tab_unselected_holo" />
    <item android:state_focused="false" android:state_selected="true"  android:state_pressed="false" android:drawable="@drawable/tab_selected_holo" />

    <!-- Focused states -->
    <item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/tab_unselected_focused_holo" />
    <item android:state_focused="true" android:state_selected="true"  android:state_pressed="false" android:drawable="@drawable/tab_selected_focused_holo" />

    <!-- Pressed -->
    <!--    Non focused states -->
    <item android:state_focused="false" android:state_selected="false" android:state_pressed="true" android:drawable="@drawable/tab_unselected_pressed_holo" />
    <item android:state_focused="false" android:state_selected="true"  android:state_pressed="true" android:drawable="@drawable/tab_selected_pressed_holo" />

    <!--    Focused states -->
    <item android:state_focused="true" android:state_selected="false" android:state_pressed="true" android:drawable="@drawable/tab_unselected_pressed_holo" />
    <item android:state_focused="true" android:state_selected="true"  android:state_pressed="true" android:drawable="@drawable/tab_selected_pressed_holo" />
</selector>

*

*tab_unselected_holo

*tab_selected_holo

*tab_unselected_focused_holo

*tab_selected_focused_holo

*tab_unselected_pressed_holo

*tab_selected_pressed_holo
PS: I get this example from here.


text:
Q: Save changes to GitHub using Git Bash I'm new to both GitHub and Git. I created a repository on github.com and added some files to it. Then, I used git bash (on Windows) to download those files using git clone github.com/username/repository.git. So I've got the files on my computer. Now, I have edited some files and I want to send the new files to the master branch on my GitHub repository. I've actually read those questions:
How to push to GitHub using Git Bash?
Error when push commits with Github: fatal: could not read Username
but I can't figure out any solutions.

A: *

*track the changes you wish to make
git add --all

*Commit your changes
git commit -m "$message"

*push your changes to github branch
git push origin localbranchname:remotebranchName

*create a pull request on github to master
It sounds like you might have removed your origin using those tutorials. On github, copy the address of the repo.
git remote set-url origin https://github.com/... (the link)

before step 3

A: What I would do is
git remote rm origin
git remote add origin 'git@github.com:username/repo.git'


text:
Q: ASP.NET MVC Database Views Quick question about database views. Am I right in assuming that I can create a database of view of various tables and connect them how I want etc and then when I do queries, add, edit delete etc then MVC will figure it all out for me without needing to do any complex SQL in the controller or repository?
Odd question but just wanted to make sure my assumption was valid. Cheers

A: Unfortunately, MVC will not figure it all out for you, you'll still need to write the SQL code (or use an ORM framework) to communicate with the database.
What MVC gives you with it's architecture is a clear separation of responsibilities:

*

*Views are responsible for displaying data and should be as simple as possible (i.e. little to no logic in them)

*Model(s) contain the business logic and rules

*Controllers are responsible for passing data between the Model and the Views.

A: What you are looking for is Scaffolding. In .net MVC I can't think of any tools which do this for you directly against the database. They all require either as Russ said an ORM i.e. Linq To SQL or Entity Framework (EF).
http://msdn.microsoft.com/en-us/library/cc488540.aspx
The closest you could get would be to use Database First model generation and then put the necessary MVC templates/views/code on top.

A: A database view is read-only so you will not be able to perform write operations on the view. You can however create a model from a view and display your data as defined from the view. If you are using an ORM solution such as ADO.NET Entities you can instantiate an object and add the child objects to it and be able to save the final result in a single transaction as well.


text:
Q: How to clean reinstall Win 7 without Install disc I want to reinstall one really old Windows 7 Home Prem. It was installed in laptop yet by seller. I searched and found just option Choosing an advanced recovery method->Return your computer to the factory setting but there is not option to reinstall Windows.
Is there any way to find original install package on disk, put it on USB and than clean install Win 7 on this laptop?
And also where can I find Product key of my windows. That on the bottom of my laptop is unreadable :(

A: Here you go: http://www.microsoft.com/en-us/software-recovery
You can verify your key and download an iso image there.
This howtogeek page gives you more information and direct download links to digitalriver.net hosted Windows iso's:
http://www.howtogeek.com/186775/how-to-download-windows-7-8-and-8.1-installation-media-legally/
Note: you do need a valid license code to validate the installation once installed, of course.
/edit: just read your addition that you don't have a valid license code. Be sure to retrieve your code before you start reinstalling anything.
Good luck!


text:
Q: Unable to import boto3 library after installation I installed boto3 library from AWS SDK but when I try to import in python interpreter, I get error. Here is the traceback:

import boto3
      Traceback (most recent call last):
        File "", line 1, in
        File "/home/rahul/rahul/boto3/boto3/init.py", line 16, in
          from boto3.session import Session
        File "/home/rahul/rahul/boto3/boto3/session.py", line 17, in
          import botocore.session
      ImportError: No module named 'botocore'

Can you please help me fix this issue?

A: Apparently you have installed boto3 but not botocore
botocore is the basis of boto3 but is lower level
See https://pypi.python.org/pypi/botocore


text:
Q: iOS 7 App Crash EXC_CRASH (SIGABRT) objc_exception_throw Works fine on iOS 6 Our app is crashing in iOS 7, its working fine in iOS 6. We are not sure what is causing the issue. We can see that there is some exception thrown but we are not sure where in code is causing that.
Here is the crash report:
Incident Identifier: 1F589930-15BD-49F7-80E6-831A95092FDF
CrashReporter Key:   aaa79870161ff1e371394b881a26e97f0066f464
Hardware Model:      iPhone5,2
Process:             myapp [1492]
Path:                /var/mobile/Applications/A121DF2F-A7B9-4DD9-9FBC-BB06CD7C5EF5/myapp.app/myapp
Identifier:          co.uk.myapp
Version:             1.0 (0.9)
Code Type:           ARM (Native)
Parent Process:      launchd [1]

Date/Time:           2013-10-01 14:59:17.555 +0530
OS Version:          iOS 7.0 (11A465)
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Triggered by Thread:  2

Last Exception Backtrace:
0   CoreFoundation                  0x2d4e4e86 __exceptionPreprocess + 126
1   libobjc.A.dylib                 0x377de6c2 objc_exception_throw + 34
2   CoreFoundation                  0x2d41e0c6 -[__NSPlaceholderArray initWithObjects:count:] + 414
3   CoreFoundation                  0x2d427a4c +[NSArray arrayWithObjects:count:] + 40
4   CoreFoundation                  0x2d45d9c0 -[NSDictionary allKeys] + 172
5   Foundation                      0x2df73336 -[NSISObjectiveLinearExpression description] + 122
6   Foundation                      0x2ddfc808 _NSDescriptionWithLocaleFunc + 84
7   CoreFoundation                  0x2d4babf2 __CFStringAppendFormatCore + 5618
8   CoreFoundation                  0x2d429d18 _CFStringCreateWithFormatAndArgumentsAux + 72
9   CoreFoundation                  0x2d4523c2 _CFLogvEx + 82
10  Foundation                      0x2de0b7ee NSLogv + 82
11  Foundation                      0x2de0b78e NSLog + 22
12  Foundation                      0x2de4a918 -[NSISEngine minimizeConstantInObjectiveRowWithHead:] + 180
13  Foundation                      0x2de4a46e -[NSISEngine optimize] + 170
14  Foundation                      0x2de461a8 -[NSISEngine withBehaviors:performModifications:] + 312
15  UIKit                           0x2fc69490 -[UIView(Hierarchy) _postMovedFromSuperview:] + 292
16  UIKit                           0x2feffb92 __UIViewWasRemovedFromSuperview + 214
17  UIKit                           0x2fc68342 -[UIView(Hierarchy) removeFromSuperview] + 266
18  UIKit                           0x2fd3cccc -[UIScrollView removeFromSuperview] + 60
19  UIKit                           0x2fd313e4 -[UINavigationController navigationTransitionView:didEndTransition:fromView:toView:] + 312
20  UIKit                           0x2fdfcb5c __49-[UINavigationController _startCustomTransition:]_block_invoke + 156
21  UIKit                           0x2fd81416 -[_UIViewControllerTransitionContext completeTransition:] + 70
22  UIKit                           0x2fe418dc __53-[_UINavigationParallaxTransition animateTransition:]_block_invoke105 + 448
23  UIKit                           0x2fca2618 -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 280
24  UIKit                           0x2fca226a -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 174
25  UIKit                           0x2fca2186 -[UIViewAnimationState animationDidStop:finished:] + 62
26  QuartzCore                      0x2f8f8a0e CA::Layer::run_animation_callbacks(void*) + 230
27  libdispatch.dylib               0x37cc30ea _dispatch_client_callout + 18
28  libdispatch.dylib               0x37cc59a4 _dispatch_main_queue_callback_4CF + 264
29  CoreFoundation                  0x2d4af5b4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 4
30  CoreFoundation                  0x2d4ade80 __CFRunLoopRun + 1304
31  CoreFoundation                  0x2d41853c CFRunLoopRunSpecific + 520
32  CoreFoundation                  0x2d41831e CFRunLoopRunInMode + 102
33  GraphicsServices                0x3214f2e6 GSEventRunModal + 134
34  UIKit                           0x2fccf1e0 UIApplicationMain + 1132
35  myapp                           0x00020a16 main (main.mm:16)
36  libdyld.dylib                   0x37cd7ab2 tlv_initializer + 2

Thread 0:
0   libsystem_kernel.dylib          0x37d8e588 __semwait_signal_nocancel + 24
1   libsystem_c.dylib               0x37d09788 nanosleep$NOCANCEL + 160
2   libsystem_c.dylib               0x37d24f10 usleep$NOCANCEL + 48
3   libsystem_c.dylib               0x37d3f030 abort + 80
4   myapp                           0x001efaea uncaught_exception_handler + 22
5   CoreFoundation                  0x2d4e518a __handleUncaughtException + 578
6   libobjc.A.dylib                 0x377de924 _objc_terminate() + 172
7   libc++abi.dylib                 0x371a51b0 std::__terminate(void (*)()) + 76
8   libc++abi.dylib                 0x371a4a04 __cxa_throw + 112
9   libobjc.A.dylib                 0x377de796 objc_exception_throw + 246
10  CoreFoundation                  0x2d41e0c6 -[__NSPlaceholderArray initWithObjects:count:] + 414
11  CoreFoundation                  0x2d427a4c +[NSArray arrayWithObjects:count:] + 40
12  CoreFoundation                  0x2d45d9c0 -[NSDictionary allKeys] + 172
13  Foundation                      0x2df73336 -[NSISObjectiveLinearExpression description] + 122
14  Foundation                      0x2ddfc808 _NSDescriptionWithLocaleFunc + 84
15  CoreFoundation                  0x2d4babf4 __CFStringAppendFormatCore + 5620
16  CoreFoundation                  0x2d429d18 _CFStringCreateWithFormatAndArgumentsAux + 72
17  CoreFoundation                  0x2d4523c2 _CFLogvEx + 82
18  Foundation                      0x2de0b7ee NSLogv + 82
19  Foundation                      0x2de0b78e NSLog + 22
20  Foundation                      0x2de4a918 -[NSISEngine minimizeConstantInObjectiveRowWithHead:] + 180
21  Foundation                      0x2de4a46e -[NSISEngine optimize] + 170
22  Foundation                      0x2de461a8 -[NSISEngine withBehaviors:performModifications:] + 312
23  UIKit                           0x2fc69490 -[UIView(Hierarchy) _postMovedFromSuperview:] + 292
24  UIKit                           0x2feffb92 __UIViewWasRemovedFromSuperview + 214
25  UIKit                           0x2fc68342 -[UIView(Hierarchy) removeFromSuperview] + 266
26  UIKit                           0x2fd3cccc -[UIScrollView removeFromSuperview] + 60
27  UIKit                           0x2fd313e4 -[UINavigationController navigationTransitionView:didEndTransition:fromView:toView:] + 312
28  UIKit                           0x2fdfcb5c __49-[UINavigationController _startCustomTransition:]_block_invoke + 156
29  UIKit                           0x2fd81418 -[_UIViewControllerTransitionContext completeTransition:] + 72
30  UIKit                           0x2fe418dc __53-[_UINavigationParallaxTransition animateTransition:]_block_invoke105 + 448
31  UIKit                           0x2fca261a -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 282
32  UIKit                           0x2fca226a -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 174
33  UIKit                           0x2fca2186 -[UIViewAnimationState animationDidStop:finished:] + 62
34  QuartzCore                      0x2f8f8a0e CA::Layer::run_animation_callbacks(void*) + 230
35  libdispatch.dylib               0x37cc30ec _dispatch_client_callout + 20
36  libdispatch.dylib               0x37cc59a4 _dispatch_main_queue_callback_4CF + 264
37  CoreFoundation                  0x2d4af5b4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 4
38  CoreFoundation                  0x2d4ade80 __CFRunLoopRun + 1304
39  CoreFoundation                  0x2d41853c CFRunLoopRunSpecific + 520
40  CoreFoundation                  0x2d41831e CFRunLoopRunInMode + 102
41  GraphicsServices                0x3214f2e6 GSEventRunModal + 134
42  UIKit                           0x2fccf1e0 UIApplicationMain + 1132
43  myapp                           0x00020a16 main (main.mm:16)
44  libdyld.dylib                   0x37cd7ab4 start + 0

Thread 1:
0   libsystem_kernel.dylib          0x37d7b838 kevent64 + 24
1   libdispatch.dylib               0x37cca0d0 _dispatch_mgr_invoke + 228
2   libdispatch.dylib               0x37cc463e _dispatch_mgr_thread + 34

Thread 2 Crashed:
0   libsystem_kernel.dylib          0x37d8ec7c __workq_kernreturn + 8
1   libsystem_pthread.dylib         0x37df2e06 _pthread_wqthread + 306
2   libsystem_pthread.dylib         0x37df2cc0 start_wqthread + 4

Thread 3 name:  com.apple.NSURLConnectionLoader
Thread 3:
0   libsystem_kernel.dylib          0x37d7ba84 mach_msg_trap + 20
1   libsystem_kernel.dylib          0x37d7b87c mach_msg + 36
2   CoreFoundation                  0x2d4af55c __CFRunLoopServiceMachPort + 152
3   CoreFoundation                  0x2d4adc7c __CFRunLoopRun + 788
4   CoreFoundation                  0x2d41853c CFRunLoopRunSpecific + 520
5   CoreFoundation                  0x2d41831e CFRunLoopRunInMode + 102
6   Foundation                      0x2de5364c +[NSURLConnection(Loader) _resourceLoadLoop:] + 316
7   Foundation                      0x2dec8dc2 __NSThread__main__ + 1058
8   libsystem_pthread.dylib         0x37df4c5a _pthread_body + 138
9   libsystem_pthread.dylib         0x37df4bca _pthread_start + 98
10  libsystem_pthread.dylib         0x37df2ccc thread_start + 4

Thread 4:
0   libsystem_kernel.dylib          0x37d7ba84 mach_msg_trap + 20
1   libsystem_kernel.dylib          0x37d7b87c mach_msg + 36
2   CoreFoundation                  0x2d4af55c __CFRunLoopServiceMachPort + 152
3   CoreFoundation                  0x2d4adc7c __CFRunLoopRun + 788
4   CoreFoundation                  0x2d41853c CFRunLoopRunSpecific + 520
5   CoreFoundation                  0x2d41831e CFRunLoopRunInMode + 102
6   Foundation                      0x2de06822 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 250
7   Foundation                      0x2de57664 -[NSRunLoop(NSRunLoop) run] + 76
8   myapp                           0x001c1ffa +[AFURLConnectionOperation networkRequestThreadEntryPoint:] (AFURLConnectionOperation.m:160)
9   Foundation                      0x2dec8dc2 __NSThread__main__ + 1058
10  libsystem_pthread.dylib         0x37df4c5a _pthread_body + 138
11  libsystem_pthread.dylib         0x37df4bca _pthread_start + 98
12  libsystem_pthread.dylib         0x37df2ccc thread_start + 4

Thread 5 name:  com.apple.CFSocket.private
Thread 5:
0   libsystem_kernel.dylib          0x37d8e440 select$DARWIN_EXTSN + 20
1   CoreFoundation                  0x2d4b345e __CFSocketManager + 482
2   libsystem_pthread.dylib         0x37df4c5a _pthread_body + 138
3   libsystem_pthread.dylib         0x37df4bca _pthread_start + 98
4   libsystem_pthread.dylib         0x37df2ccc thread_start + 4

Thread 6:
0   libsystem_kernel.dylib          0x37d8ec7c __workq_kernreturn + 8
1   libsystem_pthread.dylib         0x37df2e06 _pthread_wqthread + 306
2   libsystem_pthread.dylib         0x37df2cc0 start_wqthread + 4

Thread 2 crashed with ARM Thread State (32-bit):
    r0: 0x00000004    r1: 0x00000000      r2: 0x00000000      r3: 0x00000000
    r4: 0x02bcc000    r5: 0x00060001      r6: 0x00004007      r7: 0x02bcbfe0
    r8: 0x00000000    r9: 0x00000001     r10: 0x00000000     r11: 0x00000000
    ip: 0x00000170    sp: 0x02bcbfc8      lr: 0x37df2e0b      pc: 0x37d8ec7c
  cpsr: 0x40000010

A: This crash looks like a problem with a constraints you set in your app (in a background thread ?).
In addition this looks similar (not identical) to your other reported crash: https://stackoverflow.com/questions/19114389/app-hang-and-then-crash-ios-7
So in short: your constraints setup (presumably in code) causes this problem. Most likely because your constraints reference a view that is not existing any more.
In Long:

*

*From thread 2 some code is dispatched into the main thread:
28  libdispatch.dylib               0x37cc59a4 _dispatch_main_queue_callback_4CF + 264

*A transition to another View Controller via a navigation controller did finish:
21  UIKit                           0x2fd81416 -[_UIViewControllerTransitionContext completeTransition:] + 70

*A scrollview is being removed from its superview:
18  UIKit                           0x2fd3cccc -[UIScrollView removeFromSuperview] + 60

*Constraints are being evaluated:
12  Foundation                      0x2de4a918 -[NSISEngine minimizeConstantInObjectiveRowWithHead:] + 180

*The constraints engine wants to log some error into the console:
11  Foundation                      0x2de0b78e NSLog + 22

*The constraints engine tries to generate a string:
5   Foundation                      0x2df73336 -[NSISObjectiveLinearExpression description] + 122

*An exception occurs because it tries to add a nil object to an NSArray.
This could happen if your constraint rules (done in code) reference another view that does not exist any more. You should check your constraint rules and set breakpoints to find out which one is causing the crash.


text:
Q: Does the asymptotic complexity of a multiplication algorithm only rely on the larger of the two operands? I'm taking an algorithms class and I repeatedly have trouble when I'm asked to analyze the runtime of code when there is a line with multiplication or division. How can I find big-theta of multiplying an n digit number with an m digit number (where n>m)? Is it the same as multiplying two n digit numbers?
For example, right now I'm attempting to analyze the following line of code:
return n*count/100

where count is at most 100. Is the asymptotic complexity of this any different from n*n/100? or n*n/n?

A: You can always look up here Computational complexity of mathematical operations.
In your complexity of n*count/100 is O(length(n)) as 100 is a constant and length(count) is at most 3.
In general multiplication of two numbers n and m digits length, takes O(nm), the same time required for division. Here i assume we are talking about long division. There are many sophisticated algorithms which will beat this complexity.
To make things clearer i will provide an example. Suppose you have three numbers:

*

*A - n digits length

*B - m digits length

*C - p digits length

Find complexity of the following formula:
A * B / C
Multiply first. Complexity of A * B it is O(nm) and as result we have number  D, which is n+m digits length. Now consider D / C, here complexity is O((n+m)p), where overall complexity is sum of the two O(nm + (n+m)p) = O(m(n+p) + np).
Divide first. So, we divide B / C, complexity is O(mp) and we have m digits number E. Now we calculate A * E, here complexity is O(nm). Again overall complexity is O(mp + nm) = O(m(n+p)).
From the analysis you can see that it is beneficial to divide first. Of course in real life situation you would account for numerical stability as well.

A: From Modern Computer Arithmetic:
Assume the larger operand has size
m, and the smaller has size n ≤ m, and denote by M(m,n) the corresponding
multiplication cost.
When m is an exact multiple of n, say m = kn, a trivial strategy is to cut the
larger operand into k pieces, giving M(kn,n) = kM(n) + O(kn).
Suppose m ≥ n and n is large. To use an evaluation-interpolation scheme,
we need to evaluate the product at m + n points, whereas balanced k by k
multiplication needs 2k points. Taking k ≈ (m+n)/2, we see that M(m,n) ≤ M((m + n)/2)(1 + o(1)) as n → ∞. On the other hand, from the discussion
above, we have M(m,n) ≤ ⌈m/n⌉M(n)(1 + o(1)).


text:
Q: Make one last change to NSDocument before app terminates/window closes? I have a basic NSDocument-based app. I need to make one last change to the document when:

*

*The user closes the document's window

*The user terminates the app

Why?
The document window contains an NSTextField. Usually text entered into this text field is committed to the document's model after the user presses Enter (via textDidEndEditing(_:)).
Let's assume the user typed some text, but does not press Enter. Instead he presses Cmd-W or Cmd-Q to close the document window or terminate the app altogether.
textDidEndEditing is not called so I check if the text field contains changes and try to update the document myself.
❌ Here is where it gets tricky. The following results in a deadlock on NSDocument.performActivityWithSynchonousWaiting:
override func viewWillDisappear() {
    super.viewWillDisappear()

    undoManager?.disableUndoRegistration()
    textField.commitEditing() // Updates the model

    document.updateChangeCount(.changeDone)
}

I managed to work around the deadlock by not hooking into viewWillDisappear, but into NSDocument.canClose(withDelegate delegate: Any, shouldClose shouldCloseSelector: Selector?, contextInfo: UnsafeMutableRawPointer?).
✅ This code causes the changes to be saved when the user closes the document window:
override func canClose(withDelegate delegate: Any, shouldClose shouldCloseSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {

    undoManager?.disableUndoRegistration()
    textField.commitEditing() // Updates the model

    updateChangeCount(.changeDone)

    super.canClose(withDelegate: delegate, shouldClose: shouldCloseSelector, contextInfo: contextInfo)
}

.
❓Unfortunately, the above is not called when the user terminates the app. I tried updating my document in applicationWillTerminate() -- did not work. I also tried overriding applicationShouldTerminate() and delaying termination for 3 seconds. I can see the document's window being marked as "edited", but changes are not saved.
How can I make a last change to NSDocument right before the app terminates and have it saved automatically?

A: For reference: I don't think it is possible to make a last change to NSDocument while the app is being terminated. The document architecture is simply not designed that way (see https://www.mail-archive.com/cocoa-dev@lists.apple.com/msg107739.html)
At the time the app is terminating, the document's windows have been closed and window controllers released.
I eventually solved this problem by changing the design of my app to record changes to the document as the user types. I use a new instance of UndoManager and manually call NSDocument.updateChangeCount(.changeDone) to register my changes out of the undo/redo chain. When the user finally commits changes by pressing Enter, I use the document's undo manager to register the change.


text:
Q: What could cause "dh key too small" error? I coded a program that uses openssl, and dockerized it.
But when I tried it with python:3.7 base image, the below error occured:

[SSL: DH_KEY_TOO_SMALL] dh key too small (_ssl.c:1108)

I managed to solve this by lowering security level in /etc/ssl/openssl.cnf file.
echo "CipherString=DEFAULT@SECLEVEL=1" >> /etc/ssl/openssl.cnf
But what exactly does this error mean?
Is this a server-side problem, which I cannot handle in my code?
I'm just not feeling that comfortable with resolving a problem by just lowering a security level.
What should I consider when changing that security level?
Thanks :)

A: The best explanation I found is on Debian wiki at https://wiki.debian.org/ContinuousIntegration/TriagingTips/openssl-1.1.1 which says:

In Debian the defaults are set to more secure values by default. This
  is done in the /etc/ssl/openssl.cnf config file. At the end of the
  file there is:
[system_default_sect]
MinProtocol = TLSv1.2
CipherString = DEFAULT@SECLEVEL=2

This can results in errors such as:
dh key too small
ee key too small
ca md too weak

This is caused by the SECLEVEL 2 setting the security level to 112
  bit. This means that RSA and DHE keys need to be at least 2048 bit
  long. SHA-1 is no longer supported for signatures in certificates and
  you need at least SHA-256. Note that CAs have stopped issuing
  certificates that didn't meet those requirements in January 2015, and
  since January 2017 all valid CA certificates should meet those
  requirements. However there are certificates generated by private CAs
  or that are in a test suite that do not meet those requirements.
SECLEVEL 1 was the default in previous versions and is at the 80 bit
  security level, requiring a 1024 bit RSA key.

The problem of "dh key too simple" is fully detailed at https://weakdh.org/
It says:

Diffie-Hellman key exchange is a popular cryptographic algorithm that
  allows Internet protocols to agree on a shared key and negotiate a
  secure connection. It is fundamental to many protocols including
  HTTPS, SSH, IPsec, SMTPS, and protocols that rely on TLS.
We have uncovered several weaknesses in how Diffie-Hellman key
  exchange has been deployed:
[..]
What Should I Do? If you run a server…
If you have a web or mail server, you should disable support for
  export cipher suites and use a 2048-bit Diffie-Hellman group.

What to do?
Try not to change SECLEVEL. It is better to keep it systemwide as it is (SECLEVEL=2), but try instead to fix the specific connection problem you have.
First step is to contact the administrator of the service you are trying to connect to over TLS, and give it the details above so that he does the necessary change to not be anymore in the "weak dh" vulnerability.
If that proves impossible, or in the mean time before resolution, just set, for the connection, the "SSL" ciphers to the value of DEFAULT@SECLEVEL=1. This unfortunately lowers the security but at least it impacts only this specific connection and not your whole system. You do not need to hardcode the list of ciphers the value above will make things work exactly as before.
I had that exact same problem and resolved it that way, because it couldn't convince the remote party to change its TLS server or provide certificates at least using RSA 2048 bits.

A: This is an issue with the program if you have not disallowed weak and vulnerable ciphers.
DO NOT reduce the seclevel.
A small DH key can expose the TLS communication to vulnerabilities such as LogJam.
You would need to specify a strong cipher set in your program. For a quicj test try "HIGH:!DH:!aNULL"
You could also specify a strong set of cipher suites such as in:
"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256"
But for this to happen, the server needs to be hardened to support these suites as well. I'm assuming that is already the case and your local openssl is the latest as well and supports these.
Courtesy on cipher suites list: https://www.acunetix.com/blog/articles/tls-ssl-cipher-hardening/

A: Error: error:141A318A:SSL routines:tls_process_ske_dhe:dh key too small

*

*We encoountered similar error in Cloudera 7.6.1,  while
authenticating LDAP user in Hue and other services.  Upon
investigation we found below specific cipher settings was excluded in
our server settings as a part of hardening.  Once we include the
below mentioned cypher, issue was resolved and we were able to
authenticate user via LDAP/AD.

Cipher => AES-256-CBC
Below is the custom cipher settings applied in the server to exclude weak ciphers as pert of hardening and remediation's.
This is custom file created in our environment
ls -l /etc/crypto-policies/policies/modules/NON-CBC.pmod

Before:
cat /etc/crypto-policies/policies/modules/NON-CBC.pmod
tls_cipher = -AES-256-CBC -AES-128-CBC
cipher = -AES-128-CBC -AES-256-CBC -CAMELLIA-256-CBC -CAMELLIA-128-CBC
ssh_cipher = -AES-128-CBC -AES-256-CBC

After:
vi /etc/crypto-policies/policies/modules/NON-CBC.pmod
tls_cipher =  -AES-128-CBC
cipher = -AES-128-CBC  -CAMELLIA-256-CBC -CAMELLIA-128-CBC
ssh_cipher = -AES-128-CBC

update-crypto-policies --show

update-crypto-policies --set DEFAULT:NON-CBC

systemctl restart sshd ; systemctl status sshd

Make sure AES-256-CBC included in the below file,
ls -l /etc/crypto-policies/back-ends/opensshserver.config


text:
Q: json could not be parsed - import csv and convert to vcf i have found a python script to convert csv to vcf (vcard) but it does not work how i expect it. I am new to python an programming, so i think i need your help to solve the problem.
Here is the Script:
#!/usr/bin/env python

"""
    Author : Mridul Ahuja (original author)
    Description : A small command line tool to convert CSV files to VCard files

"""

import os
import sys
import csv
import json

def print_card(target, values):
    target.write('BEGIN:VCARD' + "\n")
    target.write('VERSION:3.0' + "\n")
    target.write('N:' + values["name"] + ';' + "\n")
    target.write('FN:' + values["full"] + "\n")
    target.write('NICKNAME:' + values["nick"] + "\n")
    target.write('X-MAIDENNAME:' + values["maiden"] + "\n")
    target.write('ADR;type=HOME;type=pref:;;' + values["street"] + ';' + values["city"] + ';;' + values["zip"] + ';' + values["country"] + "\n")
    target.write('TEL;HOME;VOICE:' + values["tel"].replace("'", '') + "\n")
    target.write('TEL;type=CELL;type=VOICE;type=pref:' + values["mobile"].replace("'", '') + "\n")
    target.write('EMAIL:' + values["mail"] + "\n")
    target.write('BDAY:' + values["bday"] + "\n")
    target.write('ORG:' + values["org"] + "\n")
    target.write('ROLE:' + values["role"] + "\n")
    target.write('URL:' + values["url"] + "\n")
    target.write('NOTE: ' + values["note"] + "\n")
    target.write('END:VCARD' + "\n")
    target.write("\n")

def convert_to_vcard(input_file, single_output, input_file_format, target):

    if not os.path.exists('csv2vcf'):
        os.makedirs('csv2vcf')

    FN = input_file_format['name']-1 if 'name' in input_file_format else None
    GIVEN = input_file_format['given']-1 if 'given' in input_file_format else None
    SURNAME = input_file_format['surname']-1 if 'surname' in input_file_format else None
    PREFIX = input_file_format['prefix']-1 if 'prefix' in input_file_format else None
    NICKNAME = input_file_format['nickname']-1 if 'nickname' in input_file_format else None
    MAIDEN = input_file_format['maiden']-1 if 'maiden' in input_file_format else None
    CITY = input_file_format['city']-1 if 'city' in input_file_format else None
    STREET = input_file_format['street']-1 if 'street' in input_file_format else None
    COUNTRY = input_file_format['country']-1 if 'country' in input_file_format else None
    ZIP = input_file_format['zip']-1 if 'zip' in input_file_format else None
    ORG = input_file_format['org']-1 if 'org' in input_file_format else None
    TEL = input_file_format['tel']-1 if 'tel' in input_file_format else None
    MOBILE = input_file_format['mobile']-1 if 'mobile' in input_file_format else None
    URL = input_file_format['url']-1 if 'url' in input_file_format else None
    BDAY = input_file_format['bday']-1 if 'bday' in input_file_format else None
    ROLE = input_file_format['role']-1 if 'role' in input_file_format else None
    EMAIL = input_file_format['email']-1 if 'email' in input_file_format else None
    NOTE = input_file_format['note']-1 if 'note' in input_file_format else None

    i = 0

    with open(input_file, 'r') as source_file:
        dialect = csv.Sniffer().sniff(source_file.read(1024))
        source_file.seek(0)
        reader = csv.reader(source_file, dialect)
        if single_output:  # if single output option is selected
            vcf = open('csv2vcf/all_contacts.vcf', 'w')

        for row in reader:
            N_VAL = row[SURNAME] if SURNAME is not None else ''
            N_VAL = N_VAL + ";" + row[GIVEN] if GIVEN is not None else ''
            N_VAL = N_VAL + ";;" + row[PREFIX] if PREFIX is not None else ''
            values = {
                "name": N_VAL,
                "full": row[FN] if FN is not None else row[GIVEN] + " " + row[SURNAME],
                "nick": row[NICKNAME] if NICKNAME is not None else '',
                "maiden": row[MAIDEN] if MAIDEN is not None else '',
                "zip": row[ZIP] if ZIP is not None else '',
                "city": row[CITY] if CITY is not None else '',
                "street": row[STREET] if STREET is not None else '',
                "country": row[COUNTRY] if COUNTRY is not None else '',
                "org": row[ORG] if ORG is not None else '',
                "tel": row[TEL] if TEL is not None else '',
                "mobile": row[MOBILE] if MOBILE is not None else '',
                "url": row[URL] if URL is not None else '',
                "bday": row[BDAY] if BDAY is not None else '',
                "role": row[ROLE] if ROLE is not None else '',
                "mail": row[EMAIL] if EMAIL is not None else '',
                "note": row[NOTE] if NOTE is not None else ''
            }

            # for the user
            print_card(target, values)
            print ('----------------------')

            if not single_output:  # default ( multi-file output )
                vcf = open('csv2vcf/' + values["full"] + '_' + values["mail"] + ".vcf", 'w')

            print_card(vcf, values)

            if not single_output:  # default ( multi-file output )
                vcf.close()
            i += 1

    vcf.close()
    print (str(i) + " VCARDS written")
    print ('----------------------')

def main(args):
    args_len = len(args)

    if args_len < 3 or args_len > 4:
        print("Usage:")
        print(args[0] + " CSV_FILE_NAME [ -s | --single ] INPUT_FILE_FORMAT")
        sys.exit()

    if args_len == 3:
        input_file = args[1]

        try:
            input_file_format = json.loads(args[2])
        except Exception:
            print ('\033[91m'+"ERROR : json could not be parsed"+'\033[0m')
            sys.exit()

        single_output = 0
    elif args_len == 4:
        input_file = args[1]

        if args[2] == '-s' or args[2] == '--single':
            single_output = 1
        else:
            print ('\033[91m'+"ERROR : invalid argument `" + args[2] + "`"+'\033[0m')
            sys.exit()

        try:
            input_file_format = json.loads(args[3])
        except Exception:
            print ('\033[91m'+"ERROR : json could not be parsed"+'\033[0m')
            sys.exit()

    if not os.path.exists(input_file):
        print ('\033[91m'+"ERROR : file `" + input_file + "` not found"+'\033[0m')
        sys.exit()

    convert_to_vcard(input_file, single_output, input_file_format, sys.stdout)

if __name__ == '__main__':
    main(sys.argv)

I tried to use this script in that way:
python csv2vcf.py tel.csv -s '{"name":1, "surname":2, "org":3}'

and get the following message: ERROR: json could not be parsed
Structure of tel.csv is following:
"Vorname";"Nachname";"Firma";"Tel";"Mobil";"Land";"Kundennummer";
"Max";"Mustermann";;"+4912345678";;"Deutschland";"1234";

I tried without "" in csv and , instead of ; but nothing works.
Edit: I have modified the script to get better Exception and Error Message from the programm and that shows:
Traceback (most recent call last):
  File "C:\Scripts\csv2vcf\csv2vcf.py", line 156, in <module>
    main(sys.argv)
  File "C:\Scripts\csv2vcf\csv2vcf.py", line 143, in main
    input_file_format = json.loads(args[3])
  File "C:\Program Files\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files\Python310\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

I hardcoded the json.loads and then it works, but how can i use the orignal variable instead of hardcoding this?
 #input_file_format = json.loads(args[3])
 input_file_format = json.loads('{"given":1, "surname":2, "org":3, "tel":4, "mobile":5}')

args3 Printout value: {given:1, surname:2, org:3, 4, mobile:5}
This is the problem, if i use args[3] Variable there are no names enclosed in double quotes.
Any idea how to solve this?
Thanks in advance!

A: I have found the solution, the trick is to escape the quotes to preserve them inside the script. So this works fine:
python csv2vcf.py tel.csv -s '{\"name\":1, \"surname\":2, \"org\":3, \"tel\":4, \"mobile\":5}'


text:
Q: tfma.view.render_slicing_metrics not working I am trying to visualize model results using tfma.view.render_slicing_metrics. I am getting the results with tfma.load_eval_result(tfma_artifact.uri) and I am able to print the results.
[EvalResult(slicing_metrics=[((('trip_start_hour', 2),), {'precision': {'doubleValue': 0.6666666865348816}, 'accuracy_baseline': {'doubleValue': 0.8188405632972717},
...................................
'predictioexample_weight_metric_key='post_export_metrics/example_count', num_bootstrap_samples=1))]

But when I try to visualize the results with tfma.view.render_slicing_metrics(tfma.load_eval_result(tfma_artifact.uri)) I am seeing a empty visualization.
import tensorflow_model_analysis as tfma
tfma_artifact = store.get_dest_artifact_of_type(11,'ModelEvalPath')
tfma.load_eval_result(tfma_artifact.uri)
tfma.view.render_slicing_metrics(tfma.load_eval_result(tfma_artifact.uri))


text:
Q: Simple build process automation on Windows I'm not a huge fan of tools like Ant, but they are certainly useful. In a current C++ project I have no automated build process at all - I simply build my working dir using Visual studio, zip up the /bin folder and send it out for installation. The project is small enough this does work OK, but it's totally reliant on me knowing the project inside out.
I'd like a system which can do steps like:

*

*update multiple SVN working dirs to a specified version (or default to Head)

*run doxygen (or similar tool) to get API docs up to date

*commit the API docs to some SVN repo

*build several projects in the right order

*copy some stuff about, delete unwanted files

*package files/folders into a zip/folder named based on a user-specified version, or found from a file/SVN

Free is important. Easy to use is another. Windows is essential, and that doesn't include cygwin options.
It had crossed my mind you could probably do this using a .bat file, is that a viable option on what is still quite a small project (1-4 developers)?

A: Hudson is very easy to setup, install and run, and has no problems running in a windows environment. You don't have to use it for continuous integration, it will happily do builds only when you tell it to.
Hudson has native support for executing windows batch scripts and will happily work NANT or cmake via plugins. If there isn't already a plugin for something you want to do, you can pretty easily accomplish it, if it could normally be done from the command line.
Please note: the Hudson project has been renamed Jenkins

A: cmake is the tool of choice for any os these days. Nothing else comes close. You have to type a high level description of your code and cmake will generate VS solution/projects, and makefiles for all unices or cygwin.
NSIS: tons of open source/closed source projects use NSIS to create installers for windows -- its not bad, and the builder can be easily run from the command line -- so you can integrate it with cmake.

A: If you use Visual Studio (only) anyway, you could use its built-in build process in batch mode (type devenv /? in your cmd). That would be sufficient to build your C++ project and will resolve all C++ dependencies, which are hardest part.
Other things you could easily perform from batch script.
Also please read this 2 articles:
http://gamesfromwithin.com/the-quest-for-the-perfect-build-system
http://gamesfromwithin.com/the-quest-for-the-perfect-build-system-part-2

A: I would recommend CMake:
http://www.cmake.org/
This is a pretty standard build system if you are used to dependency based build systems.
If you are more experimental (and enjoy coding ruby) Rake is great alternative:
http://rake.rubyforge.org/
Martin Fowler has a great introduction to the tool here: http://martinfowler.com/articles/rake.html

A: If you have a spare box to spare I'd suggest Nant and [CruiseControl.net].  You don't have to necessarily use it for continuous integration you can set your builds to run [only when forced].   Both are open source, have native support for SVN, and are fairly easy to use.  I've used Nant & CruiseControl.Net for each thing you have listed except the doxygen task.  Even without the spare box I'd suggest using Nant to automate your way out of what looks like a long series of manual tasks.

A: Visual Studio still ships with a copy of Nmake, which is a classic build-by-dependency-rules tool.  I can build your Visual Studio projects using devenv  , and also do lots of other things.  Anything you can do with a command line, you can do with nmake.  And it has a pretty good macro language.

A: Use http://www.finalbuilder.com as your buildserver, easy, user friendy and best of all, No XML hacking!


text:
Q: how to float element without considering elements height I have a menu including some ul and li.
how can I float ul's to left or right but not depend on previous element height.
screen shot:

for example men's shoes are not in a right place.

A: My guess is that you're looking for something more like http://masonry.desandro.com/ . Float actually won't get you the same effect.

A: You will have to wrap each row of floated elements in like a
 or something. Like this:


text:
Q: How to read a variable width white space string table into a panda dataframe? I am a newbie to pandas and trying to read a complex string into a dataframe. The problem I am having is the data gets read in character by character. What do I have to do to get this data read in so the dataframe captures the rows and columns? Much appreciated!
Here is what one line looks like:
1  85  58  72   6   0   7 0.00  0.0    0  6.7 15 230   M    M   3        19 240

Here is what I have tried so far:
    import urllib2
    import math
    import json
    import pandas as pd
    from pandas import Timestamp
    import os, sys
    import re
    import numpy as np
    from datetime import datetime, timedelta
    import csv

    sites = {'dlh':'1'}

    prdurl = 'https://api.weather.gov/products/types/cf6/locations/'
    cf6url = 'https://api.weather.gov/products/'

    current_date = datetime.now()-timedelta(days=1)
    current_day = current_date.strftime('%d')

    def make_request(url,params):
        req = urllib2.Request(url+params)
        try:
            response = urllib2.urlopen(req)
            return json.loads(response.read())
        except urllib2.HTTPError as error:
            if error.code == 400: print error.msg

    def main():

        for id in sites:
            apijson = make_request(prdurl,id)
            for key in apijson:
                if key != '@context':
                    webjson  = apijson['@graph']
                    for x in webjson:
                        valid = x['issuanceTime']
                        date_obj = datetime.strptime(valid,'%Y-%m-%dT%H:%M:%S+00:00')
                        day = date_obj.strftime('%d')
                        if current_day == day:
                            newparam = x['id']
        cf6json = make_request(cf6url,newparam)
        for y in cf6json:
            if y == 'productText':

                cf6data = cf6json['productText']
                for line in cf6data.splitlines():
                if line.startswith('==='):
                    count = count + 1
                if count == 2:
                    df = pd.DataFrame.from_records(line)
                    print df
main()

A: You can start with this code
if you have data.txt like this :
col1 col2
===================
aa bb
===================
jjjjjjj kkkkkkkk

Then, you can use skiprows to skip some rows, and separator is the space ( sep=" ")
import pandas as pd
data = pd.read_csv('data.txt', sep=" ", header=None,skiprows=[1,3])
data.columns = ["col1","col2"]
data

Result :
    col1    col2
0   col1    col2
1   aa  bb
2   jjjjjjj kkkkkkkk

Regarding the very specific code that you added. If you want to read lines one by one, then for each one you can decide what to ignore and when. Also, using split and expand=True. "When using expand=True, the split elements will expand out into separate columns"
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html
    cf6data = cf6json['productText']
    start = False
    for line in cf6data.splitlines():

        if start or "DY MAX" in line:
            start = True
            s = pd.Series(line)
            line = s.str.split(expand=True)
            Results = Results.append(line,ignore_index=True)
            print(Results)

Play with this code a little bit, clean some lines and it should work! :)

A: Step 1: Get the data:
import requests

response = requests.get('https://api.weather.gov/products/16a535da-eb2c-4580-9725-b536890e923d')
data = response.json()['productText']

Step 2: Clean and reshape the data:
Split it into a list and remove '':
data_list = data.split('\n')
data_clean = list(filter(lambda x: x != '', data_list))

Write the relevant data to a csv:
from pathlib import Path

f = Path.cwd() / 'weather.csv'

with f.open(mode='w') as wf:
    count = 0
    for line in data_clean:
        if line.startswith('==='):
            count += 1
        if (count == 2 and not line.startswith('===')) or (line.startswith('DY MAX')):
            wf.write(f'{line}\n')

Step 3: Create the DataFrame:
df = pd.read_csv('weather.csv', sep='\\s+')

Final:

*

*It's always about getting the data into the correct form


text:
Q: Error while integrating a deleted file in perforce A parent project is throwing the following error when trying to integrate a child project.
Exception: < FILE > - can't integrate (already opened for delete)
Under what scenario does this occur?

A: When Perforce integrates changes, it tries to resolve the incoming changes in the files in the local workspace.  This exception is basically saying that it can't attempt to resolve the changes for the given file, since the file has been marked as being deleted on the local workspace, so it has no place to resolve it.
There are flags you can pass to the integrate command to allow the integration to proceed anyway.  However, I've found it's generally not a good idea to integrate changes on top of in-progress changes, so I would recommend finishing (or shelving) your in-progress changes, then attempting the integration.

A: This question comes up first on google when searching for "already opened for delete", so I thought I might post a way around this if you're not integrating, just trying to undo your own delete:
cp file file.bak  # Make a backup of the file
p4 revert file    # Revert the file
mv file.bak file  # Recover from backup
p4 edit file      # Open the file for edit


text:
Q: GitHub push to Azure website I have a GitHub repo that I want Azure to monitor for changes and get latest when it is updated.  I am at the point in the Deployments tab where I can "Associate a GitHub Repository".  When I click the "Authorize Windows Azure" link, a dialog pops and some of my repos are available, but the repo I want to publish is not listed.
What drives the repos that appear in this dialog?

A: Only public repositories are supported at the moment (this might change soon).


text:
Q: why it always come to catch block and not performing the line "cmd.ExecuteNonQuery();" here is my code
protected void Button2_Click(object sender, EventArgs e)
{
    try
    {
        string constr = @"Data Source=ADMIN\LOCALHOST;Initial Catalog=maha;Integrated Security=True";
        using (SqlConnection con = new SqlConnection(constr))
        {

            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            string query = "Insert into [dbo].[student] ([ID],[NAME],[DOB],[GENDER]) Values ('@id','@name','@dob','@gender')";

            Label3.Text = "execute";

            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@id", TB1.Text);
                cmd.Parameters.AddWithValue("@name", TB2.Text);
                cmd.Parameters.AddWithValue("@dob", TB3.Text);
                cmd.Parameters.AddWithValue("@gender", rm);
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    {
        throw new Exception(ex.ToString());
    }

}

protected void Button3_Click(object sender, EventArgs e)
{
    try
    {
        string constr = @"Data Source=ADMIN\LOCALHOST;Initial Catalog=maha;Integrated Security=True;";
        using (SqlConnection con = new SqlConnection(constr))
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            string query = "Update [dbo].[student] set [ID]=@id,[NAME]=@name, [DOB]=@dob," +
                                "[GENDER]=@gender Where [ID]=@id";
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@id", TB1.Text);
                cmd.Parameters.AddWithValue("@name", TB2.Text);
                cmd.Parameters.AddWithValue("@dob", TB3.Text);
                cmd.Parameters.AddWithValue("@gender", rm);
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    {
        throw new Exception(ex.ToString());
    }
}

A: Refer this coding. if any doubt let me know
cmd.Parameters.AddWithValue("@dob", DateTime.Parse( TB3.Text)));


text:
Q: Is there any way to use weekview in Xamarin.Plugin.Calendar I want to use week view with Xamarin.Plugin.Calendar.
Is there any way to use week view with using Xamarin.Plugin.Calendar

A: I use
https://help.syncfusion.com/xamarin/calendar/display-modes#week-view
Syncfusion one is free if you qualify for the community license.


text:
Q: Symfony 4 - Adding childs of CollectionType Form with Jquery not submitted I have a form on my entity 'OrdreMission' that has childrens entities 'OrdreMissionFraisDivers' with a CollectionType :
OrdreMission.php (the parent class)
/**
 * @ORM\Entity(repositoryClass="App\Repository\OrdreMissionRepository")
 */
class OrdreMission
{
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\OrdreMissionFraisDivers", mappedBy="ordreMission",
    cascade={"persist"})
     */
    private $fraisDivers;

    /**
     * @return Collection|OrdreMissionFraisDivers[]
     */
    public function getFraisDivers(): Collection
    {
        return $this->fraisDivers;
    }

    public function addFraisDiver(OrdreMissionFraisDivers $fraisDivers): self
    {
        $this->fraisDivers[] = $fraisDivers;
        $fraisDivers->setOrdreMission($this);

        return $this;
    }

    public function removeFraisDiver(OrdreMissionFraisDivers $fraisDivers): self
    {
        if ($this->fraisDivers->contains($fraisDivers)) {
             $this->fraisDivers->removeElement($fraisDivers);
            // set the owning side to null (unless already changed)
            if ($fraisDivers->getOrdreMission() === $this) {
            $fraisDivers->setOrdreMission(null);
            }
        }

        return $this;
    }
}

OrdreMissionFraisDivers.php (the child class)
class OrdreMissionFraisDivers
{
    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\OrdreMission", inversedBy="fraisDivers")
     * @ORM\JoinColumn(nullable=false)
     */
     private $ordreMission;

    public function getOrdreMission(): ?OrdreMission
    {
        return $this->ordreMission;
    }

    public function setOrdreMission(?OrdreMission $ordreMission): self
    {
        $this->ordreMission = $ordreMission;

        return $this;
    }
}

OrdreMissionType.php (form class of OrdreMission)
class OrdreMissionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('fraisDivers', CollectionType::class, [
            'label' => false,
            'entry_type' => OrdreMissionFraisDiversType::class,
            'entry_options' => ['label' => false],
            'allow_add' => true,
            'by_reference' => false,
        ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => OrdreMission::class
        ]);
    }
}

OrdreMissionFraisDiversType.php (form class of OrdreMissionFraisDivers)
class OrdreMissionFraisDiversType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options){
        $builder->add('libelle', TextType::class, [
            'label' => false
        ]);
        $builder->add('montantJour', MoneyType::class, [
            'label' => false,
            'mapped' => false,
            'disabled' => true,
            'attr' => ['class' => 'montantJour']
        ]);
        $builder->add('montant', MoneyType::class, [
            'label' => false,
            'attr' => ['class' => 'montantTotal']
        ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => OrdreMissionFraisDivers::class,
        ]);
    }
}

Creation of the form in my controller
    $odm = new OrdreMission();
    $odmtpe = new OrdreMissionFraisDivers();
    $odmtpe->setLibelle('test')->setMontant(15);
    $odm->addFraisDiver($odmtpe); //i add a child before creating the form to test the mapping

    $form = $this->createForm(OrdreMissionType::class, $odm,[
        'user' => $user,
        'affairesOdm' => $affairesForm,
        'method' => 'PUT'
    ]);

    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()) {
        $odm = $form->getData();
        $odm->setEtat('C');
        $odm->setDemandeur($demandeur);
        $odm->setSalarie($user);

       dd($odm);

        $em = $this->getDoctrine()->getManager();
        $em->persist($odm);
        $em->flush();
    }

    return $this->render('pages/pointage/odm/creation.html.twig', [
        'form' => $form->createView(),
    ]);

My View (i'm using a prototype to dynamiclly add childs in my form, the problem come from here)
{% macro printFraisDiversRow(fraisDiversForm) %}
    {{ form_row(fraisDiversForm.libelle) }}
    {{ form_row(fraisDiversForm.montantJour) }}
    {{ form_row(fraisDiversForm.montant) }}
{% endmacro %}

            Type d'indemnité
            Montant (€/jour)
            Montant (€/mission)
            Action

My problem is : When I add a new child to my form, this one is not submitted. I think this is a problem with my prototype or my macro but I don't see what I forgot to do.
The child that I declared in my controller before creating the form is sent when I submit this one, as you can see in the debug picture.

Debug after the form submission :

Edit : Here's the DOM generated with the children at the bottom of the form :
<fieldset class="form-group">

        <fieldset class="form-group">

                    <input type="text" id="ordre_mission_fraisDivers_0_libelle" name="ordre_mission[fraisDivers][0][libelle]" required="required" class="form-control" value="test">

                         <input type="text" id="ordre_mission_fraisDivers_0_montantJour" name="ordre_mission[fraisDivers][0][montantJour]" disabled="disabled" required="required" class="montantJour form-control">

                              €

                         <input type="text" id="ordre_mission_fraisDivers_0_montant" name="ordre_mission[fraisDivers][0][montant]" required="required" class="montantTotal form-control" value="15,00">

                                  €

             </fieldset>

 </fieldset>

The DOM generated on the table (after adding 1 child) :

                    <input type="text" id="ordre_mission_fraisDivers_1_libelle" name="ordre_mission[fraisDivers][1][libelle]" required="required" class="form-control">

                        <input type="text" id="ordre_mission_fraisDivers_1_montantJour" name="ordre_mission[fraisDivers][1][montantJour]" disabled="disabled" required="required" class="montantJour form-control">

                             €

                        <input type="text" id="ordre_mission_fraisDivers_1_montant" name="ordre_mission[fraisDivers][1][montant]" required="required" class="montantTotal form-control">

                             €

                <button type="button" class="btn btn-outline-danger">

                </button>

            <button type="button" class="btn btn-secondary add_tag_link">

                Ajouter un frais
            </button>


text:
Q: Is it possible to make a drag-and-drop batch script that copies files? I'm trying to make a batch script with Hackoo's answer on this question to repurpose it for copying files instead of opening them. Is this something that can be done using a similar structure? Here is my revision of the script:
@echo off
Title Drag and drop a font to install.
Mode con cols=60 lines=3
IF [%1] EQU [] Goto:Error
CD /D "%~1">nul 2>&1 && Goto:Explorer_Folder || Goto :OpenFile
Exit /b

:OpenFile <File>
COPY "Drag and drop your font here..." "C:\Program Files\Common Files\Adobe\Fonts" "%~1"
Exit /b

:Explorer_Folder <Folder>
Explorer "%~1"
Exit /b

:Error
Color 0C & echo(
ECHO    You must drag and drop a font into this tool!
Timeout /T 5 /NoBreak >nul
Exit /b


text:
Q: Meaning of files under /etc/lightdm/lightdm.conf.d/? I installed Xubuntu from an .iso image. Then I installed ubuntu-desktop package from the repositories and removed xubuntu.
However, the only file under /etc/lightdm/lightdm.conf.d is 10-xubuntu.conf. Now that I have removed xubuntu and I am using ubuntu, shouldn't this file be gone? Shouldn't it be 10-ubuntu.conf instead?
My question is:
What do the files under /etc/lightdm/lightdm.conf.d/ do?
Is it safe for me to replace 10-xubuntu.conf with 10-ubuntu.conf?

A: The contents of 10-xubuntu.conf are:
[SeatDefaults]
user-session=xubuntu

In contrast, Ubuntu (that is to say, ubuntu-desktop) usually keeps configuration for LightDM in /usr/share/lightdm/lightdm.conf.d, where you should find a 50-ubuntu.conf:
$ cat /usr/share/lightdm/lightdm.conf.d/50-ubuntu.conf
[SeatDefaults]
user-session=ubuntu

If this files exists, and has the same contents, you can go ahead and uninstall xubuntu-default-settings, the package that owns 10-xubuntu.conf:
sudo apt-get purge xubuntu-default-settings

That would be cleaner than deleting or replacing 10-xubuntu.conf.


text:
Q: React renders repeatedly on event I'm using sockets in my website and there's an event where one user can send a word to the server, which emits (art-addpic) an image URL corresponding to that word to everyone, but only the user with isArtist=true gets to respond to the event.
The artist's page is supposed to update an existing list of image URLs (optionImages) with the received URL once. But when the event is received, all images in the list are replaced by the received URL. Furthermore, the component rendering the list of images ArtBoard is not re-rendered with updated URLs.
I'm new to React. Where am I going wrong?
I've checked the server and the event art-addpic is broadcasted only once.
Arena.js: (The webpage where this happens):
import React, { useEffect, useState } from "react";
import Leaderboard from "../comps/Leaderboard";
import { io } from "socket.io-client";
import Service from "../Service";
import DetBoard from "../comps/DetBoard";
import ArtBoard from "../comps/ArtBoard";
const username = "Nick"
const roomkey="abc"
let userid;
if(localStorage.getItem('userid')){
    userid = localStorage.getItem('userid')
}
else{
    userid = Service.makeid(5);
    localStorage.setItem('userid', userid);
}
function useForceUpdate(){
    const [value, setValue] = useState(0); // integer state
    return () => setValue(value => value + 1); // update the state to force render
}
// const [userid,setUserId] =
const socket = io('http://localhost:3001', {query:"username="+username+"&roomkey="+roomkey+"&userid="+userid});
const Arena = (props)=>{
    const [isArtist, setIsArtist] = useState(false);
    const [focusImage, setFocusImage] = useState('https://i.imgur.com/61HsZCU.jpeg')
    const [players, setPlayers] = useState([]);
    const [optionImages, setOptionImages] = useState([
        'https://i.imgur.com/61HsZCU.jpeg',
        'https://i.imgur.com/61HsZCU.jpeg',
        'https://i.imgur.com/61HsZCU.jpeg',
        'https://i.imgur.com/61HsZCU.jpeg',
        'https://i.imgur.com/61HsZCU.jpeg'
    ])
    useEffect(()=>{
        socket.on('connect',()=>{
            console.log("connected")
        })
        socket.on('players', (data)=>{
            data = JSON.parse(data)
            console.log(data)
            setPlayers(data)
        })
        socket.on('artist', (data)=>{
            if(data===userid){
                console.log('You are an artist, Mr White.')
                setIsArtist(true);
            }
            else{
                setIsArtist(false);
            }
        })
        socket.on('art-addpic', (data)=>{
            data = JSON.parse(data)
            console.log(data)
            let tempOps =optionImages;
            tempOps.splice(0, 1);
            tempOps.push(data.url)
            console.log(tempOps)
            setOptionImages(tempOps);
        })
    }, [
        optionImages
    ]);
    if(isArtist){
        return(

            <Leaderboard players={players}></Leaderboard>
            {/* <ArtBoard></ArtBoard> */}
            <ArtBoard socket={socket} focusImage={focusImage} optionImages={optionImages} setOptionImages={setOptionImages}/>

        );
    }
    else{
        return (

            <Leaderboard players={players}></Leaderboard>
            {/* <ArtBoard></ArtBoard> */}
            <DetBoard socket={socket} focusImage={focusImage}/>

        );
    }
}
export default Arena;

A: You've at least a few issues:

*

*No clean up function returned from the useEffect hook to unsubscribe the socket connections, so they remain open.

*optionImages state mutations.

*Updating the optionImages state retriggers the useEffect callback which creates more subscriptions.

Hook Code
useEffect(() => {
  socket.on('connect', () => {
    console.log("connected");
  });

  socket.on('players', (data) => {
    data = JSON.parse(data);
    console.log(data);
    setPlayers(data);
  });

  socket.on('artist', (data) => {
    if (data === userid) {
      console.log('You are an artist, Mr White.');
      setIsArtist(true);
    } else {
      setIsArtist(false);
    }
  });

  socket.on('art-addpic', (data) => {
    data = JSON.parse(data);
    console.log(data);
    let tempOps = optionImages; // (2) tempOps is reference to optionImages state
    tempOps.splice(0, 1);   // (2) mutation!
    tempOps.push(data.url); // (2) mutation!
    console.log(tempOps);
    setOptionImages(tempOps); // (2,3) saved state reference back into state
  });

  // (1) missing cleanup function
}, [optionImages]); // (3) state updated in hook

From what I can tell, the main issue is with the 'art-addpic' event. It seems like you want to remove the first element from the optionImages state and add a new URL to the end.
If this is the case then I have the following suggestions:

*

*Return a cleanup function to unsubscribe the socket connections.

*Remove all useEffect hook dependencies so the hook run once when the component mounts to establish the socket subscriptions, and clean them up when unmounting.

*Use a functional state update for optionImages to remove the state as an external dependency.

Hook Code
useEffect(() => {
  socket.on('connect', () => {
    console.log("connected");
  });

  socket.on('players', (data) => {
    const parsedData = JSON.parse(data);
    console.log(parsedData);
    setPlayers(parsedData);
  });

  socket.on('artist', (data) => {
    setIsArtist(data === userid);
  });

  socket.on('art-addpic', (data) => {
    const parsedData = JSON.parse(data);
    console.log(parsedData);

    setOptionImages(optionImages =>
      // Shallow copy into array, append URL, slice & keep last 4 elements
      [...optionImages, parsedData.url].slice(-4),
    );
  });

  return () => {
    socket.removeAllListeners();
  }
}, []);

useEffect(() => {
  if (isArtist) {
    console.log('You are an artist, Mr White.');
  }
}, [isArtist]);


text:
Q: How does Google know my Computers's name? I was entering my Google account recently and noticed that not only did it say which browser I was currently using - it also knew the exact name of the computer I was using. How is Google able to fetch these informations?

I have been browsing the internet for javascript methods that should give me computer name or similar - but I am sure that Javascript is not able to read these data. If for anything, the site should maybe contain a small java application that executes and fetches the data, but that would usually require for me to accept that java is running in the browser by clicking a modal opening box.
Then I thought maybe they executed some C code in the browser - but how do they do it and access data outside the browsers "sandbox"? A third theory I have is that when I installed the Google Chrome browser, it was able to pass along these details - but it didn't make sense neither when I note that it also knows my iPads exact name though I haven't installed any google applications on my ipad at all. (neither google maps, gmail, chrome or anything).
UPDATE 01/25/2016
I have given this some extra thought and seemed to stumble across something else. I went through possible solutions using node.js or Flash to do the same, but I recalled that Google writes everything in Python, which made me think if it was simple enough using Python. I found this post: How can I use Python to get the system hostname? and thought that this might be a way for Google to it. I don't know if this is still achievable when you are writing a website and if this is a browser-based method as well (mind you I am not Python programmer at any level).

A: I did some testing. I have 2 Google accounts, and what I found was that on my main account (which I use with Chrome), Google knows my computer name. On another account, I am logged in with Edge and Firefox, but neither of them show my computer name. It was not until I logged into the Chrome browser ITSELF (not the Google page) as a Chrome user that my second Google account showed the browser I was using.
I verified this on my laptop: I logged in with my second account into the Google website on a new user, which didn't update the computer name on either device in the security settings. Once I logged into the Google Browser with that account, it showed my computer name. So it looks like because you're logged into Google Chrome, Google knows your computer name.
Note that Google using a sandbox does not make any difference for this. It is trivial to find your computer name, all it takes is hostname in a command prompt.

A: Because when you connect to Google they install cookie in your compputer for they know your information and for say you are alerady come here its Like ID Installor
Cookie its file (ID) when you connect to site, the site use this file for know if you alerady came here or not and they can get all your infos: IP, Computer Name, Access To WIFI I thing and create special and unique ID on your pc
that are why they know your computer name

A: the problem here is if there was a way to get dekstop name though headers that means the browser has that info and if it has there will definitely be some way of getting the name from javascript but there is not i support the above answer that the google uses some sync bad habits or it may be that it stores the ip address which btw we can get with headers this might be the case as with tokens and this ip address thing ddos attacks will be quite easier to deal with so this ip address storing might be true but still its just a guess

A: I don't know you still want to know that or not but anyway,
Every requests that browser sends to loading every pages on the web has some headers, and this headers has some information about browser, referral url and etc..
The important one in this case is "User-Agent" header which includes information about browser, OS and few more information.
You could access the browsers User-Agent string using Java Script in client side via:
navigator.userAgent

and even in server side programming languages like PHP and ASP and etc.. .
This is and example User-Agent string of Safari browser on Macintosh Device:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A
Also you can get yourself User-Agent string and all of analysed datas here


text:
Q: How to automatically wait until a function is done with promises in node.js/javascript? I have a module that when instantiate it, it runs a lot of asynchronous functions.
var freader = new filesreader();    // <-- this runs a lot of async functions
var IMG_ARRAY = freader.get_IMG_ARRAY();   // <-- I get the array that stuff gets put into
console.log(IMG_ARRAY); // <-- this prints an empty array

When I create a new filesreader it, creates [] and then runs a lot of async code to put stuff in the array. Then I want to get the array and print it. But since theres async code, if I try to get the array in the next line and print it, it will be empty. I need to wait until all the async code has finished in the module, but theres so much stuff I don't want to manually track everything and put callbacks everywhere. Is there a way I canjust automatically wait until the function has finished fully through some hack?
Thanks

A: Rather than writing filesreader so it returns an array that will be populated, have it return a Promise:
function get_IMG_ARRAY() {
  var result = [];
  return new Promise(function (resolve, reject) {
    // All your async stuff, then eventually...
    resolve(result);
  });
}

That way, all you have to do to consume it is this:
var freader = new filesreader();
freader.get_IMG_ARRAY().then(function (IMG_ARRAY) {
  console.log(IMG_ARRAY);
}, function (err) {
  // Handle any errors
});


text:
Q: Using existing human translations to aid machine translation to a new language In the past, my company has used human, professional translators to translate our software from English into some 13 languages. It's expensive but the quality is high.
The application we're translating contains industry jargon. It also contains a lot of sentence fragments and single words which, out of context, are unlikely to be correctly translated.
I am wondering if there is a machine translation system or service that could use our existing professionally-generated translations to more accurately create a machine translation into any new language.
If an industry term, phrase or sentence fragment has been translated from en-US to es-AR, pt-BR, cs-CZ, etc., then couldn't those prior translations be used as a hint regarding what the correct word choice should be for some new language? They could be used, in a sense, to triangulate. At worst, they could be used to create a majority voting system (e.g. if 9 of 13 languages translated a phrase to the same thing in the new language, we go with it).
Is anyone aware of a machine translation service that works like this?

A: I have no idea about tranlation systems, but such functionality -- custom translations for specific words -- will be offered by any commercial system, I guess. It is even possible with google translate by clicking on the book with the star on cover.
As a trivial non-invasive method, you could for each goal-language make up a dictionary [] the required terminology in the form [word-as-is-translated, word-as-should-be-translated], where you have an N:1 relationship (in one language multiple word-as-is-translated should be mapped to one word-as-should-be-translated. The words word-as-is-translated thereby depend on the actual translation system).
After preparing those dictionaries, you can simply search the translation result for those words and replace them with the desired words.


text:
Q: Convert json data in jquery from one form to another I'm trying to convert one type of json data to array data. Do I need to traverse through complete data or there is some type of map function to do this. Please help
 var currencies = [
    { value: 'Afghan afghani', data: 'AFN' },
    { value: 'Albanian lek', data: 'ALL' },
    { value: 'Algerian dinar', data: 'DZD' },
    { value: 'European euro', data: 'EUR' },
    { value: 'Angolan kwanza', data: 'AOA' },

to

 var currencies = { 'Afghan afghani': 'AFN' ,
     'Albanian lek':  'ALL' ,
     'Algerian dinar':  'DZD' ,
     'European euro' : 'EUR' ,
     'Angolan kwanza':  'AOA' }

$.ajax({
      url: 'search',
      type: 'get',
      async: "false",
      success: function(data, status) {

        test = $.parseJSON(data);

        countriesArray = $.map(test, function (value, key) { return { value: value, data: key }; });
        fruits = JSON.stringify(countriesArray);
        alert(fruits);
      },
      error: function(xhr, desc, err) {
        console.log(xhr);
        console.log("Details: " + desc + "\nError:" + err);
      }
    }); // end ajax call

A: you can try something like
var a= $.map(currencies,function(m){return '{'+m.value+':'+m.data+'}' })