text:
Q: Get image width and height before loading it completely in iPhone I am loading an image in my UITableViewCell using

[NSData dataWithContentsOfURL:imageUrl]

For setting custom height for my tableview cell , i need the actual size of the image that am loading.
Can we get the width and height of an image before loading it completely ? Thanks in advance.

A: Try the Image I/O interface as done below. This will allow you to get the image size without having to load the entire file:
#import <ImageIO/ImageIO.h>

NSMutableString *imageURL = [NSMutableString stringWithFormat:@"http://www.myimageurl.com/image.png"];

CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)[NSURL URLWithString:imageURL], NULL);
NSDictionary* imageHeader = (__bridge NSDictionary*) CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
NSLog(@"Image header %@",imageHeader);
NSLog(@"PixelHeight %@",[imageHeader objectForKey:@"PixelHeight"]);

A: you can do it like this:
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = [UIImage imageWithData:imageData];
NSLog(@"image height: %f",image.size.height);
NSLog(@"image width: %f",image.size.width);

A: Take a look at this Question How do I extract the width and height of a PNG from looking at the header in objective c which shares how is it possible to parse image Meta-data.
I have a created OpenSource project Ottran that extracts the image size  and type of a remote image by downloading as little as possible, which supports PNG, JPEG , BMP and GIF formats.

A: NSData is an "opaque" data, so you cannot do much with it before converting it to something more "useful" (e.g., creating an UIImage by means of it -initWithData: method). At that moment you could enquiry the image size, but it would be late for you.
The only approach I see, if you really need knowing the image size before the image is fully downloaded, is implementing a minimal server-side API so that you can ask for the image size before trying to download it.
Anyway, why do you need to know the image size before it is actually downloaded? Could you not set the row height at the moment when it has been downloaded (i.e., from your request delegate method)?

A: dataWithContentsOfURL is synchronous it will block your UI until its download complete, so please use header content to get resolution, Below is Swift 3.0 code
 if let imageSource = CGImageSourceCreateWithURL(url! as CFURL, nil) {
     if let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary? {
          let pixelWidth = imageProperties[kCGImagePropertyPixelWidth] as! Int
          let pixelHeight = imageProperties[kCGImagePropertyPixelHeight] as! Int
          print("the image width is: \(pixelWidth)")
          print("the image height is: \(pixelHeight)")
       }
   }


text:
Q: How to link an event in tab in ipywidgets? In below code I created 2 tabs with a text box and a button in inside each tab. I want to select button one and link an event for it. How can I do it?
import ipywidgets as widgets

lst = ['one', 'two']
list_widgets  = [
    widgets.HBox([widgets.Text(
        placeholder="name",
        description=name,
        disabled=False),
                  widgets.Button(
                  description="ok")]) for name in lst]

children=list_widgets
tab = widgets.Tab(children)
[tab.set_title(num, name) for num, name in enumerate(lst)]

display(tab)

A: To link an action to an ipywidget button you use the on_click method for a button you have created.  From ipywidget:

The Button is not used to represent a data type. Instead the button
  widget is used to handle mouse clicks. The on_click method of the
  Button can be used to register function to be called when the button
  is clicked.

But, if you create your layout using your strategy you'll be somewhat limited with your buttons because they'll have the same action (the same button will be referenced).  In this example button is used on both tabs:
import ipywidgets as widgets

def click(h):
    print('button click')

button = widgets.Button(description="ok")
button.on_click(click)

lst = ['one', 'two']
list_widgets  = [
    widgets.HBox([widgets.Text(
        placeholder="name",
        description=name,
        disabled=False),
    button]) for name in lst]

children=list_widgets

tab = widgets.Tab(children)
[tab.set_title(num, name) for num, name in enumerate(lst)]

display(tab)

With some modifications you can add two buttons with different actions:
import ipywidgets as widgets

def click1(h):
    print('button one click')

def click2(h):
    print('button two click')

one = widgets.Button(description="ok")
one.on_click(click1)

two = widgets.Button(description="ok")
two.on_click(click2)

btn = [one, two]
lst = ["one", "two"]
list_widgets  = [
    widgets.HBox([widgets.Text(
        placeholder="name",
        description=name,
        disabled=False),
    btn[num]]) for num, name in enumerate(lst)]

children=list_widgets

tab = widgets.Tab(children)
[tab.set_title(num,name) for num, name in enumerate(lst)]

display(tab)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Assign equal weights in new column based on count of values I have the following df
dictionary1 = {'trade_date': {1350: 20151201,
  6175: 20151201,
  3100: 20151201,
  5650: 20151201,
  3575: 20151201,
     1: 20170301,
     2: 20170301},
 'comId': {1350: '257762',
  6175: '1038328',
  3100: '315476',
  5650: '658776',
  3575: '329376',
     1: '123456',
     2: '987654'},
 'return': {1350: -0.0018,
  6175: 0.0023,
  3100: -0.0413,
  5650: 0.1266,
  3575: 0.0221,
  1: 0.9,
  2: 0.01}}
df1 = pd.DataFrame(dictionary1)

I want to create a new column called weights and assign equal weights based on the number of entries for a particular trade_date.
In other words, the output should be like this:
dictionary2 = {'trade_date': {1350: 20151201,
  6175: 20151201,
  3100: 20151201,
  5650: 20151201,
  3575: 20151201,
     1: 20170301,
     2: 20170301},
 'comId': {1350: '257762',
  6175: '1038328',
  3100: '315476',
  5650: '658776',
  3575: '329376',
     1: '123456',
     2: '987654'},
 'return': {1350: -0.0018,
  6175: 0.0023,
  3100: -0.0413,
  5650: 0.1266,
  3575: 0.0221,
  1: 0.9,
  2: 0.01},
'weights':{1350: 0.2,
  6175: 0.2,
  3100: 0.2,
  5650: 0.2,
  3575: 0.2,
  1: 0.5,
  2: 0.5}}

df2 = pd.DataFrame(dictionary2)

This there are five values associated with trade_date 20151201, hence they all get a value 0.2 (1/5) in the new column weights and 2 values associated with trade_date 20170301, hence they all get the value 0.5 (1/2) in the new column weights.
Any suggestions how to do this?

A: df['weights'] = df.groupby('trade_date')['trade_date'].transform(lambda x: 1/len(x))


text:
Q: How to automate the calculation of the average entry price for every new entry price and contract size added in an Excel sheet? trading related Context

*

*Entry Price (a.k.a. Entry Point) refers to the price at which an investor initiates a position in a security.  A trade entry can be initiated with either a buy order for a long position, or sell order for a short position.

*Average Entry Price refers to the central price at which an investor is positioned in a security in order to increase potential profits and exit the market more easily, it can take different entry prices as well as different quantity of contracts (a.k.a. contract size)
Manual calculation of the Average Entry Price in an Excel Sheet
Based on this article, I managed to calculate the Average Entry Price as follows:

*

*Say you have the following Entry Prices:
[16500,16400,16300,16200]

*And also you have the following Quantity of Contracts pegged to those Entry Prices respectively:
[0.1,0.1,0.1,0.1]
Such information will be stored in a table like this one:

Entry   Price
Quantity (BTC)
Average Entry   Price

16500
0,1

16400
0,1

16300
0,1

16200
0,1

Now, the correspondingly average entry price formulas were written as follows (assume the position name of the columns is A,B,C respectively):

Entry   Price
Quantity (BTC)
Average Entry   Price

16500
0,1
=B3/(B3/A3)

16400
0,1
=(A3 * B3+A4 * B4)/(B3+B4)

16300
0,1
=(A3 * B3+A4 * B4+A5 * B5)/(B3+B4+B5)

16200
0,1
=(A3 * B3+A4 * B4+A5 * B5+ A6*B6)/(B3+B4+B5+B6)

Finally, the results were the following:

Entry   Price
Quantity (BTC)
Average Entry   Price

16500
0,1
16500

16400
0,1
16450

16300
0,1
16400

16200
0,1
16350

Problem
How could I automate the calculation of the Average Entry Price for every new value of Entry Prices and Quantity pasted in the last row of the table? The expected output would be something like this:

Entry   Price
Quantity (BTC)
Average Entry   Price

16500
0,1
16500

16400
0,1
16450

16300
0,1
16400

16200
0,1
16350

16100
0,1
16300

16000
0,1
16250

15900
0,1
16200

A: Assuming you are indeed working with a table as per your description:

Formula in C2:
=SUMPRODUCT(INDEX([Entry Price],1):[@[Entry Price]],INDEX([Quantity (BTC)],1):[@[Quantity (BTC)]])/SUM(INDEX([Quantity (BTC)],1):[@[Quantity (BTC)]])

This will now autopopulate upon new entries:


text:
Q: How to write find command to delete 7 days older files with selected JPGs ? I use Linux on Centos
And I need to remove the JPG in a file for more than 7 days.
But can't delete the JPG of the main directory
example: find /users/mac/desktop/test/*
Will output
/users/mac/desktop/test/test.jpg
/users/mac/desktop/test/test01
/users/mac/desktop/test/test01/test01.jpg
/users/mac/desktop/test/test02
/users/mac/desktop/test/test02/test02.jpg

But I only need delete this two .jpg
/users/mac/desktop/test/test01/test01.jpg
/users/mac/desktop/test/test02/test02.jpg

A:
I need to remove the JPG in a file for more than 7 days.  But can't delete the JPG of the main directory

find /users/mac/desktop/test -mtime +7 -mindepth 2 -type f -name '*.jpg' -delete

*

*-mtime +7 the modification time of the file is older then 7 days

*-mindepth 2 ignore the "main directory"

*-type f only files

*-name '*.jpg' only jpg files

*-delete delete them

A: find /users/mac/desktop/test/*/*


text:
Q: MOSFET Cell Balancing Circuit I'm designing a simple cell balancing for charging LiPoFe4 cells in series. In order to prevent overcharging, when on of the cells reach the maximum charing voltage, the microcontroller will enable the mosfet, to bypass the current to the next cell.
Consider the following circuit, where the 3.2V sources represent two cells, only with the top cell presenting the balancing circuit.

simulate this circuit – Schematic created using CircuitLab
For the mosfet I intend to use, the max threshold gate voltage is 2.5V. Assuming the worst case scenario, the botom cell being fully charger, I'll have a Vs of 3.2V. With the bypass enabled, I'll have Vg of 5V from the microcontroller. Thus, I won't achieve the Vgs = 2.5V, and the mosfet won't transit onto its 'on' state.
The question, what would be the best way of workaroud here, not changing the mosfet? I thought, maybe, add a greater voltage reference and control this one with the microcontroller,but I still think there's something simple I'm missing.
Thanks in advance!

