Images disappear in Combobox

Question: I have a ComboBox which shows an image and text along with it in a stackpanel. The items are shown when I initially open the ComboBox. When I scroll through the list going down, the images in the items at the top of the list disappear (when I scroll back up to see those items) and vice versa. The text remains intact. Also, even without scrolling, when I select an item from the combobox, that item is displayed without the image in the closed combobox. How to rectify this?
<ComboBox ItemsSource="{Binding ElementName=searchPage, Path=emotionList}"
                               SelectionChanged="ComboBox_SelectionChanged"
                               Name="emotionComboBox"
                               VerticalAlignment="Center">
                            <ComboBox.ItemTemplate>
                                <DataTemplate x:DataType="local:StorageItemThumbnailClass">
                                    <StackPanel Orientation="Horizontal">
                                        <Image Source="{Binding Thumbnail, Converter={StaticResource ImagetoThumbnailConverter}, Mode=OneWay}" Margin="10" MaxHeight="50" MaxWidth="50"/>
                                        <TextBlock Text="{Binding Name}" Style="{StaticResource BodyTextBlockStyle}" Margin="10" TextWrapping="WrapWholeWords" Width="120"/>
                                    </StackPanel>
                                </DataTemplate>
                            </ComboBox.ItemTemplate>
                        </ComboBox>