A: You could pull the gate up to the upper cell + terminal with the high value resistor and then pull it down to turn the MOSFET off, for example with a BJT or another MOSFET (open collector/open drain).
However, the "threshold" voltage is not what you want to look at-- you want a gate voltage that will guarantee a certain Rds(on) so as not to cook your transistor. The only iron-clad guarantee on that datasheet is for 4.5V Vgs, so I would suggest using a MOSFET with guaranteed performance (Rds(on)) with 3V or lower Vgs. Also you should take care that the voltage under fault conditions (for example with the battery removed) cannot come close to exceeding the Vgs maximum rating (usually 10-20V, but sometimes lower). The MOSFET gate oxide can be protected with back-to-back zeners (between gate and source), if necessary.


text: Q: Opening multiple notebooks in Linux Mint Cinnamon I installed mathematica on Linux mint cinnamon latest edition and it works, but with one annoying issue: when there is a notebook open and I click on another notebook in the file manager, a whole new instance of the mathematica application launches (with a new startpage that needs to be closed separately at the end). How can I launch the new notebook from the file manager in the already running app? Is it not a problem to have two instances of mathematica running? I think it affects the performance or the interface is laggier if there are two.


text:
Q: A better word for 'hot' (spicy)? I never know how to order food correctly but succinctly the first time. :(
Basically: I can't eat hot stuff (i.e. most pepper, similar spices, ...).
On the one hand, I don't want to say "Please don't make it spicy", because I really don't mind spice (heck, a lot of them are great!) -- I just don't want it to be hot spice.
On the other hand "Please don't make it hot" would seem to imply I'd like my food cold!
Possibilities I've considered:

*

*"Please don't add hot spice" just sounds weird

*"Please don't add pepper" is the best I've thought of so far, but I'm pretty sure I've come across foods without pepper (or apparently so) which nevertheless tasted pretty hot.
And not just that, but it would also exclude bell peppers, etc. which I don't mind much.
Any ideas for how to communicate this clearly? The fewer words the better, haha.

A: I can't speak for other nationalities, but if you are speaking to an American English speaker, they will very likely understand "hot" to mean "spicy", and "spicy" to mean "with hot spice".
I have never actually considered "spicy" to mean anything other than "with hot spice". If you are talking about something that everyone knows has hot spice on it, they will assume that you want it to not have hot spice 999 times out of 1000 if you say:

*

*"I don't want it too hot" - or - "not too hot"

*"not too spicy"

They will probably get it if you are ordering food that comes with hot spice.

A: If you don't mind venturing into foreign tongues, you might find that French piquant fits the bill.

A: Rather than trying to negate one of two terms which are both unfortunate homonyms, you might be better off using a positive term to describe what you do want rather than what you don't.
In other words, simply order it mild.

A: Personally, I've had no problems with being understood, when I've said "spicy hot". If you want to be perfectly clear and straight to the point, saying spicy hot is fine.

A: You are worried about mixing 2 forms of hot:

*

*spicy hot

*temperature hot

If you are using English in America, saying don't make it too spicy will be understood as don't make it too "spicy hot" if the food is generally hot due to the spices that are in the food.
However, if it is a food with many spices (not just hot ones), you may want to say "don't make it too spicy hot" for extra clarity.
I would agree that you should avoid saying "don't make it too hot" to avoid mixing the two forms of hot I mentioned above.
Hope that helps!

A: If you want to be pedantic you could say:

I am intolerant of capsaicinoids.

Anyone who frequently works with hot peppers should understand, though may think you a bit odd.

A: The Spanish word, piqua for hot as in spicy hot sounds great to me. When referring to hot as in the temperature we could just use hot. Piqua sounds better to me than the French piquant in a poetical sense. It is more expressive of and describes a literal experience of cayenne or chili better. I am going to popularize the word piqua in English to mean spicy hot.

A: There are 2 uses for the word HOT when it comes to food.
Hot could mean
1.) Its Spicy as in the taste of chili in the mouth.
2.) The food temperature is hot and just above boiling point.
One good way to differentiate the 2 meaning, is to try to replace the word with an antonym. You may use this example if you wish.
Blistering - for the hot temperature food.
ie " Remember the baked meat must be blistering before you take it out of the oven "
Red-Hot - For spicy tasting food.
ie " Warning! This Malaysian Sambal Sauce will leave a red-hot taste in the mouth "


text:
Q: Laravel get TimeZone not working Iam trying to convert UTC timezone to Singapore Time
    echo $Date->format('Y-m-d H:i:s');
    echo '
';
    echo with(new Carbon\Carbon($Date->format('Y-m-d H:i:s')))->tz('Asia/Singapore')->format('Y-m-d H:i:s');
    exit;

it works fine in Localhost but in aws server it displays utc Time for both...Both server and Localhost is set to UTC Time .. how do we fix this??

A: I assume that $Date in your case is DateTime object (or Carbon object). You can use PHP setTimeZone() and DateTimeZone:
$Date = new DateTime($user->updated_at); // sample DateTime creation - also $Date = $user->updated_at; would work here

echo $Date->format("Y-m-d H:i:s")."
";

$Date->setTimezone(new DateTimeZone('Asia/Singapore'));
echo  $Date->format("Y-m-d H:i:s")."
";

For me it generates:
2014-09-19 12:06:15
2014-09-19 20:06:15

A: I assumed that, the $Date variable you have is a Carbon (By default available in Laravel) object:
$Date->format('Y-m-d H:i:s');

Now to set the timezone you may use any one of these:
$Date->timezone = new DateTimeZone('Asia/Singapore');
$Date->timezone = 'Asia/Singapore';
$Date->tz = 'Asia/Singapore';

You may also set it from your app/config/app.php like:
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/

'timezone' => 'Asia/Singapore',

A: Try this it will work
 $timestamp ='1411205843'  //Timestamp which you need to convert

 $sourceTimezone = new DateTimeZone('UTC');

 $destinationTimezone = new DateTimeZone('Asia/Singapore');

 $dt = new DateTime(date('m/d/Y h:i A', $timestamp), $sourceTimezone);
 $dt->setTimeZone($destinationTimezone);

 echo strtotime($dt->format('m/d/Y h:i A'));

A: You can set to session like below;
 Session::put('timezone', 'Your/TimeZone');

Enjoy your Code !


text:
Q: Design pattern for many if statement and Boolean condition? I am wondering if there is any design pattern for such situation:
private static boolean check(String s) {
    if(isBook(s)) {
        System.out.println("Book");
        return false;
    }else if(isEmail(s)) {
        System.out.println("Email");
        return false;
    }
    return true;
}

private static boolean isBook(String s) {
    if(s.equals("B")) return true;
    return false;
}

private static boolean isEmail(String s) {
    if(s.equals("E")) return true;
    if(s.length() > 4) return true;
    return false;
}

There will be many isXXX in check method, but I don't wanna to have many if-else statement.

A: Instead of creating an is... method for each possible type, introduce an enumeration and make one method that returns the type.
This way you can easily use a switch statement.

A: Since you have many isXXX checks, I would make the system more generic in order to avoid a huge switch (or if/else)
private static boolean check(String s, Collection<Predicate<String>> rules)
{
    return rules.stream()
                .noneMatch(rule -> rule.test(s));
}

Declare your rules as follow
Predicate<String> isBook = s -> s.equals("B");
Predicate<String> isEmail = s -> s.equals("E") || s.length() > 4;

Usage
check("E", Arrays.asList(isBook, isEmail)); //false
check("B", Arrays.asList(isBook, isEmail)); //false
check("Emo", Arrays.asList(isBook, isEmail)); //true
check("Email", Arrays.asList(isBook, isEmail)); //false


text:
Q: Cannot prevent my service from registering with Eureka I have a Spring Boot application with the following config:
eureka:
  client:
    enabled: true
    registerWithEureka: false
    serviceUrl:
      defaultZone: http://somehost:9999/eureka/
  registration:
    enabled: false

My service makes use of Eureka to discover external services, but I don't want it to register with Eureka. Despite the above config I still see the following in my logs, which is odd:
DiscoveryClient - Not registering with Eureka server per configuration
...
EurekaServiceRegistry - Registering application foo with eureka with status UP

The first log line makes sense - it's what I want. However, the second log line doesn't make sense given the config. Am I missing a setting?

A: You didn't missing anything and your configuration is right. The second log just says that what happened in your local process.
The all periodic tasks that are related to actual registration process (ex heartbeat, instance info replication) with Eureka server are not scheduled by your configuration. So registration with Eureka server will not happen.


text:
Q: Unable to replace/delete \xa0 from a string in Python (parsing from Excel)     from collections import Counter
    from openpyxl import load_workbook

    nomefile = 'SerieA18_19.xlsx'

    wb = load_workbook(nomefile)
    ws = wb.worksheets
    sheet = wb.active
    max_row = sheet.max_row

    results = []
    for i in range(1, max_row + 1):
      cell_obj = sheet.cell(i, 1).value
      cell_obj.strip()
      cell_obj.replace('\\xa0', ' ')
      if cell_obj[2:3] == '-':
         results.append(cell_obj)
      if cell_obj[3:4] == '-' and cell_obj[:1] != '(':
         results.append(cell_obj)

    results_counter = Counter()
    for response in results:
       results_counter.update(response.split(','))

    print(results_counter)

OUTPUT is as follows :
        Counter({'1\xa0-\xa01': 44, '2\xa0-\xa01': 39, '1\xa0-\xa00': 35, '0\xa0-\xa00': 34, '2\xa0-  \xa00': 28, '0\xa0-\xa01':
I am not able to delete/replace these '\xa0' that are probably coming from the Excel file

A: String in python is immutable. You need to assign the value to a variable.
Replace
cell_obj.strip()
cell_obj.replace('\\xa0', ' ')

with
  cell_obj = cell_obj.strip().replace(u'\xa0', u' ')

\xa0 is actually non-breaking space in Latin1 (ISO 8859-1), also chr(160).
When .encode('utf-8'), it will encode the unicode to utf-8, that means every unicode could be represented by 1 to 4 bytes. For this case, \xa0 is represented by 2 bytes \xc2\xa0.
Read up on http://docs.python.org/howto/unicode.html.


text:
Q: Command works in terminal but do not work in crontab i have a problem with executing terminal simple command in crontab.
Terminal view:
touch  /home/eugene/`date +%d-%m-%y-%s`.txt

Crontab view:
* *     * * *   root    touch  /home/eugene/`date +%d-%m-%y-%s`.txt

If i run this command in terminal, everything works perfect.
Cron log file view (File: /var/log/cron.log):
Aug 30 22:15:01 eugene-desktop CRON[8809]: (root) CMD (   touch  /home/eugene/`date +)
Aug 30 22:16:01 eugene-desktop CRON[8859]: (root) CMD (   touch  /home/eugene/`date +)
Aug 30 22:17:01 eugene-desktop CRON[8896]: (root) CMD (   touch  /home/eugene/`date +)

A: The crontab requires full path of the command. The normal path is not used in crontab.
Try /bin/touch or /usr/bin/touch, instead of just touch

A: I believe your script should be:
* * * * *   root  /usr/bin/touch  /home/eugene/`date +%d-%m-%y-%s`.txt

The full path to the touch command should be used


text:
Q: Generating word document document in sharepoint 2010 I want to generate word document within the sharepoint environment programmatically. How can achieve this.

A: You can achieve your goal using Office XML SDK to generating document programmatically.
here is a link to download  : http://www.microsoft.com/en-us/download/details.aspx?id=5124


text:
Q: Twilio nodejs answer phone example not working I am using the following code example: RESPOND TO INCOMING PHONE CALLS IN NODE.JS
I am using twilio package version 3.3.0.  The error I am receiving is twilio.TwimlResponse is not a constructor. Thoughts...Thanks in advance!

A: Soooo, it never fails.  This was my first question and I knew as I was typing it this had to be something simple that I was missing :-/  Well, the example pages has a little link in the right corner for version.  Sure enough, the default version is 2.x.  Guess what happens when you click the 3.x example...It works!!!  Geez.  Oh well, at least I didn't waste a full day on it :-)  Thanks!


text:
Q: Lock feature when N taps reached per day I am trying to add some code that locks or unlocks an app feature depending on the times a button is tapped per day.
So I f user taps button, for example, 3 times the feature is locked until next day. I am using some code for time control like this:
// My dates:
NSDate * today = [NSDate date];
NSDate * yesterday = [[NSUserDefaults standardUserDefaults] objectForKey:@"YESTERDAY"];
NSDate * refDate; // your reference date

// 10 first characters of description is the calendar date:
NSString * todayString = [[today description] substringToIndex:10];
NSString * yesterdayString = [[yesterday description] substringToIndex:10];
NSString * refDateString = [[refDate description] substringToIndex:10];

if ([refDateString isEqualToString:todayString])  {
    NSLog(@"Today");

} else if ([refDateString isEqualToString:yesterdayString])  {
    NSLog(@"Yesterday");

} else  {
    NSLog(@"%@", refDateString);
}

Now I should add the button action, but it is going to be a very ugly function. Does any body knows a pod for this purposes?

A: I have found the way of beautify the NSDate function like this:
NSDate *lastButtonDate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"YESTERDAY"];
if(![[NSCalendar currentCalendar] isDateInToday:lastButtonDate]){
     // One day has passed away and we can store the new date
     NSDate *today= [NSDate date];
     [[NSUserDefaults standardUserDefaults] setObject:today forKey:@"YESTERDAY"];
}

Now I need to add the button part, I mean, n times to lock the content I want to trigger.

A: This is my last try of the function, it returns YES if the limit of button taps was reached and NO if it is not already reached.
- (BOOL)isContentLockedByTaps
{
    NSInteger buttonTaps = (NSInteger)[[[NSUserDefaults standardUserDefaults] objectForKey:@"buttonTaps"] integerValue] + 1;
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%ld", buttonTaps] forKey:@"buttonTaps"];
    NSLog(@"#### buttonTaps: %ld", (long)buttonTaps);

    NSDate *lastTimeButtonTapDate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"lastTimeButtonTapDate"];
    if(![[NSCalendar currentCalendar] isDateInToday:lastTimeButtonTapDate]){
        // Executed once per day. Save the first time the button is tapped.
        // And resets the button taps once per day.
        NSLog(@"#### Executed once per day");
        NSDate *today= [NSDate date];
        [[NSUserDefaults standardUserDefaults] setObject:today forKey:@"lastTimeButtonTapDate"];
        // Reset & Update button taps.
        buttonTaps = 0;
        [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%ld", buttonTaps] forKey:@"buttonTaps"];
        // Content not locked
        return NO;

    }else{
        // Executed everytime except one time per day.
        NSLog(@"#### Executed everytime per day -1");
        if(buttonTaps > 3){
            NSLog(@"#### buttonTaps reached daily limit");
            // Content locked
            return YES;
        }else{
            NSLog(@"#### buttonTaps allowed");
            // Content not locked
            return NO;
        }
    }

    // Content locked by default
    return YES;
}


text:
Q: Cnditional expectation of exponential on UDF Let $X$ be an exponential random variable with $\lambda = 5$ and $Y$ a uniformly distributed random variable on $(-3,X)$. Find $\mathbb{E}[Y]$.
I tried to solve it by just integrating $f(y)$ from $(-3, x)$, but that doesn't seem to be working.

A: The (conditional) expectation of $Y$ is $\frac{X+3}{2}$. So you want
$$\int_0^\infty \frac{x+3}{2}\cdot 5e^{-5x}\,dx.$$
Here I am assuming that by the exponential with parameter $\lambda$ you mean that the density function is $\lambda e^{-\lambda x}$, $x\gt 0$. More infrequently, some people think of it as having density $\frac{1}{\lambda}e^{-x/\lambda}$.

A: You know that $\mathsf E(X)=\lambda^{-1} = 1/5$ and $\mathsf E(Y\mid X)=(X+3)/2$ , from what was given.
So you may make good use of the tower rule (aka the Law of Iterated Expectation). $$\mathsf E(Y)=\mathsf E(\,\mathsf E(Y\mid X)\,)$$


text:
Q: Segmentation fault in c I'm trying to write a program that checks palindrome.
But somehow I get a segmentation fault.
This program:
#include <stdio.h>

int palindrome(char *beginning); //functions declaration

int main()
{
    char str[255],c; //variables
    int i=0;

    printf("please enter a string: "); //message to user
    fgets(str,255,stdin);
    palindrome(str[255]);

    return 0;
}

int palindrome(char *beginning) //functions to chack palindrome
{

    char *end = beginning + strlen(beginning) -1;

    if (end - beginning <= 0)
        return 1;

    if (!isalpha(*beginning))
        palindrome(beginning+1);

    if (!isalpha(*end))
        {
            *end = '\0';
            palindrome(beginning);
        }

    if (*beginning == *end)
        {
            *end = '\0';
            return palindrome(beginning+1);
        }
    return 0;

}

A: char str[255] holds 255 values. With palindrome(str[255]); you attempt to pass the 256th(!) value of str, which doesn't exist.
What's more, palindrome accepts a char *, pointer to char, but you're passing a char, which'll lead to a bunch of other errors. You're probably looking for &str[254] or, as pointed out in the comments, merely palindrome(str), which is more likely.

A: There are a few things wrong with your code.
Firstly, if you're trying to pass a char [] array to a function, just pass the array name itself, i.e. (function(array)); passing array[index] is passing the value at the specific index you include.  Since the index you mention 255 is actually out of bounds of the array, you are accessing a value that isn't even in your array - even if you were calling a function that accepted a single char as an argument, this would be incorrect.
I wouldn't implement palindrome to be recursive unless it's a specific requirement for your assignment/coursework. Technically, this is all you need for a palindrome test (you may omit the parameter len and call strlen in your function to determine the length if you wish):
int ispalindrome(char *str, int len)
{
    char *p = &str[0];
    char *q = &str[len - 1];
    do
    {
        if(p >= q)
        {
            return 1;
        }
    }
    while (*p++ == *q--);
    return 0;
}


text:
Q: Azure Custom Resource Provider to Azure Resource Graph Database I am new to azure and I am trying to figure out things. I created a custom resource provider which would be retrieving few data from an endpoint. When I do a GET call to my custom provider I am able to see the data coming from the endpoint, but I would like this data to be stored within the Resource Graph DB so I can write queries to verify the data.
Could someone let me know if this use case is possible? If so how can I do it?
Thank you in Advance !


text:
Q: Using PHP Sessions in a quiz I have made a yes/no quiz where the game tries to guess what creature you are thinking of based on these questions, there are only 16 possible answers.
What I am trying to is make it so that if the user closes the site part-way through the quiz then when they return to the quiz they will taken to the same question they left off on. Below is what I have done so far but it doesn't work properly (see for yourself at http://s504518.brunelweb.net/Creatures.php) You must answer yes to the first question and then close the browser as I have only done a session for that question so far. Here is part of the what I have done so far
//These are used for saving the session
 $q2 = "

{$questions[0][0]}

";
 $q3 = "

{$questions[0][1]}

";

 $f2 = "
<form method ='GET' action='Creatures.php'>
     <input type='submit' name='answer1' value='Yes' class='buttons' />
     <input type='submit' name='answer1' value='No' class='buttons' />
     </form>
";
 $f3 = "
<form method ='GET' action='Creatures.php'>
     <input type='submit' name='answer2' value='Yes' class='buttons' />
     <input type='submit' name='answer2' value='No' class='buttons' />
     </form>
";

//If start button has not been pressed, display nothing
if (!isset($_POST['start'])){

} //If start button has been pressed, display questions
else
{
//Display the first question
echo $firstquestion;
     echo "
<form method ='GET' action='Creatures.php'>
     <input type='submit' name='yes1' value='Yes' class='buttons' />
     <input type='submit' name='no1' value='No' class='buttons' />
     </form>
";
}
//Question 2
if (isset($_SESSION['form']))
{
echo $_SESSION['question'];
echo $_SESSION['form'];
}
else{
if ($_GET['yes1']) //If answer to Q1 is yes then display this
{
echo "

{$questions[0][0]}

";
showquestion(1);
$_SESSION['question'] = $q2;
$_SESSION['form'] = $f2;
}
}

What I am trying to achieve here is, if a session has already been set then display the question and form from that session and if it hasn't display nothing until they click the start button. I'm not sure why it doesn't work properly and any help would be much appreciated.

A: You need to create a session with session_start(), put this into the first line of php:
session_start();

As php.net tells me, it will also use already generated sessions. Just be shure you have no html-output before starting the session


text:
Q: one third container leaving white space at end css I have the following problem on a website i am building:
3 columns of equal height and 1/3 width but on the last column there is a small white gap on the right hand side.  I cant figure out why, here is what I'm talking about:
enter image description here
See the white line by the right hand side of the blog image.
The code I'm am using for the 1/3rd column is:
.thirdBox {
  float: left;
  width: 33.33%;
  width: calc(100% / 3);
  padding: 20px 40px;
  box-sizing: border-box;
  min-height: 400px;
  display: table;
}

and the background images:
.thirdBox:nth-of-type(3) {
  background: url("imagelinkhere...") no-repeat 50% 50%;
  background-size: cover;
}

A: The issue is that 100%/3 is 33.33% in most browsers, not quite the exact width you want it to be.
Instead of using calc() to find each table's width, I would use display:flex; on the parent of all three elements you want to be in one row.
This is the best I can help you with without any HTML structure. Please post that and I may be able to help you more.

.parentElement{
  display:flex;
}

.firstBox, .secondBox, .thirdBox {
  padding: 20px 40px;
  flex:1;
}

.firstBox{
  background:blue;
}

.secondBox{
  background:red;
}

.thirdBox{
  background:green;
}

A: Here is a solution using display: table:

            Menu

Some text here

            Blog

Css:
.row {
    background-color: #999;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

.col {
    float: left;
    width: 33.33%;
    min-height: 400px;
}

.col-inner {
    display: table;
  width: 100%;
    min-height: 400px;
    box-sizing: border-box;
    padding: 20px 40px;
}

.col:first-child,
.col:last-child {
    background-color: yellow;
}

.col-inner span,
.col-inner p {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}


text:
Q: Access SharePoint intranet application from Sharepoint Designer 2010 I can not access our intranet portal from SharePoint Designer 2010

*

*I enabled anonymous access in IIS for SharePoint web application

*I enabled user permissions for User Remote Interfaces

It has worked before in the last two weeks

this web application has below aam

When I enable verbose logging I find this error:
Exception returned from back end service. System.ServiceModel.ServerTooBusyException: The HTTP service located
 at http://spdv01:32843/d8223431896f4032a7e417eecf79819b/MetadataWebService.svc is too busy.  ---> System.Net.WebException: The remote server returned an error: (503) Server Unavailable.
 at System.Net.HttpWebRequest.GetResponse()
 at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)     -
 -- End of inner exception stack trace ---    Server stack trace:
 at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
 at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
 at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
 at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
 at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
 at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
 at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
 at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
 at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)    Exception rethrown
 at [0]:
 at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
 at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
 at Microsoft.SharePoint.Taxonomy.IMetadataWebServiceApplication.GetServiceSettings(Guid rawPartitionId)
 at Microsoft.SharePoint.Taxonomy.MetadataWebServiceApplicationProxy.<>c__DisplayClass2f.<ReadApplicationSettings>b__2e(IMetadataWebServiceApplication serviceApplication)
 at Microsoft.SharePoint.Taxonomy.MetadataWebServiceApplicationProxy.<>c__DisplayClass2c.<RunOnChannel>b__2b()

A: I   was able to resolve this issue by web.config file change.
The following entry in the web.config file was missing:
serviceHostingEnvironment aspNetCompatibilityEnabled="true"

under the system.serviceModel tag of the Web Application web.config.
I added the entry again and the issue was fixed.
http://mrhodes.net/2010/03/30/sharepoint-designer-2010-the-server-could-not-complete-your-request-the-content-type-of-the-response-is-8/


text:
Q: Git checkout branches to their own folders Some time ago I watched a video on YouTube where a guy explained how you can clone a repo in some kind of a special way and then checkout branches to their own directories in that root repo folder, so that you can work on several branches in parallel without having to stash stuff or make intermediate commits, and just switch to that other directory. Probably even open them in your IDE.
I thought I'd give it a try, but I can't find any documentation on that. All I can find relates to checking out specific directories, and not to what I want.
Can anyone direct me to the right documentation on this?


text:
Q: UNREAL ENGINE 4 Cast Failed Когда я пытаюсь сделать cast to thirdperson character каст не срабатывает , как я предполагаю скорее всего  это происходит из-за try get pawn owner,  потому что когда вызываю функцию is valid из try  get pawn owner она возвращает is not valid.  Я пытался это  пофиксить cоздавал object reference  на моего  героя его  подсоединял к обьекту  cast to  thirdperson character .  из Меша героя вытягивал anim instance  подсоединял это к таргету try get pawn owner.  вместо  try get pawn owner пытался использовать  get character  player. Все безуспешно от  отчаянья я подумал может быть это происходит  из-за с++(герой на нем),  cоздавал новый класс на  Блупринтах и новый АнимБлупринт для него  ,но результат такой же .
Как пофиксить и сделать так  чтобы try get pawn ownere  был  Valid.
Картинка  ниже  показывает эту кашу.

A: Чтобы сделать Cast на вашего Character можно использовать get player controller, либо что-то связанное с get pawn, точнее сейчас не скажу


text:
Q: IE asks for security certificate approval twice for self signed applet Using RXTX and Java applet, I have created an applet to dial a telephone number.
Its wokring fine ,but when browser loads the applet , security certificate approval pop up comes twice.
when I click on RUN when the security pop up comes first time and why does the pop up come again.
my applet is in click2callapplet.jar and uses RXTXcomm.jar both of which are self-signed by the same certificate.
log of the java console is attached below. Any kind of help would be kindly appreicaated.
Java Plug-in 10.1.0.8
Using JRE version 1.7.0_01-b08 Java HotSpot(TM) Client VM
User home directory = C:\Users\hcluser2
----------------------------------------------------
c:   clear console window
f:   finalize objects on finalization queue
g:   garbage collect
h:   display this help message
l:   dump classloader list
m:   print memory usage
o:   trigger logging
q:   hide console
r:   reload policy configuration
s:   dump system and deployment properties
t:   dump thread list
v:   dump thread stack
x:   clear classloader cache
0-5: set trace level to <n>
----------------------------------------------------
Detected from bootclasspath: C:\\PROGRA~1\\Java\\jre7\\lib\\deploy.jar
security: property package.access value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.
security: property package.access new value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.javaws
security: property package.access value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.javaws
security: property package.access new value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.javaws,com.sun.deploy
security: property package.access value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.javaws,com.sun.deploy
security: property package.access new value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.javaws,com.sun.deploy,com.sun.jnlp
security: property package.definition value null
security: property package.definition new value com.sun.javaws
security: property package.definition value com.sun.javaws
security: property package.definition new value com.sun.javaws,com.sun.deploy
security: property package.definition value com.sun.javaws,com.sun.deploy
security: property package.definition new value com.sun.javaws,com.sun.deploy,com.sun.jnlp
security: property package.access value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.javaws,com.sun.deploy,com.sun.jnlp
security: property package.access new value sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.javaws,com.sun.deploy,com.sun.jnlp,org.mozilla.jss
security: property package.definition value com.sun.javaws,com.sun.deploy,com.sun.jnlp
security: property package.definition new value com.sun.javaws,com.sun.deploy,com.sun.jnlp,org.mozilla.jss
basic: Added progress listener: sun.plugin.util.ProgressMonitorAdapter@156a6be
basic: Plugin2ClassLoader.addURL parent called for http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar
basic: Plugin2ClassLoader.addURL parent called for http://172.30.13.226:9080/3in1srv/Click2CallJars/RXTXcomm.jar
security: Blacklist revocation check is enabled
security: Trusted libraries list check is enabled
network: Cache entry found [url: http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar, version: null] prevalidated=false/0
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/ with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar with cookie "JSESSIONID=00004p01LsRXIYU5nbHw-wTqpNy:-1"
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/ with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar with cookie "JSESSIONID=00004p01LsRXIYU5nbHw-wTqpNy:-1"
cache: Reading Signers from 995 http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar | C:\Users\hcluser2\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\10\21db2eca-604fb61f.idx
cache:  Read manifest for http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar: read=449 full=449
security: Loading Deployment certificates from C:\Users\hcluser2\AppData\LocalLow\Sun\Java\Deployment\security\trusted.certs
security: Loaded Deployment certificates from C:\Users\hcluser2\AppData\LocalLow\Sun\Java\Deployment\security\trusted.certs
security: Loading certificates from Deployment session certificate store
security: Loaded certificates from Deployment session certificate store
security: Loading certificates from Internet Explorer TrustedPublisher certificate store
security: Loaded certificates from Internet Explorer TrustedPublisher certificate store
security: Validate the certificate chain using CertPath API
security: Loading certificates from Internet Explorer ROOT certificate store
security: Loaded certificates from Internet Explorer ROOT certificate store
security: Loading Root CA certificates from C:\Program Files\Java\jre7\lib\security\cacerts
security: Loaded Root CA certificates from C:\Program Files\Java\jre7\lib\security\cacerts
security: Obtain certificate collection in Root CA certificate store
security: Obtain certificate collection in Root CA certificate store
security: Obtain certificate collection in Root CA certificate store
security: Obtain certificate collection in Root CA certificate store
security: The certificate hasnt been expired, no need to check timestamping info
security: Found jurisdiction list file
security: No need to checking trusted extension for this certificate
security: The CRL support is disabled
security: The OCSP support is disabled
security: This OCSP End Entity validation is disabled
security: Checking if certificate is in Deployment denied certificate store
security: Checking if certificate is in Deployment permanent certificate store
security: Checking if certificate is in Deployment session certificate store
security: Checking if certificate is in Internet Explorer TrustedPublisher certificate store
security: User has granted the priviledges to the code for this session only
security: Adding certificate in Deployment session certificate store
security: Added certificate in Deployment session certificate store
security: Saving certificates in Deployment session certificate store
security: Saved certificates in Deployment session certificate store
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/ with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar with cookie "JSESSIONID=00004p01LsRXIYU5nbHw-wTqpNy:-1"
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/ with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar with cookie "JSESSIONID=00004p01LsRXIYU5nbHw-wTqpNy:-1"
security: Validate the certificate chain using CertPath API
security: The certificate hasnt been expired, no need to check timestamping info
security: Found jurisdiction list file
security: No need to checking trusted extension for this certificate
security: The CRL support is disabled
security: The OCSP support is disabled
security: This OCSP End Entity validation is disabled
security: Checking if certificate is in Deployment denied certificate store
security: Checking if certificate is in Deployment permanent certificate store
security: Checking if certificate is in Deployment session certificate store
basic: Plugin2ClassLoader.getPermissions CeilingPolicy allPerms
network: Cache entry found [url: http://172.30.13.226:9080/3in1srv/Click2CallJars/RXTXcomm.jar, version: null] prevalidated=false/0
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/RXTXcomm.jar with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/ with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/RXTXcomm.jar with cookie "JSESSIONID=00004p01LsRXIYU5nbHw-wTqpNy:-1"
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/RXTXcomm.jar with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/ with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/RXTXcomm.jar with cookie "JSESSIONID=00004p01LsRXIYU5nbHw-wTqpNy:-1"
cache: Reading Signers from 994 http://172.30.13.226:9080/3in1srv/Click2CallJars/RXTXcomm.jar | C:\Users\hcluser2\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\24\4abc9f18-5d59227f.idx
cache:  Read manifest for http://172.30.13.226:9080/3in1srv/Click2CallJars/RXTXcomm.jar: read=86 full=1769
security: Validate the certificate chain using CertPath API
security: The certificate hasnt been expired, no need to check timestamping info
security: Found jurisdiction list file
security: No need to checking trusted extension for this certificate
security: The CRL support is disabled
security: The OCSP support is disabled
security: This OCSP End Entity validation is disabled
security: Checking if certificate is in Deployment denied certificate store
security: Checking if certificate is in Deployment permanent certificate store
security: Checking if certificate is in Deployment session certificate store
security: Checking if certificate is in Internet Explorer TrustedPublisher certificate store
security: User has granted the priviledges to the code for this session only
security: Adding certificate in Deployment session certificate store
security: Added certificate in Deployment session certificate store
security: Saving certificates in Deployment session certificate store
security: Saved certificates in Deployment session certificate store
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/RXTXcomm.jar with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/ with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/RXTXcomm.jar with cookie "JSESSIONID=00004p01LsRXIYU5nbHw-wTqpNy:-1"
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/RXTXcomm.jar with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/ with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/RXTXcomm.jar with cookie "JSESSIONID=00004p01LsRXIYU5nbHw-wTqpNy:-1"
security: Validate the certificate chain using CertPath API
security: The certificate hasnt been expired, no need to check timestamping info
security: Found jurisdiction list file
security: No need to checking trusted extension for this certificate
security: The CRL support is disabled
security: The OCSP support is disabled
security: This OCSP End Entity validation is disabled
security: Checking if certificate is in Deployment denied certificate store
security: Checking if certificate is in Deployment permanent certificate store
security: Checking if certificate is in Deployment session certificate store
basic: Plugin2ClassLoader.getPermissions CeilingPolicy allPerms
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/ with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar with cookie "JSESSIONID=00004p01LsRXIYU5nbHw-wTqpNy:-1"
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/ with proxy=DIRECT
network: Connecting http://172.30.13.226:9080/3in1srv/Click2CallJars/Click2CallApplet.jar with cookie "JSESSIONID=00004p01LsRXIYU5nbHw-wTqpNy:-1"
security: Validate the certificate chain using CertPath API
security: The certificate hasnt been expired, no need to check timestamping info
security: Found jurisdiction list file
security: No need to checking trusted extension for this certificate
security: The CRL support is disabled
security: The OCSP support is disabled
security: This OCSP End Entity validation is disabled
security: Checking if certificate is in Deployment denied certificate store
security: Checking if certificate is in Deployment permanent certificate store
security: Checking if certificate is in Deployment session certificate store
basic: Applet loaded.
basic: Applet resized and added to parent container
basic: PERF: AppletExecutionRunnable - applet.init() BEGIN ; jvmLaunch dt 217677 us, pluginInit dt 20753021 us, TotalTime: 20970698 us
Telephone Number from JSP:0196523759
Telephone Prefix from JSP:9
basic: Applet initialized
basic: Starting applet
basic: completed perf rollup
Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version   = RXTX-2.1-7
>>> ATZ
<<< ATZ
<<<
>>> ATDT9023523759
<<< OK
WARNING: Modem did not echo command.
<<< ATDT9023523759
basic: Applet made visible
basic: Applet started
basic: Told clients applet is started
basic: Starting applet teardown
basic: Finished applet teardown
basic: Removed progress listener: sun.plugin.util.ProgressMonitorAdapter@156a6be
plugin2manager.parentwindowDispose


text:
Q: How to catch any link that came from upload/ in laravel 5? im new in laravel 5.2, I just want to ask how you can catch a link that came from uploads like: http://sitename.com/uploads/59128.txt? I want to redirect them to login page if they tried to access any of route or link that came from uploads/{any filename}.

A: Yes you can achieve by protecting your route with auth middleware,
make a small FileController
class FileController extends Controller {
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function getFile($filename)
    {
        return response()->download(storage_path($filename), null, [], null);
    }
}

and then in routes.php
Route::get('file/{filename}', 'FileController@getFile')->where('filename', '^[^/]+$');
And that's it. Now, your authenticated users can download files from storage folder (but not its subfolders) by calling http://yoursite.com/file/secret.jpg. Add you can use this URL in src attribute of an image tag.
answer's original source!

A: @xerwudjohn simple you can't.
When this file is in the public folder, everyone can access it whitout being logged in.
One method I tried for some minutes, create a new route:
Route::group(['middleware' => ['web', 'auth']], function () {
   Route::get('/download/{id}', 'DownloadController@showFile');
});

create the function showFile in the DonwloadController
public function showFile($id)
{
    return redirect('/image/'.$id.'.txt');
}

or use a Model to read uniqueIds out of any table and get the realfile name.
Cheers


text:
Q: UIDocumentPickerViewController -> "No Documents" because iCloud not available I use this method to show an UIDocumentPicker:
func showDocumentPicker(){
  let docPicker = UIDocumentPickerViewController(documentTypes: ["public.composite-content "], inMode: UIDocumentPickerMode.Import)
  docPicker.delegate = self
  docPicker.modalPresentationStyle = UIModalPresentationStyle.FullScreen
  self.presentViewController(docPicker, animated: true, completion: nil)
}

The UIDocumentPicker gets displayed nicely, but it always shows

No Document, Documents in iCloud Drive are not available because the iCloud Documents & Data setting is disabled

But when I check the iCloud Status, iCloud Drive is enabled! (My App even shows up in the settings there, also enabled!)

This happens in Simulator and on the device (via a Prerelease distributed by Apple TestFlight)

A: This error can be caused due to invalid UTI-constants:
Make sure to double-check the UTIs you pass to the documentTypes parameter. In this case, note the blank space in the public.composite-content string


text:
Q: XML, JSON, YAML, or CSV for storing articles on server? Please help me decide between the following formats for storing articles on a server:

*

*XML

*JSON

*YAML

*CSV

There are too many and I don't have the knowledge to choose.  I am looking for objective criteria, not subjective opinions.
The articles may contain a short title, some paragraphs and images.

A: XML vs JSON vs YAML vs CSV
Here are some considerations you might use to guide your decision:
Choose XML if

*

*You have to represent mixed content (tags mixed within text).  [This would appear to be a major concern in your case.  You might even consider HTML for this reason.]

*There's already an industry standard XSD to follow.

*You need to transform the data to another XML/HTML format.  (XSLT is great for transformations.)

Choose JSON if

*

*You have to represent data records, and a closer fit to JavaScript is valuable to your team or your community.

Choose YAML if

*

*You have to represent data records, and you value some additional features missing from JSON: comments, strings without quotes, order-preserving maps, and extensible data types.

Choose CSV if

*

*You have to represent data records, and you value ease of import/export with databases and spreadsheets.


text:
Q: Go urlfetch.Transport.RoundTrip, can call in GET, but not POST? I'm having a problem getting any response from urlfetch.Transport.RoundTrip in GAE Go. When I browse a page that makes the call in a browser, the call is executed as intended. When the same function is called from a POST request made by poclbm Bitcoin miner, I can't get a response.
The call is made by this package I made at line 77.
Is it possible, that in Google App Engine one can request data from other web pages under a HTTP GET, but not POST, or is there something else that can be causing this problem?

A: You can do POST request from App Engine using http.Client.Post, just make sure you create  the http client with urlfetch.Client function.


text:
Q: Rename Custom Post Slug using taxonomy We have a custom posts called "Reviews" and rename the URL based on a taxonomy (manufacturers) selected for the post. For example if the MFG taxonomy called BENQ is selected the URL for the post will be
domain.com/benq/postname not domain.com/reviews/postname/
I'm getting this error: Warning: Missing argument 3 for custom_post_type_link(), called in /../wp-includes/class-wp-hook.php on line 288 and defined in /../wp-content/themes/understrap-child-theme/functions.php on line 1192
Here is the function:
add_filter('post_type_link', 'custom_post_type_link', 10, 2);

function custom_post_type_link($permalink, $post, $leavename) {
    if (!gettype($post) == 'post') {
        return $permalink;
    }

    $url_components = parse_url($permalink);
    $post_path = $url_components['path'];
    $post_path = trim($post_path, '/');
    $post_name = explode('/', $post_path);
    $post_name = end($post_name);

    if (!empty($post_name)) {

        if ($post->post_type == 'reviews') {

            $terms = get_the_terms($post->ID, 'manufacturers');

            if (is_array($terms)) {

                $term = array_pop($terms)->slug;
            }
            else {

                $terms = get_the_terms($post->post_parent, 'manufacturers');

                if (is_array($terms)) {
                    $term = array_pop($terms)->slug;
                }
                else {
                    $term = 'review';
                }
            }

            $permalink = str_replace($post_path, '' . $term . '/' . $post_name . '', $permalink);
        }
    }

    return $permalink;
}

Any idea of the issue?

A: You're passing 3 arguments to your function ($permalink, $post, $leavename), but you're only specifying that it has 2 when you're adding the filter (the last parameter to add_filter). Change your add_filter call to this:
add_filter( 'post_type_link', 'custom_post_type_link', 10, 3 );


text:
Q: insert order of in Many-to-Many Database Relationships with Flask-SQLAlchemy I am trying to follow the tutorial from
[Many-to-Many Database Relationships with Flask-SQLAlchemy](https://www.digitalocean.com/community/tutorials/how-to-use-many-to-many-database-relationships-with-flask-sqlalchemy)
in step2, it use a init_db.py to add some data into DB
I see that the order that post item is added to DB as
db.session.add_all([post1, post2, post3])
then it use flask shell to query from DB
Post The First [<Tag "animals">, <Tag "writing">]

Post The Third [<Tag "cooking">, <Tag "tech">, <Tag "writing">]

Post The Second []

`

I can see that post3 is using the id 2 in post table in db as in below image,

seems to me with
db.session.add_all([post1, post2, post3])
don't understand why post3 is inserted after post1?
I reproduced this in my laptop on sqlite and postgres, cannot figured out from sqlalchemy doc on session.add_all method can you help to review on it if I missed anything ?


text:
Q: GPO for Scheduled Task Server 2008 R2 (Computer reboot) I am currently running into a bit of a problem.  I am trying to create a GPO that reboots all computers in a specific OU at a specific time using Server 2008 R2 64 bit.
I have gone into GP management, created a new GPO, went to computer configuration, preferences, control panel settings, then scheduled tasks.
Right clicked and created a new scheduled task as follows:
Action: Create
Name: Test Reboot
Run: shutdown.exe /f /r
username: admin
pass: pass
Scheduled to run at said time I want.
The GPO replicates as needed.  I see it in computer management, but it never runs and gives an error message in the history.  The error message is as follows:
Task Scheduler failed to launch action "shutdown.exe /f /r" in instance "{5171f2bf-de1c-4fae-bbb8-e8db9370ed1f}" of task "\Test Reboot". Additional Data: Error Value: 2147942403.
Am I using the wrong command?  If I am can you please tell me what I should be using?

A: Command shutdown.exe /f /r seems to be ok, but I would check some settings in your scheduled task.
When you specify program to run as scheduled task, you shuold write parameters (arguments) in separate field named Arguments. In your case, you should set Run: shutdown.exe and Arguments: /f /r.


text:
Q: Custom maker in Symfony MakerBundle In Symfony MakerBundle docs there is a word about creating own makers. It says to:

create a class that extends AbstractMaker in your src/Maker/
directory. And this is really it!

Slow down there.
What about a custom template/skeleton for this new maker? I checked in Symfony\Bundle\MakerBundle\Generator class and it searches for templates like this:
$templatePath = __DIR__.'/Resources/skeleton/'.$templateName;

So when running custom maker (command) the path is still set to Symfony MakerBundle resources. Am I missing something? No clean way to generate files from custom templates?

A: Well if I look at the code in Symfony\Bundle\MakerBundle\Generator I see this:
 private function addOperation(string $targetPath, string $templateName, array $variables)
    {
        if ($this->fileManager->fileExists($targetPath)) {
            throw new RuntimeCommandException(sprintf('The file "%s" can\'t be generated because it already exists.', $this->fileManager->relativizePath($targetPath)));
        }

        $variables['relative_path'] = $this->fileManager->relativizePath($targetPath);

        $templatePath = $templateName;
        if (!file_exists($templatePath)) {
            $templatePath = __DIR__.'/Resources/skeleton/'.$templateName;

            if (!file_exists($templatePath)) {
                throw new \Exception(sprintf('Cannot find template "%s"', $templateName));
            }
        }

        $this->pendingOperations[$targetPath] = [
            'template' => $templatePath,
            'variables' => $variables,
        ];
    }

So basically, it first checks if the file exists, if it doesn't it changes the template's path to __DIR__.'/Resources/skeleton/'.$templateName; and if that file doesn't exist either, it then throws an exception.
So basically, if you provide a file path that exists to the $templateName argument, you can decide where the template is loaded from.


text:
Q: PHP script not able to connect to MS SQL database in webmatrix I am using webmatrix and trying to connect to a local database in that which is SQL database . I have IIS and SQL Server  installed on the computer . The database was created in webmatrix only .
Initially the error display was not on , I managed to do that by manipulating the php.ini file . After that I tried this script which is giving the following result .
<?php
    if (function_exists('mssql_connect')){
echo "Okay, fn is there
------------------
";
} else {
echo "Hmmm .. fn is not even there
------------------
";
}

if(extension_loaded("mssql")) {
echo "MSSQL is Loaded
";
}
else {
echo "MSSQL not loaded
";
}

if(extension_loaded("msql")) {
echo "MSQL is Loaded
";
}
else {
echo "MSQL not loaded
";
}
echo '

';

$ext = get_loaded_extensions();
if(in_array('mssql', $ext))
echo 'u have mssql installed

';
else
echo 'u do NOT have mssql installed

';

?>

The result is :
Hmmm .. fn is not even there
MSSQL not loaded
MSQL not loaded
u do NOT have mssql installed
This is the command I was using to connect to mssql database
<?php
$con=mssql_connect('.\SQLEXPRESS','Shops_localdbU','thePass');
if($con) {
echo "success";
}
?>

and output was:
Fatal error: Call to undefined function mssql_connect() in C:\xampp\htdocs\sample.php on line 3

A: May be the functions are not installed on your server. If you have access to install them, then you can do that. If not, you cannot use these functions.
If you do have permission to modify the PHP configuration, start here:
http://www.php.net/manual/en/mssql.setup.php


text:
Q: Assigning edge_keys to networkx multigraph using from_pandas_edgelist function returns errors I am trying to recreate the following script from the networkx documentation:
edges = pd.DataFrame(
{
    "source": [0, 1, 2, 0],
    "target": [2, 2, 3, 2],
    "my_edge_key": ["A", "B", "C", "D"],
    "weight": [3, 4, 5, 6],
    "color": ["red", "blue", "blue", "blue"],
})
G = nx.from_pandas_edgelist(
edges,
edge_key="my_edge_key",
edge_attr=["weight", "color"],
create_using=nx.MultiGraph(),)

When I do this, instead of getting the expected graph, I get the following error:
TypeError: from_pandas_edgelist() got an unexpected keyword argument 'edge_key'

I have tried running it after removing the edge_key="my_edge_key", part and the graph is generated just fine.
But the thing is, I am working on a large multigraph with edges having the same start and end node pairs. I need to assign keys to my graph edges because I plan to remove particular edges by their keys for the graph that I am working on. So I was wondering, if I was doing something wrong in assigning the edge keys. Or is this an outdated function and there is now a better way to do this? If so, could someone please direct me?

A: You need to update networkx to be able to use the edge_key parameter. As you can see here the version 2.4 did not had this parameter. In contrast the latest version (as you have also seen in the docs) has the parameter, see here.


text:
Q: Rate Limiting Feature for particular Route in Laravel 5.2 I am using the below code that implements Rate Limiting feature for all Routes in a Group.
Route::group(['middleware' => ['web', 'throttle:2']], function () {
    Route::get('/CSR', array('uses' =>  'CSR_Controller@index', 'as' => 'CSRList'));
    //Second Route
    //Third Route
    //Fourth Route
    //Fifth Route
    //....
});

Question
This works great. Is there any way to implement this for any particular route in a group ?

A: Of course you can. Any attribute you can assign to a route group can be assigned to a single route as well (in fact route groups really only apply their attributes sequentially to each of the routes contained within them, nothing more). So you can assign a middleware group such as api to a single route:
Route::get('/route/path', ['middleware' => 'api', 'uses' => 'Controller@action']);

Or if you want to use just the throttling middleware you can use:
Route::get('/route/path', ['middleware' => 'throttle:2', 'uses' => 'Controller@action']);

For more details on the rate limiting feature you can check out the Laracasts video linked below:

What's New in Laravel 5.2: API Rate Limiting


text:
Q: Html.Labelfor use DisplayName of object not property Given a view model like this:
public class ParentViewModel
{
    public object ChildViewModel { get; set; }
}

If I use Html.LabelFor like this:
@Html.LabelFor(model => model.ChildViewModel)

I would get an output like this:
ChildViewModel

What I actually want though is for the generated label to use the DisplayName attribute applied to the object E.G.
[DisplayName("My Custom Label")]
public class ChildViewModel
{
}

with an output of:
My Custom Label

I understand that the Html.LabelFor method takes an expression that expects a property and it will look for the DisplayName attribute on that property rather than the object itself.
I have created an Html helper method to achieve what I want that looks like this:
public static IHtmlString CreateLabel<TModel>(this HtmlHelper html, Func<TModel, object> func)
    where TModel : class
    {
        TagBuilder tb = new TagBuilder("label");

        var model = html.ViewData.Model as TModel;
        if (model != null)
        {
            object obj = func(model);
            if (obj != null)
            {
                var attribute = obj.GetType().GetCustomAttributes(
                    typeof(DisplayNameAttribute), true)
                    .FirstOrDefault() as DisplayNameAttribute;

                if (attribute != null)
                {
                    tb.InnerHtml = attribute.DisplayName;
                    return MvcHtmlString.Create(tb.ToString());
                }
                else
                {
                    tb.InnerHtml = obj.ToString();
                    return MvcHtmlString.Create(tb.ToString());
                }
            }
        }

        tb.InnerHtml = html.ViewData.Model.ToString();
        return MvcHtmlString.Create(tb.ToString());
    }

Instead of taking an expression, my helper takes a Func<TModel, object> which returns the object that I want to check for the DisplayName attribute.
The first problem I had was when I tried to call this method in razor like this:
@Html.CreateLabel(model => model.ChildObject)

I get the following error:
The type arguments for method 'CreateLabel<TModel>(this HtmlHelper,
Func<TModel, object>) cannot be inferred from usage. Try specifying
the arguments explicitly.'

So I call the method like this instead:
 @{ Html.CreateLabel<ChildViewModel>(model => model.ChildObject); }

but nothing gets rendered. If I use the debugger to step through my helper method, the label tag is being generated but nothing is shown when my page is rendered.
So my questions are:

*

*How do I fix this to generate the label to my view?

*What do I have to do so that the generic parameter can be inferred?

*Is there any way to write the Html helper to do the same thing but using an expression? I have no experience using expressions so don't know where to start.

Update
I thought I'd post the final code as I made a few minor changes. First of all I took a look at the helpers in the MVC source code and decided to split the method into three separate methods in line with the provided examples. I also removed all the TagBuilder stuff as all I really needed was to generate the text that was to be injected between the <legend></legend> tags. The final code is below. Once again, thanks to Sylon for helping me out with this.
public static IHtmlString LegendTextFor<TModel, TObject>(this HtmlHelper<TModel> html, Expression<Func<TModel, TObject>> expression)
{
    return LegendTextHelper(html,
        ModelMetadata.FromLambdaExpression(expression, html.ViewData),
        ExpressionHelper.GetExpressionText(expression),
        expression.Compile().Invoke(html.ViewData.Model));
}

private static IHtmlString LegendTextHelper<TModel, TObject>(this HtmlHelper<TModel> html, ModelMetadata metadata, string htmlFieldName, TObject value)
{
    string resolvedLabelText = metadata.DisplayName ?? value.GetDisplayName() ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();

    if (String.IsNullOrEmpty(resolvedLabelText))
        return MvcHtmlString.Empty;

    return MvcHtmlString.Create(resolvedLabelText);
}

private static string GetDisplayName<T>(this T obj)
{
    if (obj != null)
    {
        var attribute = obj.GetType()
            .GetCustomAttributes(typeof(DisplayNameAttribute), false)
            .Cast<DisplayNameAttribute>()
            .FirstOrDefault();

        return attribute != null ? attribute.DisplayName : null;
    }
    else
    {
        return null;
    }
}

A: I just created a custom Html helper for label that does what you want:
Html Helper:
public static class HtmlHelperExtensions
{

    public static MvcHtmlString LabelForCustom<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);

        string customDisplayName = null;

       var value = expression.Compile().Invoke(html.ViewData.Model);

       if (value != null)
       {
          var attribute = value.GetType().GetCustomAttributes(typeof(DisplayNameAttribute), false)
           .Cast<DisplayNameAttribute>()
           .FirstOrDefault();

           customDisplayName = attribute != null ? attribute.DisplayName : null;
       }

         string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
        string labelText = metadata.DisplayName ?? customDisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
        if (String.IsNullOrEmpty(labelText))
        {
            return MvcHtmlString.Empty;
        }

        TagBuilder tag = new TagBuilder("label");
         tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
        tag.SetInnerText(labelText);
        return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
    }
}