This method is called from the OnNavigated function of the searchPage in which the combobox is present -
private async Task populateEmotionListAsync()
        {
            emotionList = new ObservableCollection<StorageItemThumbnailClass>();
            emotionList.Add(new StorageItemThumbnailClass { Name = EmotionEnum.None.ToString(), Thumbnail = null });
            emotionList.Add(new StorageItemThumbnailClass { Name = EmotionEnum.Angry.ToString(), Thumbnail = await (await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/EmotionIcons/angry.png"))).GetThumbnailAsync(ThumbnailMode.PicturesView, 50) });
            emotionList.Add(new StorageItemThumbnailClass { Name = EmotionEnum.Contempt.ToString(), Thumbnail = await (await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/EmotionIcons/contempt.png"))).GetThumbnailAsync(ThumbnailMode.PicturesView, 50) });
            emotionList.Add(new StorageItemThumbnailClass { Name = EmotionEnum.Disgusted.ToString(), Thumbnail = await (await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/EmotionIcons/disgust.png"))).GetThumbnailAsync(ThumbnailMode.PicturesView, 50) });
            emotionList.Add(new StorageItemThumbnailClass { Name = EmotionEnum.Afraid.ToString(), Thumbnail = await (await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/EmotionIcons/afraid.png"))).GetThumbnailAsync(ThumbnailMode.PicturesView, 50) });
            emotionList.Add(new StorageItemThumbnailClass { Name = EmotionEnum.Happy.ToString(), Thumbnail = await (await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/EmotionIcons/happy.png"))).GetThumbnailAsync(ThumbnailMode.PicturesView, 50) });
            emotionList.Add(new StorageItemThumbnailClass { Name = EmotionEnum.Neutral.ToString(), Thumbnail = await (await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/EmotionIcons/neutral.png"))).GetThumbnailAsync(ThumbnailMode.PicturesView, 50) });
            emotionList.Add(new StorageItemThumbnailClass { Name = EmotionEnum.Sad.ToString(), Thumbnail = await (await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/EmotionIcons/sad.png"))).GetThumbnailAsync(ThumbnailMode.PicturesView, 50) });
            emotionList.Add(new StorageItemThumbnailClass { Name = EmotionEnum.Surprised.ToString(), Thumbnail = await (await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/EmotionIcons/surprised.png"))).GetThumbnailAsync(ThumbnailMode.PicturesView, 50) });
        }

Here is the StorageItemThumbnailClass -
public class StorageItemThumbnailClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private StorageItemThumbnail _thumbnail;
    private string _name;

    public StorageItemThumbnail Thumbnail
    {
        get { return _thumbnail; }
        set
        {
            _thumbnail = value;
            // Call OnPropertyChanged whenever the property is updated
            OnPropertyChanged("Thumbnail");
        }
    }

    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

    public String Name
    {
        get { return _name; }
        set
        {
            _name = value;
            // Call OnPropertyChanged whenever the property is updated
            OnPropertyChanged("Name");
        }
    }
}

And here is the converter-
class ImagetoThumbnailConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        BitmapImage image = null;
        if (value != null)
        {
            if (value.GetType() != typeof(StorageItemThumbnail))
            {
                throw new ArgumentException("Expected a thumbnail");
            }
            StorageItemThumbnail thumbnail = (StorageItemThumbnail)value;
            image = new BitmapImage();
            image.SetSource(thumbnail);
        }
        return (image);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

Answer: I was able to resolve this issue. The ComboBox performs UI virtualization, and images in the ComboBox's virtualized panel were removed when scrolled out of view. When scrolled back, converter of the removed image was called again and the image source was reset. Hence, the stream used as source needed to be set to the start position for reuse.
Converter-
StorageItemThumbnail thumbnail = (StorageItemThumbnail)value;
thumbnail.Seek(0);
image = new BitmapImage();
image.SetSource(thumbnail);

Images disappear in Combobox


Launch a .bat from Jenkins does not work

Question: This is the .bat file :
start cmd.exe /k "C:\Users\etudes.ext46\AppData\Local\Android\sdk1\tools\emulator.exe -avd ff &"
ping 127.0.0.1 -n 60 > nul
start cmd.exe /k "adb shell input keyevent 82"
start cmd.exe /k "node "C:\Program Files\Appium\node_modules\appium\bin\appium.js" -a 127.0.0.1 -p 4723 &"
ping 127.0.0.1 -n 30 > nul
C:\Users\etudes.ext46\Downloads\NUnit-2.6.4\NUnit-2.6.4\bin\nunit-console.exe C:\Users\etudes.ext46\Downloads\NUnit-2.6.4\NUnit-2.6.4\bin\apk\UnitTestProject1.dll
start cmd.exe /k "taskkill /F /IM emulator-x86.exe"
start cmd.exe /k "taskkill /F /IM node.exe"
start cmd.exe /k "taskkill /F /IM cmd.exe"

When i run it manually, it works pretty well (emulate an android device an use Appium with Nunit tests).
But when I try to launch the exact same .bat from Jenkins it doesn't work
Errors and Failures:
1) TearDown Error : AppiumSample.ASSI2.AssistanceV2
   SetUp : System.InvalidOperationException : A new session could not be created. (Original error: Could not find a connected Android device.) (33)
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.

The complete logs are here : http://img.prntscr.com/img?url=http://i.imgur.com/KsrEJiT.png
How can I make this .bat work with Jenkins?
Comment: The link to the log does not work. I would start by verifying that the user has the proper permissions when run from Jenkins. Also, use full path for all executables, as the current directory may be different when run from Jenkins (adb and node).
Answer: The solution was to add the option -no-window when launching the emulator
start cmd.exe /k "C:\path\emulator.exe -avd ff -no-window &"

instead of
start cmd.exe /k "C:\path\emulator.exe -avd ff &"


how to decrypt an ordinary folder (not home, nor partition, nor .Private)

Question: Following the procedure described here I could create an encrypted folder in an external drive.
mount -t ecryptfs /media/foo/bar /media/foo/bar

Then I put some stuff inside, restarted my computer and I now get a few folders named
 ECRYPTFS_FNEK_ENCRYPTED.FWbqvPj9ejI71-QEsY3Zgt7-TRG7S-ek830T453HKzNQPfJjZVpbWWaxlE--

Which I don't know how to mount again.
All tutorials I look for speak about encrypted partitions, encrypted .Private folders or encrypted /home/<user>
Answer: The answer was to use the exact same line of command. But !
Also to remember all the parameters passed at the first mount...
Select cipher:
 1) aes: blocksize = 16; min keysize = 16; max keysize = 32
 etc.

Select key bytes:
 1) 16
 etc.

Enable plaintext passthrough (y/n) [n]:
Enable filename encryption (y/n) [n]: y
Filename Encryption Key (FNEK) Signature [abcdefcbaa123456]:

and the passphrase of course


List all the preview diffs in phabricator

Question: Is there a way to list out all the preview diffs in Phabricator?
That is, I created a diff using arc diff --preview, but have lost track of the diff URL and have lost the original local git commits that went with it. I'd like to regenerate them using arc patch --diff, but I don't know the diff number
Answer: arc diff preview is not intended for storing commits for later. Just create a revision and don't assign anyone it's the exact same thing.
You can't do anything through the UI to recover these as this was never the intention of --preview. If you have access to the database you can go into the *_user.user find your user phid then go into the *_differential.differential_diff table and select all users with this PHID. Or just have your DBA run this for you.
SELECT *
FROM phabricator_differential.differential_diff
WHERE authorPhid
IN (
    SELECT phid
    FROM phabricator_user.user
    WHERE username = 'Kirby'
   )
AND revisionID IS NULL;

From the id column in this list you can access your diffs at the following url. https://phabricator.com/differential/diff/{id}/.
This is a very old ticket upstream that would likely be part of adding better diff support to the UI https://secure.phabricator.com/T1084. I haven't seen much interest in this ever though so i don't imagine it will be supported in the next year unless your company or yourself is willing to pay them to make it.
Comment: You could look into using the `--plan-changes` flag when running arc diff. I don't currently know of anyway to force someone from not not adding a reviewer unless they have custom herald rules setup which add them on every diff. However using --plan-changes will make sure that people listed on review are not being bugged about it.
Comment: Thanks. I'm new to Phabricator and to the project using it. Generating a review isn't an option because on our project you shall specify a reviewer. I was also told that this project doesn't want to push local branches to the remote git. But, as far as I can tell, for the purpose of backing up my work, that is the only option
Comment: oh, yeah. That's better! Thanks


Solr join and non-Join queries give different results

Question: I am trying to link two types of documents in my Solr index. The parent is named "house" and the child is named "available". So, I want to return a list of houses that have available documents with some filtering. However, the following query gives me around 18 documents, which is wrong. It should return 0 documents.
q=*:*
&fq={!join from=house_id_fk to=house_id}doctype:available AND discount:[1 TO *] AND start_date:[NOW/DAY TO NOW/DAY%2B21DAYS]
&fq={!join from=house_id_fk to=house_id}doctype:available AND sd_year:2014 AND sd_month:11

To debug it, I tried first to check whether there is any available documents with the given filter queries. So, I tried the following query:
q=*:*
&fq=doctype:available AND discount:[1 TO *] AND start_date:[NOW/DAY TO NOW/DAY%2B21DAYS]
&fq=doctype:available AND sd_year:2014 AND sd_month:11

The query gives 0 results, which is correct. So as you can see both queries are the same, the different is using the join query parser. I am a bit confused, why the first query gives results. My understanding is that this should not happen because the second query shows that there is no any available documents that satisfy the given filter queries.
Answer: I have figured it out.
The reason is simply the type of join in Solr. It is an outer join. Since both filter queries are executed separately, a house that has available documents with discount > 1 or (sd_year:2014 AND sd_month:11) will be returned even though my intention was applying bother conditions at the same time.
However, in the second case, both conditions are applied at same time to find available documents, then houses based on the matching available documents are returned. Since there is no any available document that satisfies both conditions, then there is no any matching house which gives zero results.
It really took sometime to figure this out, I hope this will help someone else.


TypeScript: Map has key (object) not working

Question: I'm having some troubles while checking if a map already has an object as key.
e.g.
const myMap: Map<MyObject1, MyObject2> = new Map<MyObject1, MyObject2>();

I also defined an equals function in MyObject1 class
equals(other: ThreatAgentMgm): boolean {
    return other.id === this.id;
}

but myMap.has(myObject1) is always false.
I read theat the has method is based on the === operator, should I define something else in MyObject1 class?
Comment: Possible duplicate of [How to customize object equality for JavaScript Set](https://stackoverflow.com/questions/29759480/how-to-customize-object-equality-for-javascript-set) which talks about `Set` and not `Map` but it's about the same issue: key equality
Comment: `Map` in JavaScript is not the same as `Map` in Java, and neither of those are JSON.  ♂
Comment: Objects in maps are same instance match only. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
Comment: JavaScript doesn't use any `equals()` method when comparing objects for equality.  Why don't you just make your map key the `id` field of `MyObject1` and then do `myMap.has(myObject1.id)`?
Comment: I'll need to pass this map as it is to another existing Java API, which will parse this JSON. So what are you saying is that it's not possible to use an object as a key for a map? Am I right?
Comment: Do you really mean "Java"?  And JSON only allows string keys.  Not sure what you're asking.
Comment: You can use an object as a key for a map, but you need to index by the same exact object. If this doesn't meet your needs you can implement your own `Map`-like thing that accepts a key equality function.  But I don't understand your use case enough to give a more concrete suggestion.  If you want more information please update your question with more details and someone can help.
Comment: Yes, I mean the Java API expects a JSON having MyObject1 stringified as the key of the object. So I'd need to be able to use an object as the key of the map. Strange it's not possible such a simple thing as it is in Java.
Comment: Well, the object has the same values, just it's a different instance in time.
Comment: You can still use the stringified object as key.
Answer: Since every JSON object in the end is just a string, I ended up using the JSON.stringify(myObject) as the key of the Map, and a couple of values (MyObject1, MyObject2) as the actual value. This way I'm able to get the desired value in time O(1) while keeping the key object available, without the need of parsing the JSON again or worst, retrieving it from the DB once again.


Which of these options is the best for a long registration process?

Question: I am designing quite a lengthy registration process. Has anyone had any negative or positive outcomes in terms of conversion rates, using the following three solutions:

A Progress Indicator with clearly defined categories. Each step will conditionally reveal content.
A form that only shows one large form field at a time with a progress bar. Each step will conditionally reveal content.
One long scroll-able page with all the form fields displayed and categorized.

It will be a responsive site and will have more desktop users. But the mobile experience should be as close as possible to the desktop.
Comment: Will your users primarily be mobile or desktop?
Comment: Please provide more context and what you can tell us about your users if you don't want to get a ton of "it depends" type of answers.
Answer: Separating registration from content development will get you earlier buy in. Long registration is a burden and can be overwhelming.
If the long registration process is required, I would suggest creating a step by step process in small chunks, with a progress bar. That way the user can't look ahead and feel overwhelmed.
Answer: It depends on many, many factors (user demographics, devices, nature of your service or product, and type of information to name a few) so a little bit of context would help better my answer.
As a rule of thumb, you don't want long registration forms, but if you definitely must, I suggest to first capture the most minimal, important information (usually email and password) and then present the users with the rest of the form.
A progress bar is useful to set expectations correctly so it's a nice-to-have.
Comment: @AmitJain Good question. I believe that, in most cases, this approach gives a sense of engagement since the user will have invested time and data for the first step, so they will feel the need to complete the task. On the other hand, the system can then send reminders to encourage task completion.
Comment: Curious - How does capturing minimal, most important information first up help in getting a positive form conversion?
Answer: The best option for a long registration process is to make it shorter.
Presumably the reason for the long registration process is that there is lots of information you want to capture.  What you ought to do is separate most of this information capture from the actual act of registering for an account.
Allow registering for an account with the absolute minimum of information: someone who wants to sign up for your site should be able to do this with no effort.
Then later, you can capture important, detailed information.  You can guide the user directly to a longer form as soon as they register, but if they don't finish it then, they can always come back, and you can send gentle reminders to users who haven't completed everything.
Look at LinkedIn as a good example of this paradigm.  A LinkedIn account isn't useful unless you enter quite a lot of information.  Nevertheless, they let you register with only name and email address.  Then, later on they encourage you to build up a detailed profile by adding more information.
For this to work, the detailed information actually has to be of some benefit to the user.  However, that is true of any model: you aren't going to get good results if you ask for lots of information that has no clear benefit to them.
Comment: Thanks, I like this idea. Register first, then capture info as and when it's needed.


Deploy Salesforce Package Using Visual Studio Code

Question: I am new to developing for Salesforce. I have installed the Salesforce Extension Pack for Visual Studio Code. So far I have been able to create a project, authorize an org and deploy a single Apex class to a Salesforce Trailhead org.
Where I'm stuck is being able to deploy the entire package to my Salesforce org instead of just a single class. I followed the Trailhead Visual Studio Code training but it ends at deploying just a single Apex class. I've search but can't find anything that answers my question.
Answer: First you have to create Project with Manifest in Vs Code . After the update add all the class and other things to Vs code . Now update the package.xml file . You got in force-app in vs code. After then you can deploy it to org by clicking on right button .
Comment: I added the package.xml to my project and deployed using VS Code but I still don't get my application showing up as a package in Salesforce. Just the Apex class is deployed.
Answer: You can right click your package file in the Explorer and select 'SFDX Deploy Source in Manifest to Org':

Alternatively, deploy from the command line with
<code>> sfdx force:source:deploy -x path/to/package.xml</code>
You can check docs for the CLI commands here:
https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_force_source.htm#cli_reference_force_source_deploy


How to count NULL values in MySQL?

Question: I want to know how can i find all the values that are NULL in the MySQL database for example I'm trying to display all the users who don't have an average yet.
Here is the MySQL code.
SELECT COUNT(average) as num
FROM users
WHERE user_id = '$user_id'
AND average IS_NULL

Comment: wait, are you trying to show the users or the counts?  Your question doesn't match your sample.
Comment: the counts your answer was right.
Answer: A more generic version (that doesn't depend on the where clause and hence limits your overall results):
SELECT
    SUM(CASE WHEN average IS NULL THEN 1 ELSE 0 END) As null_num,
    SUM(CASE WHEN average IS NOT NULL THEN 1 ELSE 0 END) AS not_null_num
FROM users

It's not better then the specific queries presented by other answers here, but it can be used in situations where using a limiting where clause is impractical (due to other information being needed)...
Comment: In MySQL, it's syntactically far simpler to use the `ISNULL()` function than to use `CASE` for this particular purpose.
Comment: maybe you can use IF clause like this: SELECT SUM(IF(IFNULL(average), 1, 0) AS null_num, SUM(IF(IFNULL(average), 0, 1) AS not_null_num FROM users
Comment: SUM(ISNULL(average))
Comment: This solution is great in left join cases where for example one wants to select all users and their count of unread messages in a left joined table. Since count(isnull(read_at)) doesnt work. To give one example.
Comment: Instead of 2 results (null_num and not_null_num) maybe we can use one count and a group by this value.
Answer: SELECT
    COUNT(*) as num
FROM
    users
WHERE
    user_id = '$user_id' AND
    average IS NULL

Comment: "count(column)" will not really count the line with the value of column is "null"
Answer: Also, you can:
Select Count(*) - Count(Average) as NullAverages
From Users
Where user_id = '$user_id'

Comment: Seems to work fine in MySQL for me, and is *MUCH* faster than the 'case when' approach.
Comment: Often you need both values (total count and nulls count) in your code anyway. So, this solution is fast and flexible for any use-case.
Answer: you're on the right track. Remove '_' from 'IS_NULL' and change 'COUNT(average)' to 'COUNT(1)' and you will have it.
For more information on working with NULL in MYSQL see http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html
And for working with IS NULL specifically see
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_is-null
Answer: This is a one liner that also could be used for this problem :
SELECT COUNT(IF(average IS NULL,1,0))
FROM table;

It worked like a charm for me!
Comment: This answer is very useful and help full.
Comment: When the if statement returns any value, the outer count function counts all rows like Count(*) does. Here is the link for more info: [https://learnsql.com/blog/difference-between-count-distinct/](https://learnsql.com/blog/difference-between-count-distinct/). It may be better to use SUM() here.
Answer: I may be missing something mysql specific but this would work in sql server
SELECT COUNT(*) as num
FROM users
WHERE user_id = '$user_id'
AND average IS NULL

Answer: A bit late but you can do it in MySQL 5.0.51:
SELECT COUNT(*) AS total, COUNT(field1) AS notNullFields1
FROM table
GROUP BY field5, field6

Regards.
Comment: Based on http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_count

How to count NULL values in MySQL?


Color Red for Positive Numerical Values in eccomerce site?

Question: Company I am currently with wants to use red for positive values because it reflects their brand colors. I opposed using red because it associated with sale items or negative numbers. Any thoughts? or know any articles I can reference.
Comment: What is the context and domain? Is there a dashboard or performance reports? If you have a rough mock of your thinking so far that would also help...
Comment: It's worth noting that the most common form of color blindness is red/green meaning that red text will look very much like black text to those individuals.
Answer: Your company's (marketing, design?) leaders assume that users will notice (and appreciate) the exceptions (breaking of conventions) for your brand. 99% of your users time will most likely be spent on other sites, and will be used to those conventions.
You're right to point out the conventional use of red.
Jakob Nielsen (from the Nielsen Norman Group) has a short video about Jakob's Law of Internet User Experience:

Users spend most of their time on other sites. This means that users prefer your site to work the same way as all the other sites they already know. Design for patterns for which users are accustomed.

I'm not aware of the domain of your website, but if it's dealing with performance metrics, this would be in direct contrast to conventions.
Red as seen in performance indicators:
While red and green can be problematic with color alone (some users are color blind), when paired with an icon, it is a standard for performance indicators and to use red for down (negative).
From Google Analytics:

Yahoo Finance

Bloomberg
Answer: First of all, it depends in which context use red color(grid, text, graph).
If we have few colors and one of them is close to green then we will have classic situation: green - positive value, red - negative. But for example, we have table and all numbers in black or gray but positive in red in this case we highlight positive values not negative.
Also, big impact has background (white or black)


mongodb error handling whlle using exec

Question: I have ExpressJS ,NodeJs, Mongoose application.
I have written mongodb code like below and it works fine.
module.exports.getStudentid = function(id, callback) {

    Student
        .find({ _id: id })
        .populate('marks')
        .exec(callback);
}

But is it a good code in terms of error handling in NodeJS..Will it pass error to the next layer? How can I improve the above code to use proper error handling?
Comment: https://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html   CB details in sample code on this pg
Comment: I am using mongoose and i am more concerned about the error handling while using the construct which i used
Answer: One thing should be define your callback function to support your error. Your callback should look like:
function (err, student) {
  if (err) {
     // handle error err, will have your error
     return;
  }
  return student;
}

How do you pass it to the next layer would be based on what you do on the commented line... My suggestion, change this to use promises:
const Q                 = require('q');
module.exports.getStudentById = function getById(id) {
    let deferred = Q.defer();
    Student
        .find({ _id: id })
        .populate('marks')
        .exec(function doAfterExec(err, student){
          if (err) {
            deferred.reject(err);
          }
          deferred.resolve(student);
    });
 return deferred.promise;
}

And then to call this, lets assume that you previous module is called StudentIO
const io = require("StudentIO");
io.getStudentById(id)
.then(function doSuccess(result) {
   console.log("yeeei!!!", result);
})
.fail(function doError(err) {
   console.log("buuu", err);
});

This could be even cleaner if you use the new => syntax, but I did not included it since not sure if you are using it. So I've used regular function notations.
Hope this could throw some light. Take a look at Q and promises... it can get rid of the callback hell scenario really easily.

mongodb error handling whlle using exec


Unhandled Exception Error : NoSuchMethodError : class bool has no instance Method ' [ ]'

Question: Future<void> fetchAndSetProducts() async {
    const url =
        'https://flutter-shop-2b595-default-rtdb.asia-southeast1.firebasedatabase.app/products.json';
    try {
      final response = await http.get(url);

      final extractedData = json.decode(response.body) as Map<String, dynamic>;

      final List<Product> loadedProducts = [];

      extractedData.forEach((prodId, prodData) {
        loadedProducts.add(Product(
            id: prodId,
            title: prodData['title'],
            description: prodData['description'],
            price: prodData['price'],
            imageUrl: prodData['imageUrl']));
      });
      _items = loadedProducts;
      notifyListeners();

      //print(json.decode(response.body));
    } catch (error) {
      rethrow;
    }
  }

Comment: Could you share more code? Probably prodData is not defined as bool?
Comment: kindly share the errors
Answer: The response of that url is:
{
  "-N5Pn8iWUJrxG85wpOMw": {
    "description": "an apple laptop",
    "imageUrl": "https://cdn.mos.cms.futurecdn.net/uWjEogFLUTBc8mSvagdiuP-970-80.jpg",
    "isFavorite": false,
    "price": 1234,
    "title": "laptop"
  },
  "-N5Q7PtvJADT214YwUvp": {
    "description": "it is an apple laptop",
    "imageUrl": "https://cdn.mos.cms.futurecdn.net/uWjEogFLUTBc8mSvagdiuP-970-80.jpg",
    "isFavorite": false,
    "price": 123,
    "title": "laptop"
  },
  "-N5Q8CzKquMt73v9DfeX": {
    "description": "an apple laptop",
    "imageUrl": "https://cdn.mos.cms.futurecdn.net/uWjEogFLUTBc8mSvagdiuP-970-80.jpg",
    "isFavorite": false,
    "price": 123,
    "title": "laptop"
  },
  "isFavorite": false
}

Notice how the first 3 fields indeed have a map as value that can be parsed correctly. But there's a 4th called isFavorite that has a boolean as value.
You could add an extra check for this to prevent it, maybe like:
  extractedData.forEach((prodId, prodData) {
    if (prodData is Map) {
        loadedProducts.add(Product(
            id: prodId,
            title: prodData['title'],
            description: prodData['description'],
            price: prodData['price'],
            imageUrl: prodData['imageUrl']));
    }
  });


Materialize - DropDown onclick disappear Issue

Question: I am using below HTML which is a Dropdown. On clicking the Menu Icon the DropDown pops up perfectly but doesn't disappear on clicking the Icon again.
If I click else where on the page, the Dropdown disappears.

----- Added
$('.menu-dropdown').dropdown({
                inDuration: 300,
                outDuration: 225,
                constrain_width: false, // Does not change width of dropdown to that of the activator
                hover: false, // Activate on hover
                gutter: 0, // Spacing from edge
                belowOrigin: true, // Displays dropdown below the button
                closeOnClick: true
            });

How to disappear the Dropdown on Icon Click?
Comment: can you create fiddle for our reference
Comment: I have this problem, solved with updated materialize.js and materialize.min.js .
Answer: Try this:
$('#mainMenu').on('click',function(){
 $('#dropdown1').toggle();
})

Comment: Pls see my edited question...i am using `.dropdown({})` to initialize the DropDown.
Answer: This is without the use of jQuery

        erer

                ffse

                fsefs

                fsefs

Comment: This would be doing same behaviour without using jQuery


Simple Recursion

Question: I was playing around with this function:
public class x {

public static void main(String[] args) {
recurse(10);
}

public static int recurse(int theNumber) {

    if(theNumber == 0) {
        return 0;
    }

    else
    {
        System.out.println(theNumber);
        theNumber--;
        recurse(theNumber);
        System.out.println(theNumber);
    }

    return -1;
}
}

and I got this output:
10
9
8
7
6
5
4
3
2
1
0
1
2
3
4
5
6
7
8
9
Press any key to continue . . .
How is this possible? I understand where the countdown from 10 to 0 comes from.. but how on earth does it count back up?? I'm quite certain I'm missing a fundamental concept about recursion. Can someone fill in the blanks??
Answer: That is because of the last System.out.println(theNumber); in your method. After recursively calling the method, and upcon completion of the method it is printing those values.
Comment: @user: Why don't you step thorough your program using a debugger? This would be much more enlightening than reading some comments.
Comment: I understand that it is because of the last System.out.println(theNumber). I'm not understanding the flow. Is the recursive call completed, then the 2nd System.out.prinln(theNumber) call visited? I just don't understand the flow of this...
Comment: It never reaches the call until after it has converged. So in other words you will enter a call to recurse without printing anything. Then after the last recursive call the stack frames unwind.
Comment: Could you explain how the method executes in a step-by-step manner?
Comment: @user, I would suggest you to dry run the program with a smaller value , actually it is not call the last println statement untill the number reaches 0, then from that it executes rest of the method cals. But try it on paper first
Comment: I need a bit more elaboration if you could.
Comment: @habib from what i see, and i'm clearly wrong, the method is called recursively down to 0, printing values along the way. then after all recursive calls are completed, it prints off the value of theNumber. from what i see, and again, i know i'm wrong, it should only print off the last remaining value of theNumber and then quit the method
Comment: @user, no, after reaching `0`, it returns to the call for example `recurse(1)`, then it prints `1`, then to previous call `recurse(2)` prints 2, and so on...
Answer: Habib explained it quite well actually. Just make sure you understand that the recursion is followed until the parameter theNumber is zero, hence the recursion terminates, and that this happens before any of the the last Sysout calls is done. Also keep in mind that the variable is not shared but local to each invocation. Visually, it might look like this
recurse(5)
print(5)
recurse(4)
  print(4)
  recurse(3)
    print(3)
    recurse(2)
      print(2)
      recurse(1)
         print(1)
         recurse(0)
         print(0)
      print(1)
    print(2)
  print(3)
print(4)

Calls that are in the same column belong to the same stackframe, i.e. same method invocation. Notice, how you decent in the call hierarchy before you actually reach the first print statement after the recursive invocation. This should make it clear, to you.
Comment: "Also keep in mind that the variable is not shared but local to each invocation." - this might be the kicker that i'm missing
Comment: Yeah, maybe. I know that this is kind of confusing in the beginning. One gets used to thinking in stack frames after a while :) It's like becoming a robot. Please upvote.
Answer: For brevity, let's say you call recurse(2) in your main program. Then you have:
theNumber = 2 prints 2, decrements, calls recurse(1)
--> theNumber = 1, prints 1, decrements, calls recurse(0)
----> theNumber = 0, returns without printing
--> theNumber = 1 prints 0 (decremented from 1), returns
theNumber = 2 prints 1 (decremented from 2), returns
Comment: i understand everything up until theNumber=0, returns without printing. after that, shouldn't the function quit??
Comment: say method A looks like this:

`statement0;`

`statement1;`

`methodB();`

`statement3;`

In the general case, when `methodB` returns, execution will resume in `methodA` at `statement3`, even if `methodB` == `methodA` (i.e. you call the method that you are in). Try doing a search for what the call stack and a program counter are.
Comment: @user Why should it? Recursive methods are executed exactly like any other methods. Hence there is no "early quit".
Answer: This is what you need-
public static int recurse(int theNumber) {

    System.out.println(theNumber);
    if (theNumber > 0) {
        theNumber--;
        recurse(theNumber);
    }

    return 0;
}

Answer: Your last System.out.println(theNumber) is the reason of it. As you were asking about the Flow. First the recursive call is completed and then it's making BackTracking. Check this Link BackTracking
Answer: As Habib said flow goes into recursion and then after completion of executing recursive function your last System.out.println(theNumber) gets called.
---->  public static int recurse(int theNumber) {
|
|       if(theNumber == 0) {
|           return 0;
|       }
|
|       else
|       {
|           System.out.println(theNumber);
|           theNumber--;
----------< recurse(theNumber);
            System.out.println(theNumber);
        }

        return -1;
    }

So the time when function returns from recursion theNumber contains the value which was was decremented by 1 only.
Comment: so does it go theNumber--, recurse(9), print, theNumber--, recurse(8), print, etc, etc. how on earth does it get to that last print statement on numerous occasions?
Comment: It goes like print, recurse(9) ; print, recurse(8) ; print, recurse(7).. and after returning from recurse(0) it prints(0) and returns. So print(0) ; print(1) upto first call where theNumber was passed with value 10
Answer: Before your last syso statement you are calling recurse function so it is going on adding your calls on stack..and after reaching value to 0 it is returning to current function back by pulling values from stack.. and after that it is printing values by your last syso statement...

Simple Recursion


How I can monitor new files in a directory and move/rename them into another directory?

Question: A program generates output textfiles, named output.txt, after every 15th iteration of a certain process. Doing so, it overwrites the last output.txt. I want to keep the files however, and I can't modify the file name within the program.
Can I run some script, together with the program, that monitors the output directory and moves and renames the output.txt files into another directory?
Comment: What do you mean by iterations? If this is your custom program, you better modify it so that it can handle this, and if you don't know how do to it you should ask this question on Stack Overflow.
Comment: This program run a loop and then save the output file. I need file manager. I got one clue, and hope it will work. Thank you for your attention.
Answer: First install the package inotify-tools:
sudo apt-get install inotify-tools

A bash script would help
#! /bin/bash

folder=~/Desktop/abc

cdate=$(date +"%Y-%m-%d-%H:%M")

inotifywait -m -q -e create -r --format '%:e %w%f' $folder | while read file

  do
    mv ~/Desktop/abc/output.txt ~/Desktop/Old_abc/${cdate}-output.txt
  done

What does this script means:
This will watch the folder ~/Desktop/abc so whenever a file created inside then it's going to move the file founded inside which is name output.txt to a directory ~/Desktop/Old_abc and rename providing a suffix of date and time of t he new file, this to be sure not to overwrite old files and like that you can also know this file was created in what time and date
Answer: The script below will move and rename any file that might appear in a defined directory (dr1). It renames the files like: output_1.txt, output_2.txt` etc. The script looks "actively" if the targeted name already exists in directory 2 (not from a "blindly" chosen range), so you can start and stop the script at any time without the risk of overwriting existing files.
Since it gives the output files a unique name, and does by definition not overwrite existing files, the targeted directory can be the same as the source directory.
How to use

Copy the script into an empty file, save it as rename_save.py
Important step: in the head section, set the time interval to check for new files. make sure the time interval is (much) shorter than the interval in which new files appear (the time 15 iterations take) or else new files will be created before the last one is moved.
Also in the head section, set the paths to both the source directory and the directory you want to save the renamed files to.
Run it by the command:
python3 /path/to/rename_save.py

while the other (iterating) script is running

The script
#!/usr/bin/env python3
import shutil
import os
import time

#--- set the time interval to check for new files (in seconds) below
#    this interval should be smaller than the interval new files appear!
t = 1
#--- set the source directory (dr1) and target directory (dr2)
dr1 = "/path/to/source_directory"
dr2 = "/path/to/target_directory"

name = "output_"; extension = ".txt"
newname = lambda n: dr2+"/"+name+str(n)+extension

while True:
    newfiles = os.listdir(dr1)
    for file in newfiles:
        source = dr1+"/"+file
        n = 1; target = newname(n)
        while os.path.exists(target):
            n = n+1; target = newname(n)
        shutil.move(source, target)
    time.sleep(t)

Answer:
Install the package inoticoming
sudo apt-get install inoticoming

Create wrapper script watch_output:
#!/bin/bash
backup_folder="$HOME/backups"

filename="$1"

mkdir -p "$backup_folder"

if [ "$filename" == "output.txt" ]
then
    echo "New or changed file \"output.txt\" in $2"
    mv "$2/$filename" "$backup_folder/${filename%.*}.$(date +'%Y-%m-%d_%H:%M:%S').${filename##*.}"
fi

Make it executable:
chmod +x <full_path_of_watch_output_script>

Watch your folder output folder:
inoticoming "$HOME/output" <full_path_of_watch_output_script> {} "$HOME/output" \;

Example:
$ killall inoticoming
$ inoticoming "$HOME/output" ./watch_output {} "$HOME/output" \;
$ touch $HOME/output/output.txt
$ ls -log $HOME/backups
total 0
-rw-rw-r-- 1 0 Mai 13 14:32 output.2015-05-13_14:32:10.txt


CakePHP 2.6 DateTime input and user timezone

Question: Given a web application that operates in different time-zones, is there a way for CakePHP 2.x dateTime inputs to display the values shown to the user on edit, to be in their timezone.
For eg. If I have a record that's stored in the database that says appointment_date (which would be in the UTC timezone), if I, as a user in the timezone America/Jamaica, I would want to edit that record with the inputs showing me values in my time-zone, like when I do this:
<?php echo $this->Form->dateTime('appointment_date'); ?>

And of course, lets assume that we'll convert back to UTC time-zone just before save.
Comment: When you say "shown in their timezone" do you mean the default value in the time dropdown shows my local time (rather than UTC) ?
Comment: correct, but note it would be an "existing" value of a record. Imagine editing a field called appointment_date (which was originally saved in the db as UTC)
Answer: I have created a gist here: https://gist.github.com/antoniovassell/fed29e782be33b7eb5ab
Which allows for an abstract way of possible dealing with dateTime input timezone conversion, using a custom helper class that extends the FormHelper.
public function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $attributes = array()) {
        $attributes = parent::value($attributes, $fieldName);
        if (!empty($attributes['value'])) {
            $attributes['value'] = CakeTime::format('Y-m-d H:i:s', $attributes['value']);
        }
        return parent::dateTime($fieldName, $dateFormat, $timeFormat, $attributes);
    }

So besides manually converting the form value to user time-zone using the TimeHelper, then setting the value to the input, we could automate this by overriding the Form dateTime function. And whenever we call echo $this->Form->dateTime('my_field'); it we do this automatically.


Kaminari index from both data-remote and html messing with links

Question: I have an index view for a model(nested ) that never gets called from the model, but is rendered from a couple different models. One view can render the index with either JS or html. With JS is it in a #related div in the show view and a data-remote link. Another option uses the same controller action to render it only has html.
All was fine until I added Kaminari paging. In the full page view, there was no #related div so paging didn't work. I broke out the guts into a partial and added a #related div and rendered the partial. From js I just rendered the partial from JS.  That worked fine in the full page view, but in the show page it would render the partial, but the links didn't work, looks like it renders the entire show page. Clinking on another tab and then going back to the Progressions tab loads the partial and all works fine. It is just on the initial load of the show page that I can't get the page links to work.
I can load another tab that does not use paging first and solve my problem, but this was kind of the main information that you go to this page for.
Any ideas?
EDIT Request for code
The controller action method. The index method in this controller also sets @progressions
def progressions
  authorize! :read, Progression
  @stage = Stage.find(params[:id])
  @progressions = @stage.progressions_by_score.page(params[:page]).per(20)
  if params[:status] && !params[:status].blank? && @progressions
    @progressions =  @progressions.where(status: params[:status]).page(params[:page]).per(20)
  end
  respond_to do |format|
    format.js
    format.html {render :template => "progressions/index"}
  end
end

The progressions.js.erb file in the stages view
$("#related").html("<%= escape_javascript(render('progressions/index'))%>");

The relations div in the show view. This is pretty much my scaffold template where I display or link to related information. The
 is where any date-remote links will load the data. On initial load it loads the _index partial.

    <%= link_to 'Progressions: Status ->', progressions_stage_path(@stage), :'data-remote' => true,
      :onclick => '$("#progression_status").val("")'  %>

      <%= hidden_field_tag :stage_id, params[:id]%>
      <%= select_tag :progression_status, options_for_select(Progression.statuses["all"], params[:status]),
        :prompt => 'All', :class => 'f-left' %>

    <%= link_to 'Assessors', assessors_stage_path(@stage), :'data-remote' => true %>
    <%= link_to 'Events', events_stage_path(@stage), :'data-remote' => true %>
    <%= link_to 'Select', select_stage_path(@stage) if can? :select_candidates, @stage %>
    <%= link_to 'Ad Mgmt', edit_ad_stage_path(@stage) if can? :manage_ad, @stage %>

    <%= render "progressions/index"%>

The index.html.haml file
#related
  = render "progressions/index"

The _index.html.haml file is just an index table listing the progressions but it does contain:
= paginate @progressions,  :remote => true

Comment: Some code instead of of descriptions of code would be nice :)
Comment: Added code. Shortly after I found a solution.
Answer: Shortly after posting some code, I went back in my memory and used javascript to load the related div. I've tried to stay away from javascript, but in this case I added this to the end of the page after adding :id => "status_id" to the progressions link:

While this fixes my problem, I still don't understand why the initial html response does not respond to the page links in the related div. I'll leave that as something else to learn. I'll put it in coffescript after I figure out how to have fire only on initial load of the show page.


undefined refernce to

Question: In the following code
map<nsaddr_t, Rating*>::iterator it;

generate error for the following line
(it->second)->updateRating(alpha, beta, TRUST_FADING, 1);

the error of "undefined reference to" during compilation.
Is the syntax correct or needs to anything else.
I didn't find the declaration of second in the whole code.
void TrustManager::updateTrust(nsaddr_t address, double alpha, double beta)
{
    map<nsaddr_t, Rating*>::iterator it;
    it = trust_t.find(address);
    if (it == trust_t.end())
    {
        trust_t[address] = initNewRating(alpha, beta, 1);
    }
    else
    {
        (it->second)->updateRating(alpha, beta, TRUST_FADING, 1);
    }
}
bool TrustManager::isTrustworthy(nsaddr_t from)
{
    map<nsaddr_t, Rating*>::iterator it;
    it = trust_t.find(from);
    if (it != trust_t.end())
    {
        double alpha = (it->second)->getAlpha();
        double beta = (it->second)->getBeta();
        double dev = alpha/(alpha+beta);
        return (dev >= UNTRUST_TOLERANCE) ? false:true;
    }
    else
        return true;
}

the full error is
In function `TrustManager::updateTrust(int, double, double)':
:(.text+0xde): undefined reference to `Rating::updateRating(double, double, double, double)'

In function `TrustManager::handleInactivityTimeout()':

(.text+0x241): undefined reference to `Rating::updateRating(double, double, double, double)'
In function `TrustManager::initNewRating(double, double, double)':

trustmanager.cc:(.text+0x306): undefined reference to `Rating::updateRating(double, double, double, double)'

In function `DSRAgent::DSRAgent()':

(.text+0x5b7): undefined reference to `makeRouteCache()'

In function `RouteCache::pre_noticeRouteUsed(Path const&, Path&, double, ID const&)':

(.text+0x54b): undefined reference to `cache_ignore_hints'

routecache.cc:(.text+0x620): undefined reference to `cache_use_overheard_routes'

dsr/routecache.o: In function `RouteCacheClass::create(int, char const* const*)':

(.text._ZN15RouteCacheClass6createEiPKPKc[RouteCacheClass::create(int, char const*

const*)]+0x7): undefined reference to `makeRouteCache()'

collect2: ld returned 1 exit status

The Rating is defined as follows:
class Rating
{
public:
    Rating() { alpha = 1.0; beta = 1.0;}
    Rating(double a, double b) { alpha = a; beta = b; last_t =
        Scheduler::instance().clock();}
    void updateRating(double a, double b, double fading, double weight);
    inline double getAlpha() { return alpha; }
    inline double getBeta() { return beta; }
    inline Time getTime() { return last_t; }
private:
    //the rating of misbehavior
    double alpha;
    //the rating of good behavior
    double beta;
    //last updated time
    Time last_t;
};
class PackData {
public:
    PackData();
    PackData(Packet* packet, Time t);
    Packet* packet;
    Time t;
};

Comment: Can you post the full error?
Comment: "undefined reference" is a linker error, not a compiler error. Seems like you forgot to define some function for which you provided a declaration
Comment: @user2214138 `second` relates to the map iterator, not the object in question. `second` returns the value of the key/value pair the iterator currently points to. In this case, it's a pointer to an object of the class 'Rating'
Comment: We may be able to help you better, if you told us the full definition of the `Rating` class.
Comment: there no member named second in the Rating
Comment: These are not a compiler errors, these are linker errors. You haven't told the linker where all the code is.
Comment: I'm guessing that you've forgotten to compile some files.
Comment: @ATaylor i have posted code for Rating
Comment: Double check, that you've got the exact prototype for `updateRating` in your corresponding C++ file.
Comment: i didn't get u @ATaylor
Answer: The error message is pretty precise:
In function `TrustManager::updateTrust(int, double, double)':
:(.text+0xde): undefined reference to `Rating::updateRating(double, double, double, double)'

You are calling the function updateRating() from within updateTrust(), but you did not define the function anywhere - at least, not where the linker would find it.
The numerous follow-up errors of the same kind hint at a translation unit not properly added to the compiler / linker command line. updateRating(), makeRouteCache(), cache_ignore_hints etc. etc. - all those have to be defined somewhere.

The Rating is defined as follows:

That is a declaration of updateRating(), not a definition. Note that there is no function body ({ ... }) in that header.
(Besides, it is good practice to not provide function bodies (or other definitions) in header files, but to keep them in corresponding .cpp files instead. For one thing, it makes the header files easier to read, i.e. somewhat self-documenting.)
Comment: @user2214138: That is a *declaration*, not a *definition*. You are telling the compiler that there *will be* a function `updateRating()` somewhere (or the compiler would give you an error already), but you don't *define* what that function actually *does*. So the compiler compiles the code without error, expecting the linker to find the definition elsewhere - but it cannot, and thus the "undefined reference" error.
Comment: updateRating is defined in the header file that is called in the C++ file under update Trust
Comment: it seems like  (it->second)   this thing is generating errors.

undefined refernce to


Open or search resources in external jars

Question: Is there a way to use "Open Resource" or Search -> File in eclipse to find resource files (eg *.js, *.css) in external jars?
Answer: Add those external jars into the project, preferably in a different folder. And search - > file by entering the file name in the Containing Text field and * * in File Name Patterns


Would chess variant identity questions be on topic?

Question: On boardgamegeek someone thrifted a copy of a chess set that is unusual. Most of us cannot nail down what it is. To be fair it is possible it isn't even chess but it really looks like it could be one. I would be able to provide pictures and piece breakdowns.
Would a question like this on the main site be viable/on-topic?
If on topic I will make a proper question in main as to not distract the purpose of this meta question. If off-topic I will take it to chat although that looks to be not too busy.
Comment: Link to the BGG post if you dare: https://boardgamegeek.com/geeklist/276021/item/7825120#item7825120
Answer: Since you have some doubts already if it's really a chess variant, I propose you ask this question on our sister site Board & Card Games. They have an [identify-this-game] tag which is quite popular (and successful). And if does turn out to be a chess variant, well, they do not exclude chess from their scope.
Comment: One of the answers I expected. I will give it a shot over there. Wonder how many folks here are also on that stack.


Umbraco: nodes and content are disappearing or outdated

Question: I'm new to web designing and have been using Umbraco to modify and update a website that my company has. I update everything in the site directly via extranet acessing the Umbraco Back Office (the admin page, by default ~/umbraco). I don't have direct acess to the server my company uses, so please keep that in mind.
Since I started using Umbraco I noticed that sometimes the nodes, content and anything else I add on the website just disappear over the weekend or after a day or two. Most of the time what happens is that the content on the website itself is updated but the content in the Back Office is outdated. Because of this, I have to rewrite everything I did.
This is an odd behavior. I tried a lot of stuff, looked for similar problems everywhere, but I can't find a solution. I tried republishing the entire site, so that cache would be deleted, but it doesn't solve the problem. Even worse is that this happens in a random way, sometimes not happening at all.
Umbraco version is 4.7.2. I appreciate any help, as this is so frustrating I think I'll eventually give up if it stays that way.
Comment: We are getting this in Umbraco 7.1.4 and 7.1.6.
Answer: Is your site using SQL CE for its database?
If so, that may be the probem. Here's the discussion in the issue tracker: http://issues.umbraco.org/issue/U4-4621
Comment: Indeed this seems to be the problem. I created another website using MySQL instead of SQL CE and so far the problem has not happened again. I guess I'll have to migrate everything to MySQL from the other website, however I know I will suffer on the process, being a newbie and all... :(
Answer: try and running appending this to you URL while logged into the backend to ensure the cache is refreshed properly http://example.com/umbraco/dialogs/republish.aspx?xml=true , replace the example.com with your sites url.
Comment: Sorry, but isn't this the same as using the "Republish entire site" option when you right-click the Content root? I've tried this before already.
Comment: Well not really as this, i believe actual will force the umbraco xml rebuild as well as the umbraco cache and the database, you could also try and install the examine index package here http://our.umbraco.org/projects/developer-tools/examine-dashboard .so am i correct that its only the back-end that is out of date but not the front end i.e. if you change a property publish the front end updates but the back-end still shows old content.
Comment: Ok then, I will try that URL. However, I will not know if it worked or not unless/until it happens again, so I'll try to give an update after some time.

Alternatively, I'd like to know how this Examine plugin works. These "rebuild/optimize index" options are related to cache?
Comment: And yes, it is only the back-end that is outdated, the front end is updated. But the example you proposed is not exactly what happens: when I update something in the back-end and publish it, the front end AND the back-end are updated. The outdating problem occurs the day after, when I open the back-end and get surprised that it is outdated while the front end is updated.
Comment: @FightMeBro: This is exactly the problem that I am having. Did you have luck figuring this out? Was AdBlock the problem?
Comment: @AjitGoel Sorry Ajit for not updating this question. The answer is no, AdBlock was not the problem, since I disabled it and continue to have this same issue, at random times but still consistently.
Comment: I tried contacting Umbraco support and they said it might be a problem with the database file that was set up when the website was created. I can't change that because I don't have access to the server, I'm just a content editor. What I am currently doing against this problem is backing up every update I make for a week or so; if nothing happens in that period, then it won't happen for that content.
Comment: I don't know if this helps someone but I never got this problem after I changed from using IIS express to using IIS server.


Mysql doesn't return the correct id of the inserted row

Question: I use Mysqljs in a project. That Mysqljs libray has a feature to get the id of an inserted row.

If you are inserting a row into a table with an auto increment primary
  key, you can retrieve the insert id like this:
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function
  (error, results, fields) {   if (error) throw error;
  console.log(results.insertId); });

But the wired thing in here is, it doesn't return the correct inserted id.
I imported my database from a script (without data only structure) but it still takes the old inserted ids I guess.
I have a table called item
first time I inserted, it returns the insertId as 143 even through I can see the id field for my first record is inserted to table as 1.
How do I fix this?
Comment: Removing currently inserted rows does not reset auto increment value. Please `truncate` table and repeat insertion.
Comment: *" it returns the insertId as 143 even through I can see the id field for my first record is inserted to table as 1."* i don't believe that pretty sure the inserted record does not have id 1 when insertId  (node.js) says 143...
Answer: There's no error in your code and in your table too, if you have already written tuples and next, deleted in that table, the answer is here.
How does it work really autoincrement ID into MySQL databases
To guarantee unicity over autoincrement columns, the DBMS store the status of the column itself as "counter".
Starting from the real beginnings: let's suppose that we have a table called "people": id as primary key not null autoincrement, name and surname.
It has been never populated before.
I do an insert, like:
insert into people(name, surname) values ('Mickey','Mouse')

It'll have as "id" value "1".
Let's assume that, after this operation, I'll insert more 99 different records: the 100th will have "100" as "id" value.
Then, let's delete all the 100 tuples we've inserted before into the table.
Right now, if I execute one more time:
insert into people(name, surname) values ('Mickey','Mouse')

I'll see that, the new record has "101" as "id" value.
In a nutshell: to maintain integrity over autoincrement columns, the DBMS will keep track of deleted records and this doesn't mean that it'll be reseted too.
Indeed, it won't.


Mixed norm estimate for $L^p$-functions

Question: Let $f\in L^1(\mathbb{R}^2)\cap L^\infty(\mathbb{R}^2)$ be integrable and bounded.
Question: Does $x\mapsto \int_{\mathbb{R}} |f(x,y)| \mathrm{d}y$ define a bounded function? In other words, is the following true?
$$\sup_{x\in\mathbb{R}} \int_{\mathbb{R}} |f(x,y)| \mathrm{d}y<\infty.$$
That is, if we integrate $f$ over one parameter, is the resulting function bounded? There are a few special cases in which this is definitely true, for example, if $f(x,y)=g(x)h(y)$ for some functions $g,h$. Then $f\in L^1(\mathbb{R}^2)\cap L^\infty(\mathbb{R}^2)$ implies $g,h\in L^1(\mathbb{R})\cap L^\infty(\mathbb{R})$ and
$$\sup_{x\in\mathbb{R}} \int_{\mathbb{R}} |f(x,y)| \mathrm{d} y = \sup_{x\in\mathbb{R}}|g(x)| \int_{\mathbb{R}} |h(y)| \mathrm{d} y <\infty.$$
Moreover, if $f$ is compactly supported in $x$ (i.e. $f(x,y)=0$ if $x\notin K$, $K\subset \mathbb{R}$ compact), then
$$\sup_{x\in\mathbb{R}} \int_{\mathbb{R}} |f(x,y)| \mathrm{d}y \leq |K| \sup_{x,y\in\mathbb{R}} |f(x,y)| < \infty.$$
However, I cannot prove it for general $f$. Also, I did not find a counterexample.
Answer: If you care about every single line, then just having $f(x, y) = \mathbb I_{x = 0}$ is enough. If you want an example where even essential supremum is infinite, construction is a bit more complicated.
Let $$f(x, y) = \begin{cases} 1, x \in [2^{-k}, 2^{-k + 1}), y \in [0, k] \\ 0\end{cases}$$
Then $f$ is bounded by $1$, integral of it is $\sum\limits_k k \cdot 2^{-k} < \infty$. But $\int_\mathbb R f(2^{-k}, y)\, dy = k$, which is not bounded.
Comment: Great example! Thanks!

Mixed norm estimate for $L^p$-functions


What is the @package compiler directive for in Cocoa?

Question: I see @package a lot in Apple's header files, but for the life of me, I can't find an authoritative source that describes its meaning.
Comment: Exact duplicate of http://stackoverflow.com/questions/772600/what-does-the-package-directive-do-in-objective-c
Comment: I had trouble finding anything before I posted. Mainly because you can't search for a "@" symbol, in Google, here, or wherever.
Comment: Totally true, it is hard to search for. Besides, I like the answer to this question a lot better. :-)
Answer: @package is a scope declaration for a particular class member. There are four:

@public: Accessible everywhere.
@protected: Accessible within the class that defines it and inheriting classes.
@private: Accessible within the class that defines it.
@package: In 64-bit, like @public, but only within the same framework; in 32-bit, identical to @public.

See this developer doc for more information.


Where to place controls on a tree/list

Question: I have a chronological list of items. The user can operate on these items with three actions.
So each row has three actions (or buttons for example).
My dilemma is thus:

Having three buttons on every row seems a clumsy solution. Surely I shouldn't have to say the same thing twice.
I could remedy issue 1 by showing the actions only on hover, but then they are invisible when we don't hover over the item and as we all know hiding interface is bad.

What would you suggest?
Answer: Showing the actions only on hover is the way that 37Signals do it in many of their products, and so far I haven't seen any problems with it, other than it not being usable on touch devices.  That is a big downside if your customers are likely to be using touch devices.  With the prevalence of iPads, this is becoming a bigger concern.
Another possible method is to have an action bar, but only make the buttons active once an item has been selected.  The advantage here is that the interface also allows interacting on multiple items at a time.
Although this is a touch example (iOS mail), the principle works just as well on PCs.
Comment: Thanks! Now I remember looking at Trent Walton's article about this issue, it's a great read: http://trentwalton.com/2010/07/05/non-hover/ In it he gives wordpress as an example.
Comment: Actually, this brings me to the issue, how do I detect whether a device has touch as a feature...
Comment: then again I could use modernizr to detect touch-devices. Sorted. http://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript
Comment: @nimrod there really isn't any foolproof way, and with touch computers now, you don't know whether someone is using touch or a mouse.  In general I just avoid relying on hover.
Answer: You can try having a clearly labelled "edit" mode, which will enable the buttons on each specific item. This might signal the user that, in order to manipulate the list, they have to push this button.
Answer:
Multiple selection:
You can have checkboxes for each entry and an action bar on top of the control bar. So user may select a couple of entries and then press the button for required action.
Single selection:
If it is not relevant to apply actions to multiple entries in your case, then instead of checking boxes user may highlight an entry with a single click and then apply the required action.  If user presses the action buttons before selecting an entry you can prompt user to select an entry first...
Answer: The usual solution when you have many commands for a collections of objects is object-selection-action syntax: provide a single non-scroll-away central location for the commands (e.g., a button bar or pulldown menu bar at the top) and provide a means to select and multi-select the items. You can supplement the centralize buttons with accelerators and a context menu (right click) to speed things up for experts. This is typical of desktop GUIs, which tend to be richer than web apps or mobile.
Object-selection-action should be considered when you've three or more commands per item  –when you start using too much space for commands that could go to data. In this case, you're right on the threshold, so you may want to reconsider the advantages of staying with separate buttons per object. It might be more familiar to your users if they've more experience with web apps than desktop apps, and it allows the user to execute a command on one item with a single click. Object-selection-action takes two clicks to complete a command (select item then a button), although expert users can make up for it if you support range multi-select through dragging or shift-clicking. Users used to web apps may not be expecting object-selection-action, and there is no standard way to indicate that selection is supported (but I'd try simply highlighting the first item on the list by default).
Comment: thanks for your answer. However, bulk-actions aren't really an option for me.

Where to place controls on a tree/list


Authenticating Google sign in token id with the backend sever Android

Question: My problem is that I don't understand how to authenticate my Signed In user's tokenId with my backend server. I am using mysql in backend and using volley to add the basic profile info of the user in my "user" table. My question is do i have to add a seperate column for token id and how to authenticate it. What changes i should make in my php script in order to authenticate the token id.
Answer: Google sign in Api  return a GoogleSignInAccount object if sign in result success GoogleSignInAccount acct = result.getSignInAccount(); , and this object has an ID field acct.getId();, you can treat this ID as the password in your backend server and authenticate users with it, every time user tries to login with google, check for his username and id if exists then this user already exists in your system, if not create a new user
Comment: What is the use of token id? And how can i use it? Do I need to store the token id in my table too?
Comment: I actually answered that, You can save the id in your table in the password field and treat it as user password and use it to authenticate users


Display doc file in browser using asp.net

Question: I am developing a job portal using asp.net. I need to build a control to display the uploaded resume on the browser from the server directory. Could any one share the code to do the same. what is the control appropriate to display the content of a doc file?
Thanks in advance.
Answer: There is no ASP.NET server control to display a Word document in a web-page. Microsoft removed the Internet Explorer-only ability to show Word documents in the browser with Office 2007, but before then you could have gotten away with doing it in an  - note that this does require Word to be installed on the browser's computer.
It sounds like you want to convert the Word document into HTML+CSS. I'll stop you right here, because that is a non-trivial operation, even with the significantly-easier-to-process OOXML file formats. There are commercial libraries that can assist you with this, but they cost $lots. (Bing for "Aspose").
There are a few other alternatives:

Print the document, server-side, to a PDF file. This needs a complicated set-up on the server as the Office COM automation libraries should not be used from headless (e.g. server) code; so you'd need to set-up some kind of GUI-session daemon to do this processing.
Accept only the OOXML file formats and extract only plaintext content (this can be done easily enough without much knowledge of OOXML if you already have experience with manipulating XML in-code).
Accept only plaintext or HTML submissions. This is how most "upload your resume" sites work, including Apple's and Microsoft's careers websites.

If you just want to return the Word document to your visitors, then just return the raw bytes of the file using Response.WriteFile, or write directly to the Response's output stream if you're persisting the Word document outside of the filesystem.
Comment: string path = //my path here//
string temppath = rs.resume_URL;
        /temppath;

if(!string.IsNullOrEmpty(path))
{
string[] readText = File.ReadAllLines(path);
StringBuilder strbuild = new StringBuilder();
foreach (string s in readText)
{
strbuild.Append(s);
strbuild.AppendLine();
}
txtresume.Text = strbuild.ToString();
}
}
i used the above code to read the content of the file.

Now the problem is, the code is displaying the image content as garbage value. how to resolve it. Please help its very Urgent
Comment: string path = //my path here//
string temppath = rs.resume_URL;
        /temppath;

if(!string.IsNullOrEmpty(path))
{
string[] readText = File.ReadAllLines(path);
StringBuilder strbuild = new StringBuilder();
foreach (string s in readText)
{
strbuild.Append(s);
strbuild.AppendLine();
}
txtresume.Text = strbuild.ToString();
}
}
i used the above code to read the content of the file.

Now the problem is, the code is displaying the image content as garbage value. how to resolve it. Please help its very Urgent
Comment: This isn't something we can help you with. You need to rephrase your question because it's unclear if you're talking about plaintext documents or Word documents. And what images?
Comment: My requirement is to display the uploaded resume just like it appears in the word document. the word document includes images text etc.
Comment: I'm afraid your requirement isn't really possible unless you have the budget for a Doc-to-HTML library or the time (and technical competence) to do implement it yourself.


Converting do-while to for loop in Java

Question: At the moment, I have this:
 do{
           if (i < y){ //y is a constant

               ObsHandler.obsPartsHandler(); //increment i twice
               ObsHandler.search();

           }
           else {
               break;
           }

       } while (!endline.equals(null)); // endline is changed during each loop cycle

With this loop, and the inputs I have, endline can not be null; this renders the while loop breaking condition redundant. When I try and convert this loop to a for loop, I get a misplaced construct error from Eclipse.
i.e:
for (i < y) {
       ObsHandler.obsPartsHandler(); //increment i twice
       ObsHandler.search(); }

Whilst, the while loop I have works, it seems like bad practice to me.
Any suggestions? Thanks.
Comment: 99% of for loops are used to go through an array/collection. For other stuff use a while loop. Your code is ok.
Answer: If you want to use a for loop, you need to have all three parts of a standard for.  Since you have two conditions, they need to be both included in the condition part:
for ( ; i < y && !endline.equals(null); ) {
    ObsHandler.obsPartsHandler();
    ObsHandler.search();
}

You probably have some initialization code for i, like i=0, which could also go into the initialization section of the for loop.  Otherwise, if all you have is a set of conditions to check without some array or list you are iterating, while or do is really the better fit.
Comment: I like the whole statement except that `while or do is a better fit`. While loops were designed for waiting on a logical condition. For loops were specifically made for the specific logical condition of "I want to run x number of times". The convention can be broken and either used as either, but bottom line if you know exactly how many times to execute, a for loop is superior to a while loop specifically for the reason you outlined, which is that your index variable can be init'd with the for loop, thus limiting its scope.
Comment: @SeanKenny What is frowned upon is using `i` as a variable that gets changed in multiple methods like that. Not only is it making debugging difficult for that because `i` is a HORRIBLE variable name for anything other than a simple for loop, but it also will confuse anyone else who tries to use for loop. If they accidentially make their for loop somewhere else in the code go `for(i = 0; i <...` and for get the `int` (which happens late in the day/night...) then it's a bug that might go undetected for quite a while.
Comment: @corsiKa: Good point, thanks for adding your input.  It does seem in this case `while` would be ok simply because the conditions are modified directly as a side-effect in `ObsHandler.obsPartsHandler()`, rather than some index or counter that is incremented throughout the loop.
Comment: Thanks, I was just seeking reassurance that this use of a while loop would not be frowned upon.
Comment: @SeanKenny: I would double-check for one-off error, because I'm not sure I've captured the meaning exactly how I've combined the conditions.
Answer: If you don't need to check endLine, you can still use a while loop:
while (i < y) {
    ObsHandler.obsPartsHandler(); //increment i twice
    ObsHandler.search();
}

If you also need to check endLine:
while (i < y && !endline.equals(null)) {
    ObsHandler.obsPartsHandler(); //increment i twice
    ObsHandler.search();
}

Note: the difference between do / while (your initial code) and while { } is that in the first case the loop is always run at least once. With a while { }, it is not run at all if the condition is not true at the beginning. That is the same behaviour as a for loop (won't run if the condition is false before the loop).
Comment: This loop is indeed the correct form. But I strongly advise changing `i` and `y` to something a little more meaningful.
Comment: Normally, I'd agree but in the context of the entire project they are meaningful.
Comment: Thanks, that's exactly what I was looking for. I just wasn't sure if a while loop was the correct form.
Answer: A while loop seems like the natural choice for your code. I would just simplify it to:
do {
  ObsHandler.obsPartsHandler(); //increment i twice
  ObsHandler.search();
} while (i < y && !endline.equals(null)); // endline is changed during each loop cycle

or, if you need to check the conditions before:
while (i < y && !endline.equals(null)) {
  ObsHandler.obsPartsHandler(); //increment i twice
  ObsHandler.search();
}

Answer: for (boolean start=true;(start || endline != null) && i < y;){
    start=false;
    ObsHandler.obsPartsHandler(); //increment i twice
    ObsHandler.search();
}

(startendline != null) is only tested the second time.
i < y is only tested the first time.
Comment: What is the purpose of the boolean?
Comment: The question mentions that is not possible for endline to equal null and that the outer loop condition is not longer needed.
Comment: fair enough but I think the original poster was confused about what he was trying to achieve - what you show is equivalent to a do / while but that's not necessarily what he wanted. See the note at the bottom of my answer.

Converting do-while to for loop in Java


Custom scrollbars in websites - do they make any sense?

Question: Are custom scrollbars still needed today?
The only reason they were needed so far is because they are fugly on Windows. They are always visible and don't autohide and they just look bad. But I've see on youtube that in Windows 10 they changed scrollbars so now they look like on MacOS! That means there's no point anymore in using scrollbar scripts like perfect-scrollbar, right? Which btw, is anything but perfect, because it never works right with modern frameworks like vue, react etc... And it never will because graphic updates are hard-impossible to track, especially when using effects.
Just to make it clear, I am talking about scrollbars for inner elements, like some list with many items, not the browser window itself. Nobody uses custom scrollbars for the browser window anyway.
Comment: Your Question and description do not make it clear what is your exact doubt. Could you clarify? Do you mean should we use them in design, or tehnically overall should it be possible, or something else?
Answer: I think scrollbars shouldn't change unless there is a big reason behind it. The scrollbar style should be as user expects which is his browser default. changing something like this without no big reason makes usability risks for your design.


VB.NET select link from listbox and browse to it in webbrowser control

Question: I have a list of links stored in a listbox. I want a timer control to load one link after the other every 4 seconds, and once it's reached the end of the list, I want the timer to stop. I've tried to achieve this with the code below and it's only loading the first link. Can someone point out my mistake(s)? Thanks in advance!
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    Dim counter As Integer = counter + 1
    If counter > ListBox2.Items.Count Then
        counter = 0
        Timer1.Enabled = False
    Else
        Dim i As Integer
        For i = 0 To ListBox2.Items.Count - 1
            WebBrowser1.Navigate(ListBox2.Items(i))
        Next
    End If

End Sub

Answer: You need to declare your counter variable at the class level instead of within your Tick handler, or else its value is always reinitialized to 1.
So in other word, defined it oustide the handler.
Also, you must not loop the entire content of the ListBox within your tick handler.
Here's a better version:
Public Class Form1

    Private counter As Integer = 0

    ...

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

        If counter > ListBox2.Items.Count - 1  Then
            counter = 0
            Timer1.Enabled = False
        Else
             WebBrowser1.Navigate(ListBox2.Items(counter))
        End If
        'Increment at the end to get element(0)
        counter = counter + 1

    End Sub
End Class

Cheers
Comment: That's true, but it's not the only problem here. The entire loop is within the tick event.
Comment: @mrlucmorin The correct is `If counter > ListBox2.Items.Count - 1 Then`
Comment: @valter, you can propose an edit if you want. I'll modify it, but you can always edit it yourself ;-)
Comment: I know that, but i know also how "sensitive" high rated users are, so i prefered to comment. This doesn't apply to you of course.
Comment: Hehe, got ya... In this case I had simply copied/pasted the original code, moved the increment to the end, but forgot to update the condition.. thx for spotting it.


how to use pre-installed binaries (zeromq) in npm install instead of build by node-gyp tool?

Question: i am on alpine:3.6 i've already installed zeromq binary from (compiled from source) on system.
and now i want to use nodejs's binding for this.
so using https://github.com/JustinTulloss/zeromq.node
here is some instruction here in which we can build library from source.
https://github.com/JustinTulloss/zeromq.node/wiki/Installation#installation-on-linux--bsd-without-root-access
we can complie lib on our own but that places binaries in same folder, but instead i want npm to use library which installed in system (/use/local)
as far as i can gess its game of these two lines which i don't much knowledge about it
export CXXFLAGS="-I $(readlink -f ../include)"
export LDFLAGS="-L $(readlink -f ../lib) -Wl,-rpath=$(readlink -f ../lib)"

then npm install will use libs what we just complied in zeromq folder
i don't have much knowledge of CXXFLAGS and LDFLAGS so is that possible.
Answer: The installation instructions you cite are for peopel without root access, which are therefore unable to install software in the "usual places" like /usr or /usr/local. If you install a library into an "unusual place" like your home directory, you have to tell the compiler and linker where the library can be found. Thats the use of CXXFLAGS and LDFLAGS in this case. Since you seem to have root access and installed the ZeroMQ library in an "usual place", npm install zmq should work without you having the set these varaibales.
Update: The above seems to be not working. However, according to https://github.com/JustinTulloss/zeromq.node#project-status, this module is deprecated anyway. The new zeromq model works without compilation for me. See this minimal Dockerfile:
FROM node:alpine

RUN npm install zeromq

Note: This does not use the pre-installed library but a pre-build one instead. However, you could leave out the pre-installed library from the base image to save size.
Comment: its not working, and its trying to compile from source.. which i don't want because in my case i just want ship lightweight app, where our docker container image already have libzmq pre installed..
Comment: so i want npm install to use preinstallled zmq instead of compiling it again, that compilation takes time which is problem for me.. is there any way you know to get npm install to use systme lib insead of building new from scratch?
Answer: it is possible now, with 6-beta.4, just tested

npm install email@example.com --zmq-shared

in a system with zeromq package is installed, i.e. in alpine

apk add zeromq-dev

I am almost sure that -dev package is not required, but I did not tested
UPDATE (few minute later)
It is possible to use zmq as external library, it requires anyway a compilation, but without downloading all package.
Give that the zeromq-dev is installed

apk add zeromq-dev

(in this case -dev is required), then

npm i zeromq-stable --zmq-external

will compile the nodejs module, but not the zeromq library itself, a very faster option, but still not getting the lightweight docker image you need


Storing the history of 1 or many columns in a row

Question: I have a request to store the date on which a specific field was changed in a table. For example, In my dbo.User table, we need to know when the IsActive flag was changed. With history.
I am proposing this:

New schema - History.

New table - [History].User_History

<code>    CREATE TABLE [History].User_History (
      Id INT NOT NUL IDENTITY(1,1), <-- PK
      UserId INT NOT NULL, <-- FK to User.Id
      CaptureDate DATETIME DEFAULT(GETUTCDATE()),
      PrivacyId INT NULL
    )
</code>
PrivacyId (Or any column added) would be NULL, as we may add new columns, and existing rows would need to be left NULL, as we didn't know the value then)
All our Updates and Inserts are via Stored Procs (Yes, I know ...)
So those two procs will need to check if the new value of PrivacyId will change. If so, write a new row to the _History table.
We do not have the option to use CDC. So seems we have to find a more manual way to achieve this. Is my proposed solution suitable? Or are there barriers or better ways to achieve this?
Comment: There are hundreds of ways to skin this cat... for example you can store the changes as XML/JSON to avoid needing the schema of your history table to match the actual table. You can even use generic history tables where 2 columns are TableName & TableId. It really depends what you are going to use it for and how much work you want to put in. Personally I would do it in a trigger rather than the SP. Not only do you automatically have the before/after values available, but you can't sneak around it with a manual update which bypasses the SP.
Answer: Your solution looks fine, as you are doing these using stored procedures. Also, your history table looks very simple. Maybe you can add, what kind of operation(INSERT, UPDATE) and who made the change.
<code>CaptureDate DATETIME DEFAULT(GETUTCDATE()),
OperationType VARCHAR(10) NOT NULL,
PerformedByUser VARCHAR(30) NOT NULL
</code>
As you told CDC is out of scope, you can think of out of the box options like,
Temporal tables


Accidentally deleted symlink libc.so.6 in CentOS 6.4. How to get sudo privilege to re-create it?

Question: I accidentally deleted the symbol link /lib64/libc.so.6 -> /lib64/libc-2.12.so with
$ sudo rm libc.so.6

Then I can not use anything including ls command. The error appears for any command I type
ls: error while loading shared libraries: libc.so.6: cannot open shared object file: No such file or directory

I've tried
$ export LD_PRELOAD=/lib64/libc-2.12.so

After this I can use ls and ln ..., but still can not use sudo ln ... or sudo -E ln .... I always get this err
sudo: error while loading shared libraries: libc.so.6: cannot open shared object file: No such file or directory

It's a remote server so I can not use a live CD. I now have a ssh bash session alive but can not establish new ones. I have sudo privilege, but don't have root password.
So currently my problem is I need to run sudo sln -s libc-2.12.so libc.so.6 to re-create the symlink libc.so.6, but I  can not run sudo without libc.so.6.
How can I fix it? Thanks~
Comment: @OlegMikheev No, either `$ su` or `$ sudo su`
Comment: Maybe you could try to scp the same version of libc.so.6 from a different machine to yours...
Comment: Boot from a different image (maybe a live CD).  You won't be able to run any command, for all intents and purposes, until you have `libc.so.6` back, so you have to find a way of running an O/S that will allow you to replace the symlink.  You don't have to install the O/S; you just need to run it long enough to get to a point where you can mount the root file system of your normal O/S and fix the symlink.
Comment: @JonathanLeffler I can not even get sudo privilege to reboot the machine ...
Comment: @rakib yes but not to the files owned by root
Comment: Create a symlink from a folder that your id has access to (e.g. your home folder, or I'd create a ~/bin ) and add that folder to the system $PATH (I'd put it at the front).  That might be enough for it to pick it up enough to run sudo ... Good luck.
Comment: @eric If you can do "sudo chmod 777 /etc/password", then try to manipulate the root user password.
Comment: There's an on-off switch — you'll probably need to use that, along with magical incantations on the keyboard (or an actual CD in the CD drive) to get the system to reboot from a new image. It ain't trivial; I'd not want to have to do it. This should have been migrated to ServerFault or SuperUser by now. You might need to pretend to upgrade your O/S (even though 6.4 is the latest, you might be able to 'upgrade' it again, restoring the library). Removing the symlink that all system executables depend on is a very effective a way of disabling a system.
Comment: Do you have any means to get into single user mode? It'll give you root access if so and hopefully allow you to recreate the symlink.
Comment: @JonathanLeffler Thanks, but it seems there's no way I can get root now. So have to wait for help. http://serverfault.com/questions/519664/accidentally-deleted-symlink-libc-so-6-in-centos-6-4-how-to-get-sudo-privilege
Comment: same question: http://stackoverflow.com/questions/12249547/how-to-recover-after-deleting-the-symbolic-link-libc-so-6
Answer: I resolved the issue by using a statically linked version of "ln" that was already in the server's /sbin.
E.g., this restored it for my configuration:
/sbin/sln /lib64/libc-2.5.so /lib64/libc.so.6
Answer: A bit embarrassing :) but it happened to me as well on Ubuntu 12.04.3 (which is not CentOS 6.4 but I thought this could still help maybe).
Because my Ubuntu wouldn't start I used a liveUSB to boot up and then mounted my hard drive and created the symlink (I did have the file itself libc-2.15.so) and that did it.
Just a few specific details:

I asked a good friend to use his computer for half an hour
I Downloaded my exact Ubuntu iso (12.04.3, if you're on;y missing the symlink, it could be any version so much that it can mount drives) from here: link
I made sure his Ubuntu has usb-creator-gtk ($ sudo apt-get install usb-gtk-creator, I'm sure Windows has an equivalent usb boot creator)
Created the liveUSB using usb-creator-gtk
Booted my computer with it (you'll probably need to change your BIOS settings to allow external USB to be booted first)
Once I booted from the live USB I figured where my hard drive partition by running the Ubuntu partition tool (the live USB has one) - mine was of type ext4 and in /dev/sdb1
I mounted it by doing $ mkdir /home/ubuntu/mnt and then $ sudo mount-t ext4 /dev/sdb1 /home/ubuntu/mnt
I then proceeded to that folder $ cd /home/ubuntu/mnt
From that location I then created the symlink by $ sudo ln -s lib/x86_64-linux-gnu/libc-2.15.so lib/x86_64-linux-gnu/libc.so.6

After a reboot I was good.
Hope it helps you (or someone..)
Comment: Something i would like to add: used **fdisk** to locate partition to mount. If you dont have BIOS access like i did - there is a workaround - you can use **grub** to boot USB. Ubuntu: Press 'c' while in grub. List and switch root to USB (in my case it was hd2). If you had only problem with getting to root, its possible to load bash with root rights from grub also. So more or less linuxes are not as safe as ppl think they are :)
Answer: I would add some thing more to @wilfo answer as same also happened with me [accidentally deleting lib.so.6 and was getting /sbin/init missing libc.so.6 on boot up] .
After creating liveUSB in windows (using UNetbootin etc [http://unetbootin.sourceforge.net/]) or in ubuntu as @wilfo suggested.
Booting from liveUSB, I selected "experience ubuntu without installing it" and was happy applying wilfo's method until step 6 and then i couldn't find my hard drive partition of type ext3/4. All were nftf/fat/extended stuff.
So i recovered previous ubuntu (the one with missing libc.so...) by following this link
https://help.ubuntu.com/community/Boot-Repair
make sure to follow all necessary steps and take a backup of your ubuntu partition.
you can see your previous ubuntu files inside /mnt/boot-sav/wubi1/home
take a backup from here to your windows partations /mnt/boot-sav/sda...
and follow remaining procedure here https://help.ubuntu.com/community/Boot-Repair


$\int\frac{dx}{x-3y}$ when $y(x-y)^2=x$?

Question:
If y is a function of x such that $y(x-y)^2=x$
Statement-I: $$\int\frac{dx}{x-3y}=\frac12\log[(x-y)^2-1]$$
  Because
Statement-II: $$\int\frac{dx}{x-3y}=\log(x-3y)+c$$
Question: Is Statement-I true? Is Statement-II true? Is Statement-II a correct explanation for Statement-I?

I can say that II is false because y is not a constant but indeeed a function, I don't know answers to other two questions.I am thinking that probably we have to eleiminate y from the given functional equation or do a clever substitution?
Comment: Why $dx$ twice in each integral?
Comment: @GerryMyerson typo
Comment: Have you tried differentiating the answers and seeing which one simplifies to $\dfrac{1}{x-3y}$? You will need to implicitly differentiate $y(x-y)^2 = x$ to find $\dfrac{dy}{dx}$.
Comment: that gives $y'=\frac{1-2xy+2y^2}{x^2+3y^2-4xy}$
Answer: This is one of the reasons I love G. H. Hardy's "A Course of Pure Mathematics". The current question is problem 16, page 260. He advises to use the substitution $t=x-y$. So that $y=x/t^2$ and then $t=x-x/t^2$. Finally we get $x=t^3/(t^2-1), y=t/(t^2-1)$. Then $$dx=\frac{t^4-3t^2}{(t^2-1)^2}\,dt,\, x-3y=\frac{t^3-3t}{t^2-1}$$ so that $$\int\frac{dx}{x-3y}=\int\frac{t}{t^2-1}\,dt=\frac{1}{2}\log(t^2-1)+C=\frac{1}{2}\log\{(x-y)^2-1\}+C$$ Hardy gives further examples:
1) $y^2(x-y)=x^2$ which is rationalized by $y=tx$.
2) $(x^2+y^2)^2=a^2(x^2-y^2)$ which is rationalized by $x^2+y^2=t(x-y)$. Thus if $$(x^2+y^2)^2=2c^2(x^2-y^2)$$ then $$\int\frac{dx}{y(x^2+y^2+c^2)}=-\frac{1}{c^2}\log\left(\frac{x^2+y^2}{x-y}\right)+C$$
There is a deep theory of rational parametrization of algebraic curves given by relation $f(x,y)=0$ with $f$ being a polynomial which is at work here. Hardy just gives a glimpse of the theory of algebraic curves here.
Comment: sorry that's a valid answer but i don't like deaccepting, hope the upvote helps?
Comment: @Aditya: its fine. We should not be too greedy of reps. If you can manage to get Hardy's book, it will help you a lot. There is no better book for students of your age.
Comment: remember you have told me about it earlier and I do have it but am not getting time to read it :(
Comment: actually read first 3-4 chapters.
Comment: @Aditya: seems I had forgot abt it. Happy to know you are reading it. :)
Answer: Differentiating
$$
x=y(x-y)^2\tag{1}
$$
we get
$$
\begin{align}
1&=y'(x-y)^2+2y(x-y)(1-y')\\
&=y'\left[(x-y)^2-2y(x-y)\right]+2y(x-y)\\
&=y'(x-3y)(x-y)+2y(x-y)\\
1-2y(x-y)&=y'(x-3y)(x-y)\\
(x-y)^2-1&=(1-y')(x-3y)(x-y)\tag{2}
\end{align}
$$
Differentiating Statement-I, we get
$$
\frac{(x-y)(1-y')}{(x-y)^2-1}=\frac1{x-3y}\tag{3}
$$
which matches $(2)$. Therefore, with the exception of a constant of integration, Statement-I is correct. That is, dividing $(2)$ by $(x-3y)\left[(x-y)^2-1\right]$ and integrating, we get
$$
\begin{align}
\int\frac{\mathrm{d}x}{x-3y}
&=\int\frac{(x-y)\,\mathrm{d}(x-y)}{(x-y)^2-1}\\
&=\int\frac{\frac12\,\mathrm{d}[(x-y)^2-1]}{(x-y)^2-1}\\[4pt]
&=\frac12\log\left[(x-y)^2-1\right]+C\tag{4}
\end{align}
$$
As you surmised, Statement-II implies that $y'=0$, which is false.


Binding Setting Property but UI not updating. Can I debug within referenced project/control?

Question: I have a custom control with bindings like below
<DataTemplate DataType="{x:Type vm:EditorTabViewModel}">
    <me:MarkdownEditor
        Options="{Binding Path=Options, RelativeSource={RelativeSource AncestorType=Window}}" />
</DataTemplate>

I find that binding (Window1.Options) is being set (after stepping through code in debug mode), the markdown editor options (supposed to set Fonts, Colors etc) does not get set, or at least the UI does not update. I want to bug whats happening with in the MarkdownEditor.xaml.cs but thats another (referenced) project. How can I verify that the MarkdownEditor.Options is being set at least?
I have actually tested that the MarkdownEditor side is working by the below
<Window ...>
    <Grid>
        <Button Content="Options" Click="Button_Click" Grid.Row="0" />
        <me:MarkdownEditor Options="{Binding Options, RelativeSource={RelativeSource AncestorType=Window}}" Grid.Row="1" />
    </Grid>
</Window>

So the difference is the latter is a MarkdownEditor just in a Grid in a Window. The one failing is a MarkdownEditor within a TabControl bound to a ObservableCollection<TabViewModel>
Visual Studio Solution Replicating The Problem
I am not really good at explaining things, so a simple project I made up minus all the unnecessary noise uploaded to media fire so you can take a look at whats wrong
The video showing the problem on Screenr
With just a simple usage, editor in a window/grid.

the binding works ok
Then when used in conjunction with TabControl bound to ObservableCollection<EditorTabViewModel>, the binding works as shown in the 2 TextBoxes updating its values. but the editor does not update
Answer: After reading Kent Boogaart's answer to this question I think that the right place to change SetValue to SetCurrentValue isn't in the CLR Property but in the constructor for MarkDownEditor.
public MarkdownEditor()
{
    InitializeComponent();
    //Options = new MarkdownEditorOptions();
    this.SetCurrentValue(OptionsProperty, new MarkdownEditorOptions());
    DataContext = this;
}

In fact, this will work just as good without this.SetCurrentValue also since Options will be set through the Binding.
To verify that your Binding has in fact been overwritten by SetValue you can add this code in some event for TabUsage (e.g PreviewMouseRightButtonDown for the FontSize TextBox) and the Binding will start to work again.
private void TextBox_PreviewMouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    MarkdownEditor.MarkdownEditor editor = VisualTreeHelpers.GetVisualChild<MarkdownEditor.MarkdownEditor>(this);
    Binding binding = new Binding();
    binding.Path = new PropertyPath("Options");
    binding.Source = this;
    binding.Mode = BindingMode.TwoWay;
    editor.SetBinding(MarkdownEditor.MarkdownEditor.OptionsProperty, binding);
}

Comment: YAY, it works! You're great @Meleak, learnt alot from you! Thanks
Comment: HBut I still don't really get `SetCurrentValue()` ... I guess time to re-read & digest the other question ...
Comment: @jiewmeng: Hehe sure thing :) Nice control you're working on btw
Comment: thanks. I was trying to replicate WMD Markdown Editor in WPF/C#. Its also a practice project, I thought it would be a relatively easy project, turns out complicated lol ...