My example model:
public class Parent
{
    public object Child { get; set; }
}

[DisplayName("yo")]
public class Child
{
   public int Id { get; set; }
}

View:
@Html.LabelForCustom(m => m.Child)  @*prints yo*@


text:
Q: How to use a variable to define the list of arguments in a function signature? I'm developing a class in Python 3.7 with a function which overrides the run function of its base class. The run() function must be defined with a precise number of arguments, e.g def run(self, a, b), and it will behave differently based on how many arguments are defined -- its signature is inspected when the function is called, in order to provide the right arguments number to the function. In my design, the number (and names) of arguments are passed to the class when its instance is constructed.
I've looked upon modules such as functools and solutions like *args and **kwargs, but I fear they won't work for my scenario, since I don't want to 'bind' any variable before calling the function, neither I do want a variable argument list. I need a fixed list of arguments for my function, but I need to define the function using a variable which is provided to the class :)
It is probably much simpler to show my expected results:
>>>args1 = ['arg1', 'arg2']
>>>args2 = ['arg1', 'arg2', 'arg3']

...
...

>>>c1 = MyClass(run_args=args1)
>>>c2 = MyClass(run_args=args2)
>>>import inspect
>>>inspect.getargspec(c1.run)
ArgSpec(args=['self', 'arg1', 'arg2'], varargs=None, keywords=None, defaults=None)
>>>inspect.getargspec(c2.run)
ArgSpec(args=['self', 'arg1', 'arg2', 'arg3'], varargs=None, keywords=None, defaults=None)

A: This is a rather strange design, because objects from the same class are expected to share common methods, hence common method signatures.
But in Python3 every object can define an attribute with a method name, and that attribute will be used when the idiom obj.method(args) is called. And if that attribute is a function or a lambda, it can have a signature.
Here is a minimalist code demonstrating the concept:
import abc
import inspect

class Base(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def run(self, *args):
        """Just an example to show what arguments have been passed"""
        print("run method called with", *args)

class Child(Base):
    def __init__(self, run_args):
        """run_args is the list of the names of the arguments of run"""
        params = [inspect.Parameter(n, inspect.Parameter.POSITIONAL_OR_KEYWORD)
                  for n in run_args]
        # self.run is a lambda calling Child.run, but has a specific signature
        self.run = lambda *args: Child.run(self, *args)
        self.run.__signature__ = inspect.Signature(params)
    def run(self, *args):
        # controls that the signature of self.run has been observed
        inspect.signature(self.run).bind(*args)
        # do the processing - here only call the base class method
        super().run(*args)

You can now test it:
>>> c1 = Child(['arg1', 'arg2'])
>>> c1.run(1,2)
run method called with 1 2
>>> c1.run(1,2,3)
Traceback (most recent call last):
...
TypeError: too many positional arguments
>>> c1.run(1)
Traceback (most recent call last):
  File "<pyshell#119>", line 1, in <module>
...
TypeError: missing a required argument: 'arg2'
>>> c2 = Child(['arg1', 'arg2', 'arg3'])
>>> c2.run(1,2,3)
run method called with 1 2 3
>>> c1.run(1,2)
run method called with 1 2


text:
Q: Cannot login to UbuntuOne since upgrade to 11.10 When I start UbuntuOne on 11.10 with the same ID and password I used to have in Ubuntu 11.04 this error message appears:
Method "CreateItem" with signature "a{sv}(oayay)b" on interface "org.freedesktop.Secret.Collection" does't exist
And I cannot sign in or connect anyway. I heard there are some bug fixed having been released, but I do not know how to use them. Can anyone help,please?

A: I had to open the Muon Package manager, searched on Ubuntu One, selected everything that was not for debugging and installed.  After, I went to "Settings", and found a "Ubuntu One"
option.  I selected it and it ran the installer.


text:
Q: Can I recover my files after upgrading to Windows 8 from Windows 7? I did not back up my files in Windows 7 before installing Windows 8 on top of it, and it appears as though they are all lost.
Is my data recoverable?

A: Unless you had performed a backup, in which case it does not appear so, you would not be able to restore your Windows 7 installation.
Your best bet is to copy off any files/documents that you had prior to the upgrade and start fresh with a new Windows 7 installation.
Instead of downgrading, what issues are you experiencing that makes you want to revert back to Windows 7? Maybe this community has some solution to your OS woes.

A: Check if you have a Windows.old folder on your system partition:

The Win8 Upgrade should have created it, and unless you specifically got rid of it it should still be there. Keep your fingers crossed and search inside it for your files.


text:
Q: Use infoBox from shinydashboard into shiny I'm using shiny to build an App in my office, and I would like to use features like infoBox build in shinydashboard.
is it possible to use infoBox() into a navbarPage ?
shinyUI(fluidPage(
  navbarPage(title="my title",collapsible=T,
  tabPanel("Update",icon=icon("refresh","fa-2x",lib="font-awesome"),
            dashboardBody(
            fluidRow(infoBox("New Orders", 10 * 2, icon = icon("credit-card"))
             )))

I know it's certainly just a story of css style but i cant figured out how to do it.
here is how it look like in shinydashboard :

here is how it look like in my App using shiny :

And here is the html code made by infoBox() :

      Progress
      25%

can I make a css file to make my shiny output look like the shinydashboard  output ?
## EDIT :
Thank's to @Victorp and @MrFlick i have copy/paste all css style in link with box or infobox frome shinydashboard.css and adminLTE.css into my boostrap.css file and it work correctly. I can use my own css style and the infobox feature.

A: Hello you also need the AdminLTE.css file (you can find it in the shinydashboard dir) :
### ui
library("shiny")
fluidPage(
  tags$h1("Example of an infoBox with shiny"),
  # Add CSS files
  includeCSS(path = "AdminLTE.css"),
  includeCSS(path = "shinydashboard.css"),
  br(),
  fluidRow(
    infoBox("New Orders", 10 * 2, icon = icon("credit-card"), fill = TRUE),
    infoBoxOutput("progressBox2"),
    infoBoxOutput("approvalBox2")
  ),
  fluidRow(
    # Clicking this will increment the progress amount
    box(width = 4, actionButton("count", "Increment progress"))
  )
)
### server
library("shiny")
function(input, output) {
  output$progressBox2 <- renderInfoBox({
    infoBox(
      "Progress", paste0(25 + input$count, "%"), icon = icon("list"),
      color = "purple", fill = TRUE
    )
  })
  output$approvalBox2 <- renderInfoBox({
    infoBox(
      "Approval", "80%", icon = icon("thumbs-up", lib = "glyphicon"),
      color = "yellow", fill = TRUE
    )
  })
}

This app will work if you copy the files in your app directory, if you don't want to do that you can do :
# Function for adding dependencies
library("htmltools")
addDeps <- function(x) {
  if (getOption("shiny.minified", TRUE)) {
    adminLTE_js <- "app.min.js"
    adminLTE_css <- c("AdminLTE.min.css", "_all-skins.min.css")
  } else {
    adminLTE_js <- "app.js"
    adminLTE_css <- c("AdminLTE.css", "_all-skins.css")
  }

  dashboardDeps <- list(
    htmlDependency("AdminLTE", "2.0.6",
                   c(file = system.file("AdminLTE", package = "shinydashboard")),
                   script = adminLTE_js,
                   stylesheet = adminLTE_css
    ),
    htmlDependency("shinydashboard",
                   as.character(utils::packageVersion("shinydashboard")),
                   c(file = system.file(package = "shinydashboard")),
                   script = "shinydashboard.js",
                   stylesheet = "shinydashboard.css"
    )
  )

  shinydashboard:::appendDependencies(x, dashboardDeps)
}

library("shiny")
# ui
ui <- fluidPage(
  tags$h1("Example of an infoBox with shiny"),
  br(),
  fluidRow(
    infoBox("New Orders", 10 * 2, icon = icon("credit-card"), fill = TRUE),
    infoBoxOutput("progressBox2"),
    infoBoxOutput("approvalBox2")
  ),
  fluidRow(
    # Clicking this will increment the progress amount
    box(width = 4, actionButton("count", "Increment progress"))
  )
)
# Attach dependencies
ui <- addDeps(
  tags$body(shiny::fluidPage(ui)
  )
)
# server
server <- function(input, output) {
  output$progressBox2 <- renderInfoBox({
    infoBox(
      "Progress", paste0(25 + input$count, "%"), icon = icon("list"),
      color = "purple", fill = TRUE
    )
  })
  output$approvalBox2 <- renderInfoBox({
    infoBox(
      "Approval", "80%", icon = icon("thumbs-up", lib = "glyphicon"),
      color = "yellow", fill = TRUE
    )
  })
}
# app
shinyApp(ui = ui, server = server)


text:
Q: How do i install a windows-cd motherboard driver I have update all my software but i cant get my TUF Gaming B550M Plus(i bought it without wireless) instead im using its wired-ethernet from the motherboard but its not detecting it
I have to use the wired lan so i can get 150mbps speed from my provider ;(
Is there a solution i can do with the latest ubuntu for amd64
I just installed ubuntu today, trying to get this my ideal simple os without the microsoft security vendor keeps restarting my windows while watching netflix


text:
Q: VB.Net Search namespace for a generic type (Reflection) I'm attempting to dynamically register entities and configurations with a context (ef4 code-only)
I would normally do:
Private Shared Sub ConfigureDatabase(ByRef Builder As ContextBuilder(Of ContextExtension))
  'Load configurations for each of the tables (Entity sets) in our database...
  ConfigureEntity(Builder, New ContactConfig)
End Sub

 Private Shared Sub ConfigureEntity(Of T)(ByRef Builder As ContextBuilder(Of ContextExtension), ByVal config As EntityConfiguration(Of T), ByVal setName As String)
    'Register the entity configuration with the builder
    Builder.Configurations.Add(config)

    'Register the entity set name with the builder
    Builder.RegisterSet(Of T)(setName)
End Sub

Where ContactConfig is a class which inherits EntityConfiguration(Of Contact) and Contact is a class which implements an interface IEntity  (IEntity is common to all entities).
So... I need to search a namespace (say Project.DB.Client) for all signatures that match:
EntityConfiguration(Of <Class which implements IEntity>)

How can I achieve this?

A: Namespace is just a part of object's name. Searching for types which inherit generic class involves much more effort than just filtering by namespace name:
Private Function CheckType(ByVal type As Type) As Boolean
    If (type Is GetType(Object)) Then ' object hierarhy root reached'
        Return False
    End If
    If (type.IsGenericType) Then
        ' inherits from some generic type'
        Dim parameters = type.GetGenericArguments()
        ' check if it has generic 1 parameter'
        If parameters.Length = 1 Then
            ' check if generic parameter is defined'
            If Not (parameters(0).FullName Is Nothing) Then
                ' check if parameter implements IEntity'
                If GetType(IEntity).IsAssignableFrom(parameters(0)) Then
                    ' check if it is EntityConfiguration(Of T)'
                    If type Is GetType(EntityConfiguration(Of )).MakeGenericType(parameters) Then
                        Return True
                    End If
                End If
            End If
        End If
    End If
    Return CheckType(type.BaseType)
End Function

Function FilterTypes(ByVal nameSpaceName As String, ByVal types As IEnumerable(Of Type)) As List(Of Type)
    Dim result As New List(Of Type)
    ' append . to namespace name'
    nameSpaceName = nameSpaceName + "."
    For Each type As Type In types
        ' we do not need abstract classes, wont be able to create their instances anyway'
        If (type.IsClass And Not type.IsAbstract And
             type.FullName.StartsWith(nameSpaceName)) Then
            ' check if type is inherited from EntityConfiguration(Of T)'
            If (CheckType(type)) Then
                result.Add(type)
            End If
        End If
    Next
    Return result
End Function

CheckType function checks if type is inherited from EntityConfiguration(Of T).
FilterTypes function additionally filters types by namespace and returns filtered list a result.
Example: Dim types = FilterTypes("Project.DB.Client", Assembly.GetExecutingAssembly().GetTypes()).


text:
Q: boost::program_options how to reload a value I would like to reload some values from a configuration file. I know that po::store will not change values if they exist in the variables_map. Is there an alternative that does replace values even if they already exist?
I tried deleting values that I am about to reload from the variables_map, but po::store does not add the new values anyway (even though old ones can not be accessed either).

A: The solution of P3trus involves a downcast. This is necessary as variables_map overloads the std::map::operator[] returning a const variable_value & (const prevents reassignments).
However in C++11 we have std::map::at() that isn't overloaded, so it is possible to do:
vm.at(option).value() = val;

directly where is needed.

A: The problem is that the variables map remembers which options are final.
If you look at the source you find the following entry.
/** Names of option with 'final' values -- which should not
    be changed by subsequence assignments. */
std::set<std::string> m_final;

It's a private member variable of the variables_map.
I guess the easiest way would be using a new variables_map and replace the old one. If you need some of the old values, or just want to replace some of them, write your own store function. You basically create a temporary variables_map with po::store and then update your variables_map the way you need it.
The variables_map is basically a std::map so you can access its content the same way. It stores a po::variable_value, kind of a wrapper around a boost::any object.If you just want to replace a single value you can use something like that
template<class T>
void replace(  std::map<std::string, po::variable_value>& vm, const std::string& opt, const T& val)
{
  vm[option].value() = boost::any(val);
}

Note: po is a namespace alias.
namespace po = boost::program_options;


text:
Q: How to center items in a div (CSS) in a grid (justify-content and align-items not working) I have a div with grid layout, with several divs inside. I want the divs inside the grid to be full-height, and I want the content of the divs inside the grid to be centered vertically. I already looked all over the place for a solution, but found none that worked.
So far, I've tried using the justify-content and align-items, but they are not doing what I want.
This is what I've tried:

.wrapper {
  display: flex;
  flex-direction: row;
}

.card {
  background-color: beige;
  border: 1px solid rgb(148, 148, 109);
  border-radius: 5%;
  padding: 10px 15px;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
  justify-content: center;
  align-items: center;
}

.one {
  flex: 1;
}

.two {
  flex: 1;
  justify-content: center;
  align-items: center;
  vertical-align: center;
}

Card 1

Lorem ipsum dolor sit amet consectetur adipisicing elit. Laborum nihil, facere voluptas, amet ipsam, deleniti ullam dolores labore illum cumque praesentium perferendis accusantium. Aspernatur commodi, beatae culpa vel similique sequi.

Item 3 just for content.

Card 2

I want the above heading and this text to be vertically centered on this card (justify-content and align-items doesn't work...

Any input is greatly appreciated!
Thanks! :)

A: If I am not mistaken it should be so.
Just on the "card" class:
display: flex;
align-items: center;
Adding a div inside will put it in the center.

.wrapper {
  display: flex;
  flex-direction: row;
}

.card {
  background-color: beige;
  border: 1px solid rgb(148, 148, 109);
  border-radius: 5%;
  padding: 10px 15px;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
  flex: 1;
  display: flex;
  align-items: center;
}

Card 1

Lorem ipsum dolor sit amet consectetur adipisicing elit. Laborum nihil, facere voluptas, amet ipsam, deleniti ullam dolores labore illum cumque praesentium perferendis accusantium. Aspernatur commodi, beatae culpa vel similique sequi.

Item 3 just for content.

Card 2

I want the above heading and this text to be vertically centered on this card (justify-content and align-items doesn't work...

A: Like this? It messed up the look of your h2 but that can easily be fixed. Your instructions said header and the text aligned vertically so I assume that's what you want? Also the default direction for display flex is row, so there's no need to specify. Just a tip for cleaner code.

.wrapper {
  display: flex;
  flex-direction: row;
}

.card {
  background-color: beige;
  border: 1px solid rgb(148, 148, 109);
  border-radius: 5%;
  padding: 10px 15px;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
}

.one {
  flex: 1;
}

.two {
  flex: 1;
 color: red;
display: flex;
align-items: center;
 }

Card 1

Lorem ipsum dolor sit amet consectetur adipisicing elit. Laborum nihil, facere voluptas, amet ipsam, deleniti ullam dolores labore illum cumque praesentium perferendis accusantium. Aspernatur commodi, beatae culpa vel similique sequi.

Item 3 just for content.

Card 2

I want the above heading and this text to be vertically centered on this card (justify-content and align-items doesn't work...

A: enter image description here
*this should work

.p-grid {
    display: flex;
    flex-wrap: wrap;
}

.p-align-center {
    align-items: center;
}

.vertical-container {
    margin: 0;
    height: 200px;
    background: #efefef;
    border-radius: 4px;
}

Vertical Alignment - Center

4

A: I hope this will help you. You forgot to add display: flex; to your cards, also when you add flex and you want to have your content in a column layout you have to add flex-direction: column; (row is the standard option)

.wrapper {
  display: flex;
  flex-direction: row;
}

.card {
    background-color: beige;
    border: 1px solid rgb(148, 148, 109);
    border-radius: 5%;
    padding: 10px 15px;
    box-shadow: 0px 0px 5px 0px rgb(0 0 0 / 20%);
    justify-content: center;
    align-items: start;
    display: flex;
    flex-direction: column;
}

Card 1

Lorem ipsum dolor sit amet consectetur adipisicing elit. Laborum nihil, facere voluptas, amet ipsam, deleniti ullam dolores labore illum cumque praesentium perferendis accusantium. Aspernatur commodi, beatae culpa vel similique sequi.

Item 3 just for content.

Card 2

I want the above heading and this text to be vertically centered on this card (justify-content and align-items doesn't work...


text:
Q: Render speed issue when resuing a directive in AngularJS I have the following simple base directive:
angular.module("base", [])
  .directive("base", function() {
    return {
      restrict: "A",
      scope: true,
      controller: function($scope) {
        this.setHeader = function(header) {
          $scope.header = header;
        }
        this.setBody = function(body) {
          $scope.body = body;
        }
        this.setFooter = function(footer) {
          $scope.footer = footer;
        }
      },
      templateUrl: "base.html"
    }
  });

I am passing data to this directive in the following way:
 .directive("custom", function() {
    return {
      restrict: "E",
      require: "^base",
      scope: {
        ngModel: "="
      },
      link: function($scope, $element, $attrs, baseCtrl) {
        //Do something with the data or not...
        baseCtrl.setHeader($scope.ngModel.header);
        baseCtrl.setBody($scope.ngModel.body);
        baseCtrl.setFooter($scope.ngModel.footer);
      }
    }
  });

When I create a list of my custom directives, I notice the custom directives aren't rendering immediately. I have made a Plunker demonstrating this behavior. (You will see the list cells empty for a split second, then the directives will appear)
My goal behind this design is to reuse the template of the base directive and only pass in the data needed for display. In this simple example, $scope.data is exactly what I need to pass in but it may be the case some rules or manipulation need to happen first. Rather than have the controller which queried the data handle this, I wanted to pass it off into the directive, separating the concerns.
So my questions are:

*

*Is there any way to make the directives render faster and avoid the flickering shown in the Plunker?

*Is this a best practice for reusing directives with Angular?

A: The flickering is being caused by the async http request to the "base.html" file. Since the HTML for the base directive has to be loaded from the server, there will be a fraction of time where no content will be displayed.
In order to render the data, Angular will go though these 3 stages:

*

*Fetch the HTML file/template from the server (no content will be displayed)

*Compile the HTML template (the DOM is updated but the scope isn't yet linked)

*Link the scope to the DOM/template (expected data is displayed)

Option 1 - Use the template attribute
Just replace the templateUrl: "base.html" for the direct HTML content:
//templateUrl: "base.html"
template: '

{{header}}

{{body}}

{{footer}}

',

You will notice that there won't be any flickering this time (check this plunker).
Option 2 - Pre-load template files
Angular has a built-in template cache ($templateCache) that it uses to check if any HTML template file/content has already been fetched from the server or not. If you populate that cache while the app is loading then Angular will not need to fetch the template to render the directive, it will read it directly from the cache.
You can use Angular's $templateRequest (if you are using the latest beta version of Angular) or $templateCache (for any version).
The difference is that $templateRequest automatically makes the HTTP GET request and stores the result in the $templateCache. On the other one you will have to do it manually, like this:
loadTemplate = function(tpl) {
  $http.get(tpl, { cache : $templateCache })
    .then(function(response) {
      $templateCache.put(tpl, html);
      return html;
    });
};
loadTemplate('base.html');

Note however that this approach needs your app to have a "loading phase".

Regarding the best practices for reusing directives, you seem to be on the right path. The example is to simple to give any advices... Nevertheless, check the "Best practice" notes in this Angular "Creating Custom Directives" guide.
Edit
(my personal preferences regarding template vs templateUrl)
If the main goal is solely performance (i.e. page render speed) then template seems to be the best choice. Fetching one file will always be faster than fetching two... However, as the app grows, the need for a good structure is mandatory, and template files are one of the best practices when it comes to that.
Normally I follow this "rules":

*

*If there are only a few lines of HTML in the template, then just use the template

*If the HTML template will not be constantly changing over time (i.e. post structure, contact details, etc...), use template, otherwise (i.e. templates containing banners/ads) use templateUrl

*If the app has a loading phase, use templateUrl with cache


text:
Q: Error: [$injector:modulerr] - angular confirm
Error: [$injector:modulerr]
  http://errors.angularjs.org/1.4.8/$injector/modulerr?p0=contactsApp&p1=%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.4.8%2F%24injector%2Fmodulerr%3Fp0%3Dangular-confirm%26p1

I am trying to use angular confirm. But it gives above error as soon as I use it.
Following is my html code where I have defined my ng-app and ng-controller:
Contacts.html

 Contacts

                    Contacts

                            Add

contacts.js:
var mycontacts = angular.module('contactsApp',['angular-confirm']);

        mycontacts.controller('contactsCtrl', function ($scope, $http,$window, $confirm) {

            $scope.sendInvitation = function (el) {
               var email = "simer@gmail.com"
                $confirm({text: 'Do you want to delete this record?', title: 'Confirmation', ok: 'Yes', cancel: 'No'}).then(function() {
                    $http.get('/sendinvitation/',{params:{"email" : email},headers:{'Content-Type':'application/x-www-form-urlencoded'}})
                    .success(function(response)
                    {
                        $window.location.reload();
                    });
                });
            }

            });

Once I remove ['angular-confirm'] from ng-app and $confirm from ng-controller my application works fine.
following are files I included: