text:
Q: UIPickerView not showing images in iOS 7 + versions I'm trying to run my app in iOS 7+ versions wherein struck with one issue
I have UIPickerview showing images correctly for versions lessthan iOS 7 but in iOS 7+ entire picker view is messed up. Here's what im trying to achieve

*

*I have array of imageViews in Viewload

*Trying to display same in ViewForRow method. Please check code below
//In ViewDidLoad()
 NSArray *box12names = [[NSArray alloc] initWithObjects:@"Black",@"Brown",@"Red",@"Orange",@"Yellow",@"Green",nil];

self.box1_views = [[NSMutableArray alloc] initWithCapacity:10];

// From code below , Box1_Black, Box1_Brown etc... are my png images in APP

for (NSString *str in box12names) {
NSString *filename = [[NSString alloc] initWithFormat:@"Box1_%@.png",str];
UIImage *image = [UIImage imageNamed:filename];
UIImageView *imageview = [[UIImageView alloc] initWithImage:image];

[self.box1_views addObject:imageview];
[filename release];
[imageview release];

}

 [self.box1_views release];

self.box2_views = [[NSMutableArray alloc] initWithCapacity:10];

for (NSString *str in box12names) {
NSString *filename = [[NSString alloc] initWithFormat:@"Box2_%@.png",str];
UIImageView *imageview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:filename]];

[self.box2_views addObject:imageview];
[filename release];
[imageview release];

}

[self.box2_views release];

[box12names release];

//In PickerViewDelegate method

-(UIView *)pickerView:(UIPickerView *)pickerView
   viewForRow:(NSInteger)row
 forComponent:(NSInteger)component reusingView:(UIView *)view

{

NSString *arrayName = [[NSString alloc] initWithFormat:@"box%d_views", component +1];

NSArray *array = [self valueForKey:arrayName];

UIView *tempview = [array objectAtIndex:row];

[arrayName release];

return tempview;

}

//Here my picker view is displaying wierdly with iOS 7+ version whereas works good with iOS 6

Please help

A: I think you didnt add subview of imageview in the pickerview's reusing view.So try this below line in pickerView:viewForRow method:
tempView.addSubview(imageView);

A: Issue resolved -
{
NSString *arrayName = [[NSString alloc] initWithFormat:@"band%d_views", component +1];
NSArray *array = [self valueForKey:arrayName];
//UIView *tempview = [array objectAtIndex:row];
UIView *tempview=[[UIView alloc] init];
[tempview setBackgroundColor:[UIColor colorWithPatternImage:[[array objectAtIndex:row] image]]];

[arrayName release];
return tempview;
}


text:
Q: Prevent Math.Round(95.55555555,2) from rounding to 95.56 in VB.NET If I do Math.Round(95.55555555,2) in VB.NET, the result is 95.56, but I want it the result the be 95.55.  Is there a way to do this in VB.NET?  I guess I just want to keep the decimal places, but not round them

A: Looks like Math.Truncate(95.5555555 * 100) / 100.
See Truncate Decimal number not Round Off

A: Try using Math.Floor(95.55555555 * 100) / 100
Or, if you want to round to a specific number of decimals:
Public Function RoundDown(ByVal value As Double, ByVal decimalPlaces As Integer) As Double
    If (decimalPlaces < 1) Then
        Throw New ArgumentException("Invalid decimalPlaces: less than 1")
    EndIf

    Dim factor As Integer = 10 ^ decimalPlaces
    Return Math.Floor(value * factor) / factor
End Sub

A: There are several ways to do this.  One would be to subtract 0.05 from the number then use Math.Round(number, 2).  (This works on the same principle as implementing floor and ceiling functions when all you have is round.)
A better way is probably
Math.Truncate(number * 100) / 100

That just multiplies the number by 100 and truncates it, giving you an integer value with the digits you want, then divides by 100 to turn it back to a decimal.

A: You don't want Math.Round. You want Math.Truncate.
Dim decimalNumber As Double = 95.55555555
Dim truncatedNumber As Double = Math.Truncate(decimalNumber * 100) / 100

Your result will be 95.55.

A: You can use this:
static double TruncateWithDecimals(double n, int nOfDec)
        {
           return Math.Round(Math.Floor(n * Math.Pow(10, nOfDec)) /  Math.Pow(10, nOfDec), nOfDec);
        }

sorry this is C#, but you can easily guess how to translate in vb I think.

A: Public Function Round(Number As Decimal, places As Integer) As Decimal
    'Convert number to string
    Dim NumberString As String = Number.ToString
    'Check if the number contains a decimal, if not return the number
    If NumberString.IndexOf("."c) = -1 Then Return Number
    'Get the whole number part of the string
    Dim IntegerPart As String = NumberString.Split("."c)(0)
    'Get the Decimal part of the string
    Dim DecimalPart As String = NumberString.Split("."c)(1)
    'If the number is already rounded to n decimal places, then return the number
    If DecimalPart.Length = places Then Return Number
    'Get whichever decimals are being rounded to
    Dim ToPlacePart As String = DecimalPart.Substring(0, places)
    'get the other part that will be compared
    Dim ComparePart As String = DecimalPart.Substring(places)
    'Create a midpoint to compare the compare part to
    Dim ControlMidPoint As Decimal = Decimal.Parse("1" & Replace(Space(ComparePart.Length), Space(1), "0")) / 2
    'Create the base result(Add the integer part to the decimal part that will stay)
    Dim Result As Decimal = Decimal.Parse(IntegerPart & "." & ToPlacePart)
    'Create an increment to add if the comparepart is greater than the mid point(ex 0.001, 0.01, 0.0000001)
    Dim AddNum As Decimal = Decimal.Parse("0." & Replace(Space(ToPlacePart.Count - 1), Space(1), "0") & "1")
    'If the comparepart was equal to or greater than the midpoint, then add the addpart to the base result and return it
    If Decimal.Parse(ComparePart) >= ControlMidPoint Then Return Result + AddNum
    'Just return the base result, because the compare part was smaller than the midpoint
    Return Result
End Function

redpajama_set_name: RedPajamaStackExchange


text:
Q: using placeholder in textbox in c# I want to display the placeholder value in textbox. When user try to type in textbox it will erase automatically from the textbox. Can anyone resolve it?

A: Use the events when the text box gets focus and loses focus. When the textbox gets focus you do something like MytextBox.Text = string.Emtpy when it loses focus you check to see whether it has content or not and if not you set it to your default value something like:
string.IsNullOrWhiteSpace(MytextBox.Text) ? "Default" : MytextBox.Text


text:
Q: Scheduling java program to update data using API I have to update data in the database at a particular time daily. Data will be updated using RestAPI. I have to consume API either in java or nodejs.
Can you tell me how can I schedule the job in java or nodejs. Which one would be better for the above scenario?
The basic requirement is updating all the data in the database once in a day using POST RestAPI.
Any specific example?

A: If you need to handle both java jar and nodejs code, and that is the same project, and you want the consistent thing for scheduling both, you should you OS capabilities for that, I'll assume you use Linux or Unix like OS.
The tool is called CRON. Details here.
https://en.wikipedia.org/wiki/Cron
You just need to create a shell script with launching the process.
And then configure it to run daily here is an example for 8 am.
0 8 * * *

For the cloud, there are services for that exists
Example of AWS is cloud watch.
https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html


text:
Q: Is the first has_many redundant? - Ruby on Rails Active records associations Rails 4.2 newbie:
2 Questions;
1) Is the first has_many redundant? Since its name is a plural of Save Class?
can I have only:
has_many   :savers, through: :saves, source: :saver

Or even better;
has_many   :savers, through: :saves

If the answer is yes, where can I set "dependent: :destroy"?
class Post < ActiveRecord::Base
  belongs_to :user
  has_many   :saves, class_name: "Save", foreign_key: "saver_id", dependent: :destroy
  has_many   :savers, through: :saves, source: :saver
end

class Save < ActiveRecord::Base
  belongs_to :saver, class_name: "User"
  validates :saver_id, presence: true
end

class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
  ...
end

2) This is the typical blog model, where user can 'save' posts posted by another user to their timeline. Does this model make use best practices? Specially in db performance, doing a Join to get posts saved by a User. The 'Save' table that will  have 100MM rows?

A: Lets first alter your example a bit to make the naming less confusing:
class User
  has_many :bookmarks
  has_many :posts, through: :bookmarks
end

class Post
  has_many :bookmarks
  has_many :users, through: :bookmarks
end

class Bookmark
  belongs_to :user
  belongs_to :post
end

Lets have a look at the query generated when we do @user.posts
irb(main):009:0> @user.posts
  Post Load (0.2ms)  SELECT "posts".* FROM "posts" INNER JOIN "bookmarks" ON "posts"."id" = "bookmarks"."post_id" WHERE "bookmarks"."user_id" = ?  [["user_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy []>

Now lets comment out has_many :bookmarks and reload:
class User
  # has_many :bookmarks
  has_many :posts, through: :bookmarks
end

irb(main):005:0> @user.posts
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :bookmarks in model User

So no, the first has_many is not redundant -  in fact its the very core of how has_many through: works. You setup a shortcut of sorts through another relation.
Note in has_many :posts, through: :bookmarks :bookmarks is the name relation we are joining through. Not the table which contains the joins.
To fix your original code you would need to do:
class Post < ActiveRecord::Base
  has_many   :saves, dependent: :destroy
  has_many   :savers, through: :saves
end

class Save < ActiveRecord::Base
  belongs_to :saver, class_name: "User"
  belongs_to :post # A join table with only one relation is pretty worthless.
  validates :saver_id, presence: true
end

class User < ActiveRecord::Base
  has_many :posts
  has_many :saves, dependent: :destroy
  has_many :posts, through: :saves
end

Note that you don't need half the junk - if you have has_many :savers, through: :saves ActiveRecord will look for the relation saver by itself. Also you only want to use dependent: destroy on the join model - not on the post relation as that would remove all the posts a user has "saved" - even those written by others!

A: Teaching Rails myself, I want to learn the professional way to use the framework and following Rails guidelines best practices. That's not easy, because I usually find answers that 'just works'
I'll try to answer myself and maybe it could be useful for Rails Newbies:
Using has_many through, association, Rails firstly infers the association by looking at the foreign key of the form <class>_id where <class> is the lowercase of the class name, in this example; 'save_id'.
So, if we have the column name 'save_id', we will have the following simplified model:
class Post < ActiveRecord::Base
  belongs_to :user
  has_many   :saves, through: :saves
end

class Save < ActiveRecord::Base
  belongs_to :savers, class_name: "User"
  validates :save_id, presence: true
end

class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
  ...
end


text:
Q: SQLAlchemy - pretty print SQL query results In Ruby console, it is possible to display SQL query results in a very human-friendly way (ActiveRecord + Hirb):
>> Tag.all :limit=>3, :order=>"id DESC"
+-----+-------------------------+-------------+-------------------+-----------+-----------+----------+
| id  | created_at              | description | name              | namespace | predicate | value    |
+-----+-------------------------+-------------+-------------------+-----------+-----------+----------+
| 907 | 2009-03-06 21:10:41 UTC |             | gem:tags=yaml     | gem       | tags      | yaml     |
| 906 | 2009-03-06 08:47:04 UTC |             | gem:tags=nomonkey | gem       | tags      | nomonkey |
| 905 | 2009-03-04 00:30:10 UTC |             | article:tags=ruby | article   | tags      | ruby     |
+-----+-------------------------+-------------+-------------------+-----------+-----------+----------+
3 rows in set

Is there a module that will allow me to do display SQLAlchemy result sets in a similar way in IPython?


text:
Q: checking availability between 2 dates not working I have a order page when you can order cars. I have 2 functions, 1 to order 1 to check.
My order function:
function reserveer($resvan,$restot,$autoid){
    $con = new Core();
    $con->connect();
    $sql = 'INSERT INTO reservering (resvan, restot,autoid) VALUES (?,?,?)';

    if ($stmt = $con->myconn->prepare($sql))
    {
        $stmt->bind_param('ssi', $resvan, $restot,$autoid);
        $stmt->execute();
        $stmt->close();
    }
    else{
        die("errormessage: " . $con->myconn->error);
    }
}

my check function:
function check($resvan, $restot,$autoid){
    $con = new Core();
    $con->connect();
    $errmsg = array();
    $sqlres = 'SELECT * FROM reservering WHERE resvan >= ? AND restot <= ? AND autoid=?';
    if($stmt = $con->myconn->prepare($sqlres)){
        $stmt->bind_param('ssi', $resvan, $restot,$autoid);
        $stmt->execute();
        $stmt->store_result();
    }
    if ($stmt->fetch()){
        $errmsg[] = "already exists!";
        return $errmsg;
    }
}

But I have a flaw in my code. When someone orders from 2001-01-01 to 2001-01-15 it gets correctly inserted. And when someone orders from 2001-01-02 to 2001-01-14 it gets inserted aswell. I thought this would work. I've tried the sql BETWEEN aswell but that doesn't work either.
So my question is, how can I make a correct check for this? I have no errors.
My table setup :

A:
When someone orders from 2001-01-01 to 2001-01-15 it gets correctly inserted

We have
resvan=2001-01-01
restot=2001-01-15

Now look at your query which checks the reservation
WHERE resvan >= ? AND restot <= ?

And when someone orders from 2001-01-02 to 2001-01-14 it gets inserted aswell

So when that happens your query becomes
WHERE resvan >= 2001-01-02 AND restot <= 2001-01-14

This does not return a duplicate because no such record exists. Your existing record had date starting on 1st january, not second january.
Solution is very simple, you do not want to double book a car on a date which it is already booked for so just provide it 1 date and not both to match. Even if 1 matches don't re-book
WHERE (
2001-01-02 BETWEEN resvan AND restot
OR 2001-01-14 BETWEEN resvan AND restot
)
AND autoid=?

Now try with those those new dates


text:
Q: Stop android app from closing I'm using the BroadcastReceiver to receive SMS messages with my app, and then edit a database based on what the message says. The app works fine when it's open, but If I leave it on for a long period of time and it automatically closes the app will force close when it receives a message (I think the BroadcastReciever is still working, but the rest of the app has closed). IS there any way to keep the app from closing, or resuming it when it receives a text message?
Thanks

A: If you want the receiver to be persistent you should consider using a Service instead of a standard Activity for your application. BroadcastReceivers that exist in a standard activity are considered to be a foreground service only when processing onReceive as soon as the execution returns the Activity resumes its normal process priority and can be terminated by the system as needed.
From: BroadcastReceiver

Process Lifecycle
A process that is currently executing a BroadcastReceiver (that is, currently running the code in its onReceive(Context, Intent) method) is considered to be a foreground process and will be kept running by the system except under cases of extreme memory pressure.
Once you return from onReceive(), the BroadcastReceiver is no longer active, and its hosting process is only as important as any other application components that are running in it. This is especially important because if that process was only hosting the BroadcastReceiver (a common case for applications that the user has never or not recently interacted with), then upon returning from onReceive() the system will consider its process to be empty and aggressively kill it so that resources are available for other more important processes.
This means that for longer-running operations you will often use a Service in conjunction with a BroadcastReceiver to keep the containing process active for the entire time of your operation.

For more information on creating a service:

Developer Guides
For a detailed discussion about how to create services, read the Services developer guide.


text:
Q: How to skip sequential row observations? I have a data set comprised of 5 minute price observations (not an xts set) as follows:
dat = read.csv("olddat.csv", as.is=TRUE);
tim = strptime(dat[,1], "%d/%m/%Y %H:%M");
dat$day = format(tim, "%Y-%m-%d");
##ddx <- row index for each day
ddx = split(seq.int(nrow(dat)), dat$day);

that returns:(this is only one day of data that I copied in from R and the observations on each day usually carry on until 23:55, the entire set has many more days)
2423  24/11/2011 00:00 1.3356 2011-11-24
2424  24/11/2011 00:05 1.3356 2011-11-24
2425  24/11/2011 00:10 1.3356 2011-11-24
2426  24/11/2011 00:15 1.3359 2011-11-24
2427  24/11/2011 00:20 1.3363 2011-11-24
2428  24/11/2011 00:25 1.3364 2011-11-24
2429  24/11/2011 00:30 1.3364 2011-11-24
2430  24/11/2011 00:35 1.3362 2011-11-24
2431  24/11/2011 00:40 1.3362 2011-11-24
2432  24/11/2011 00:45 1.3361 2011-11-24
2433  24/11/2011 00:50 1.3357 2011-11-24
2434  24/11/2011 00:55 1.3361 2011-11-24
2435  24/11/2011 01:00 1.3365 2011-11-24
2436  24/11/2011 01:05 1.3367 2011-11-24
2437  24/11/2011 01:10 1.3368 2011-11-24
2438  24/11/2011 01:15 1.3365 2011-11-24
2439  24/11/2011 01:20 1.3364 2011-11-24
2440  24/11/2011 01:25 1.3366 2011-11-24
2441  24/11/2011 01:30 1.3369 2011-11-24
2442  24/11/2011 01:35 1.3369 2011-11-24
2443  24/11/2011 01:40 1.3369 2011-11-24
2444  24/11/2011 01:45 1.3367 2011-11-24
2445  24/11/2011 01:50 1.3368 2011-11-24
2446  24/11/2011 01:55 1.3367 2011-11-24
2447  24/11/2011 02:00 1.3367 2011-11-24
2448  24/11/2011 02:05 1.3365 2011-11-24
2449  24/11/2011 02:10 1.3365 2011-11-24
2450  24/11/2011 02:15 1.3372 2011-11-24
2451  24/11/2011 02:20 1.3373 2011-11-24
2452  24/11/2011 02:25 1.3376 2011-11-24
2453  24/11/2011 02:30 1.3376 2011-11-24
2454  24/11/2011 02:35 1.3379 2011-11-24
2455  24/11/2011 02:40 1.3379 2011-11-24
2456  24/11/2011 02:45 1.3378 2011-11-24
2457  24/11/2011 02:50 1.3378 2011-11-24
2458  24/11/2011 02:55 1.3377 2011-11-24
2459  24/11/2011 03:00 1.3377 2011-11-24
2460  24/11/2011 03:05 1.3377 2011-11-24
2461  24/11/2011 03:10 1.3379 2011-11-24
2462  24/11/2011 03:15 1.3384 2011-11-24
2463  24/11/2011 03:20 1.3383 2011-11-24
2464  24/11/2011 03:25 1.3382 2011-11-24
2465  24/11/2011 03:30 1.3382 2011-11-24
2466  24/11/2011 03:35 1.3383 2011-11-24
2467  24/11/2011 03:40 1.3383 2011-11-24
2468  24/11/2011 03:45 1.3381 2011-11-24
2469  24/11/2011 03:50 1.3380 2011-11-24
2470  24/11/2011 03:55 1.3381 2011-11-24
2471  24/11/2011 04:00 1.3383 2011-11-24
2472  24/11/2011 04:05 1.3381 2011-11-24
2473  24/11/2011 04:10 1.3382 2011-11-24
2474  24/11/2011 04:15 1.3381 2011-11-24
2475  24/11/2011 04:20 1.3379 2011-11-24
2476  24/11/2011 04:25 1.3379 2011-11-24
2477  24/11/2011 04:30 1.3379 2011-11-24
2478  24/11/2011 04:35 1.3373 2011-11-24
2479  24/11/2011 04:40 1.3373 2011-11-24
2480  24/11/2011 04:45 1.3371 2011-11-24
2481  24/11/2011 04:50 1.3368 2011-11-24
2482  24/11/2011 04:55 1.3369 2011-11-24
2483  24/11/2011 05:00 1.3373 2011-11-24
2484  24/11/2011 05:05 1.3373 2011-11-24
2485  24/11/2011 05:10 1.3372 2011-11-24
2486  24/11/2011 05:15 1.3373 2011-11-24
2487  24/11/2011 05:20 1.3376 2011-11-24
2488  24/11/2011 05:25 1.3376 2011-11-24
2489  24/11/2011 05:30 1.3375 2011-11-24
2490  24/11/2011 05:35 1.3374 2011-11-24
2491  24/11/2011 05:40 1.3371 2011-11-24
2492  24/11/2011 05:45 1.3367 2011-11-24
2493  24/11/2011 05:50 1.3364 2011-11-24
2494  24/11/2011 05:55 1.3363 2011-11-24
2495  24/11/2011 06:00 1.3361 2011-11-24
2496  24/11/2011 06:05 1.3360 2011-11-24
2497  24/11/2011 06:10 1.3362 2011-11-24
2498  24/11/2011 06:15 1.3364 2011-11-24
2499  24/11/2011 06:20 1.3362 2011-11-24
2500  24/11/2011 06:25 1.3364 2011-11-24
2501  24/11/2011 06:30 1.3366 2011-11-24
2502  24/11/2011 06:35 1.3366 2011-11-24
2503  24/11/2011 06:40 1.3366 2011-11-24
2504  24/11/2011 06:45 1.3369 2011-11-24
2505  24/11/2011 06:50 1.3377 2011-11-24
2506  24/11/2011 06:55 1.3376 2011-11-24
2507  24/11/2011 07:00 1.3388 2011-11-24
2508  24/11/2011 07:05 1.3391 2011-11-24
2509  24/11/2011 07:10 1.3394 2011-11-24
2510  24/11/2011 07:15 1.3389 2011-11-24
2511  24/11/2011 07:20 1.3390 2011-11-24
2512  24/11/2011 07:25 1.3386 2011-11-24
2513  24/11/2011 07:30 1.3387 2011-11-24
2514  24/11/2011 07:35 1.3387 2011-11-24
2515  24/11/2011 07:40 1.3392 2011-11-24
2516  24/11/2011 07:45 1.3390 2011-11-24
2517  24/11/2011 07:50 1.3392 2011-11-24
2518  24/11/2011 07:55 1.3383 2011-11-24
2519  24/11/2011 08:00 1.3378 2011-11-24
2520  24/11/2011 08:05 1.3377 2011-11-24
2521  24/11/2011 08:10 1.3377 2011-11-24
2522  24/11/2011 08:15 1.3375 2011-11-24
2523  24/11/2011 08:20 1.3373 2011-11-24
2524  24/11/2011 08:25 1.3377 2011-11-24
2525  24/11/2011 08:30 1.3380 2011-11-24
2526  24/11/2011 08:35 1.3378 2011-11-24
2527  24/11/2011 08:40 1.3378 2011-11-24
2528  24/11/2011 08:45 1.3379 2011-11-24
2529  24/11/2011 08:50 1.3378 2011-11-24
2530  24/11/2011 08:55 1.3376 2011-11-24
2531  24/11/2011 09:00 1.3394 2011-11-24
2532  24/11/2011 09:05 1.3391 2011-11-24
2533  24/11/2011 09:10 1.3402 2011-11-24
2534  24/11/2011 09:15 1.3406 2011-11-24
2535  24/11/2011 09:20 1.3399 2011-11-24
2536  24/11/2011 09:25 1.3394 2011-11-24
2537  24/11/2011 09:30 1.3397 2011-11-24
2538  24/11/2011 09:35 1.3405 2011-11-24
2539  24/11/2011 09:40 1.3412 2011-11-24
2540  24/11/2011 09:45 1.3405 2011-11-24
2541  24/11/2011 09:50 1.3403 2011-11-24
2542  24/11/2011 09:55 1.3398 2011-11-24
2543  24/11/2011 10:00 1.3402 2011-11-24
2544  24/11/2011 10:05 1.3392 2011-11-24
2545  24/11/2011 10:10 1.3384 2011-11-24
2546  24/11/2011 10:15 1.3384 2011-11-24
2547  24/11/2011 10:20 1.3375 2011-11-24
2548  24/11/2011 10:25 1.3377 2011-11-24
2549  24/11/2011 10:30 1.3377 2011-11-24
2550  24/11/2011 10:35 1.3379 2011-11-24
2551  24/11/2011 10:40 1.3378 2011-11-24
2552  24/11/2011 10:45 1.3371 2011-11-24
2553  24/11/2011 10:50 1.3373 2011-11-24
2554  24/11/2011 10:55 1.3375 2011-11-24
2555  24/11/2011 11:00 1.3372 2011-11-24
2556  24/11/2011 11:05 1.3379 2011-11-24
2557  24/11/2011 11:10 1.3383 2011-11-24
2558  24/11/2011 11:15 1.3382 2011-11-24
2559  24/11/2011 11:20 1.3382 2011-11-24
2560  24/11/2011 11:25 1.3387 2011-11-24
2561  24/11/2011 11:30 1.3387 2011-11-24
2562  24/11/2011 11:35 1.3383 2011-11-24
2563  24/11/2011 11:40 1.3383 2011-11-24
2564  24/11/2011 11:45 1.3390 2011-11-24
2565  24/11/2011 11:50 1.3391 2011-11-24
2566  24/11/2011 11:55 1.3394 2011-11-24
2567  24/11/2011 12:00 1.3409 2011-11-24
2568  24/11/2011 12:05 1.3401 2011-11-24
2569  24/11/2011 12:10 1.3401 2011-11-24
2570  24/11/2011 12:15 1.3392 2011-11-24
2571  24/11/2011 12:20 1.3388 2011-11-24
2572  24/11/2011 12:25 1.3388 2011-11-24
2573  24/11/2011 12:30 1.3383 2011-11-24
2574  24/11/2011 12:35 1.3388 2011-11-24
2575  24/11/2011 12:40 1.3393 2011-11-24
2576  24/11/2011 12:45 1.3389 2011-11-24
2577  24/11/2011 12:50 1.3382 2011-11-24
2578  24/11/2011 12:55 1.3374 2011-11-24
2579  24/11/2011 13:00 1.3374 2011-11-24
2580  24/11/2011 13:05 1.3368 2011-11-24
2581  24/11/2011 13:10 1.3373 2011-11-24
2582  24/11/2011 13:15 1.3373 2011-11-24
2583  24/11/2011 13:20 1.3378 2011-11-24
2584  24/11/2011 13:25 1.3381 2011-11-24
2585  24/11/2011 13:30 1.3386 2011-11-24
2586  24/11/2011 13:35 1.3372 2011-11-24
2587  24/11/2011 13:40 1.3361 2011-11-24
2588  24/11/2011 13:45 1.3345 2011-11-24
2589  24/11/2011 13:50 1.3338 2011-11-24
2590  24/11/2011 13:55 1.3338 2011-11-24
2591  24/11/2011 14:00 1.3346 2011-11-24
2592  24/11/2011 14:05 1.3345 2011-11-24
2593  24/11/2011 14:10 1.3343 2011-11-24
2594  24/11/2011 14:15 1.3343 2011-11-24
2595  24/11/2011 14:20 1.3342 2011-11-24
2596  24/11/2011 14:25 1.3337 2011-11-24
2597  24/11/2011 14:30 1.3329 2011-11-24
2598  24/11/2011 14:35 1.3330 2011-11-24
2599  24/11/2011 14:40 1.3329 2011-11-24
2600  24/11/2011 14:45 1.3327 2011-11-24
2601  24/11/2011 14:50 1.3333 2011-11-24
2602  24/11/2011 14:55 1.3336 2011-11-24
2603  24/11/2011 15:00 1.3334 2011-11-24
2604  24/11/2011 15:05 1.3327 2011-11-24
2605  24/11/2011 15:10 1.3330 2011-11-24
2606  24/11/2011 15:15 1.3330 2011-11-24
2607  24/11/2011 15:20 1.3331 2011-11-24
2608  24/11/2011 15:25 1.3338 2011-11-24
2609  24/11/2011 15:30 1.3338 2011-11-24
2610  24/11/2011 15:35 1.3336 2011-11-24
2611  24/11/2011 15:40 1.3330 2011-11-24
2612  24/11/2011 15:45 1.3335 2011-11-24
2613  24/11/2011 15:50 1.3335 2011-11-24
2614  24/11/2011 15:55 1.3331 2011-11-24
2615  24/11/2011 16:00 1.3329 2011-11-24
2616  24/11/2011 16:05 1.3332 2011-11-24
2617  24/11/2011 16:10 1.3330 2011-11-24
2618  24/11/2011 16:15 1.3332 2011-11-24
2619  24/11/2011 16:20 1.3335 2011-11-24
2620  24/11/2011 16:25 1.3333 2011-11-24
2621  24/11/2011 16:30 1.3330 2011-11-24
2622  24/11/2011 16:35 1.3329 2011-11-24
2623  24/11/2011 16:40 1.3333 2011-11-24
2624  24/11/2011 16:45 1.3339 2011-11-24
2625  24/11/2011 16:50 1.3337 2011-11-24
2626  24/11/2011 16:55 1.3341 2011-11-24
2627  24/11/2011 17:00 1.3344 2011-11-24
2628  24/11/2011 17:05 1.3354 2011-11-24
2629  24/11/2011 17:10 1.3353 2011-11-24
2630  24/11/2011 17:15 1.3348 2011-11-24
2631  24/11/2011 17:20 1.3345 2011-11-24
2632  24/11/2011 17:25 1.3344 2011-11-24
2633  24/11/2011 17:30 1.3345 2011-11-24
2634  24/11/2011 17:35 1.3346 2011-11-24
2635  24/11/2011 17:40 1.3345 2011-11-24
2636  24/11/2011 17:45 1.3342 2011-11-24
2637  24/11/2011 17:50 1.3338 2011-11-24
2638  24/11/2011 17:55 1.3340 2011-11-24
2639  24/11/2011 18:00 1.3341 2011-11-24
2640  24/11/2011 18:05 1.3339 2011-11-24
2641  24/11/2011 18:10 1.3339 2011-11-24
2642  24/11/2011 18:15 1.3339 2011-11-24
2643  24/11/2011 18:20 1.3342 2011-11-24
2644  24/11/2011 18:25 1.3341 2011-11-24
2645  24/11/2011 18:30 1.3341 2011-11-24
2646  24/11/2011 18:35 1.3342 2011-11-24
2647  24/11/2011 18:40 1.3342 2011-11-24
2648  24/11/2011 18:45 1.3341 2011-11-24
2649  24/11/2011 18:50 1.3343 2011-11-24
2650  24/11/2011 18:55 1.3342 2011-11-24
2651  24/11/2011 19:00 1.3342 2011-11-24
2652  24/11/2011 19:05 1.3341 2011-11-24
2653  24/11/2011 19:10 1.3340 2011-11-24
2654  24/11/2011 19:15 1.3339 2011-11-24
2655  24/11/2011 19:20 1.3338 2011-11-24
2656  24/11/2011 19:25 1.3337 2011-11-24
2657  24/11/2011 19:30 1.3336 2011-11-24
2658  24/11/2011 19:35 1.3337 2011-11-24
2659  24/11/2011 19:40 1.3337 2011-11-24
2660  24/11/2011 19:45 1.3335 2011-11-24
2661  24/11/2011 19:50 1.3338 2011-11-24
2662  24/11/2011 19:55 1.3335 2011-11-24
2663  24/11/2011 20:00 1.3334 2011-11-24
2664  24/11/2011 20:05 1.3334 2011-11-24
2665  24/11/2011 20:10 1.3339 2011-11-24
2666  24/11/2011 20:15 1.3339 2011-11-24
2667  24/11/2011 20:20 1.3346 2011-11-24
2668  24/11/2011 20:25 1.3349 2011-11-24
2669  24/11/2011 20:30 1.3342 2011-11-24
2670  24/11/2011 20:35 1.3345 2011-11-24
2671  24/11/2011 20:40 1.3347 2011-11-24
2672  24/11/2011 20:45 1.3349 2011-11-24
2673  24/11/2011 20:50 1.3349 2011-11-24
2674  24/11/2011 20:55 1.3349 2011-11-24
2675  24/11/2011 21:00 1.3349 2011-11-24
2676  24/11/2011 21:05 1.3348 2011-11-24
2677  24/11/2011 21:10 1.3349 2011-11-24
2678  24/11/2011 21:15 1.3348 2011-11-24
2679  24/11/2011 21:20 1.3348 2011-11-24
2680  24/11/2011 21:25 1.3348 2011-11-24
2681  24/11/2011 21:30 1.3348 2011-11-24
2682  24/11/2011 21:35 1.3348 2011-11-24
2683  24/11/2011 21:40 1.3346 2011-11-24
2684  24/11/2011 21:45 1.3346 2011-11-24
2685  24/11/2011 21:50 1.3347 2011-11-24
2686  24/11/2011 21:55 1.3348 2011-11-24
2687  24/11/2011 22:00 1.3354 2011-11-24
2688  24/11/2011 22:05 1.3353 2011-11-24
2689  24/11/2011 22:10 1.3349 2011-11-24
2690  24/11/2011 22:15 1.3352 2011-11-24
2691  24/11/2011 22:20 1.3348 2011-11-24
2692  24/11/2011 22:25 1.3348 2011-11-24
2693  24/11/2011 22:30 1.3349 2011-11-24
2694  24/11/2011 22:35 1.3350 2011-11-24
2695  24/11/2011 22:40 1.3348 2011-11-24
2696  24/11/2011 22:45 1.3348 2011-11-24
2697  24/11/2011 22:50 1.3347 2011-11-24
2698  24/11/2011 22:55 1.3347 2011-11-24
2699  24/11/2011 23:00 1.3345 2011-11-24
2700  24/11/2011 23:05 1.3345 2011-11-24
2701  24/11/2011 23:10 1.3345 2011-11-24
2702  24/11/2011 23:15 1.3341 2011-11-24
2703  24/11/2011 23:20 1.3339 2011-11-24
2704  24/11/2011 23:25 1.3337 2011-11-24
2705  24/11/2011 23:30 1.3338 2011-11-24
2706  24/11/2011 23:35 1.3337 2011-11-24
2707  24/11/2011 23:40 1.3341 2011-11-24
2708  24/11/2011 23:45 1.3338 2011-11-24
2709  24/11/2011 23:50 1.3335 2011-11-24
2710  24/11/2011 23:55 1.3331 2011-11-24

The 5 minute observations were already in place when the data was downloaded. I am basically just wondering how can I modify this data to obtain observations at every 10 minutes, 15 minutes, 30 minutes and one hour, i.e. to sequentially drop rows when reading in the data without having to manually delete each undesired row at one at a time through MSExcel and then read in the data?

A:  res <- 2
 ## 2 for one every 10min (i. e. one every 2 rows),
 ## 3 for one every 15min (i. e. one every 3 rows), etc.
 dat[seq(1, nrow(dat), by=res), ]

Edit following comments:
res <- 2
split(dat, dat$day, drop=TRUE) -> d1
##Split into days
lapply(d1, FUN=function(x) {x[seq(1, nrow(x), by=res), ]->x}) -> d1
##Select one observation every 10min for each day separately
as.data.frame(do.call(rbind, d1)) -> result
##Re-aggregate into one single dataframe (you may need to reset the row names though)


text:
Q: Setting specific chrome flags in puppeteer (enable and disable) I'm trying to add specific flags of chrome (flags that are found in "chrome://flags/") to the running of my browser in the tests.
The flags I'm trying to enable are:

*

*"#enable-webgl-draft-extensions"

*"#shared-array-buffer"

and to disable:

*

*"#enable-asm-webassembly"

In the regular chrome command line it looks like this:
"--flag-switches-begin --enable-webgl-draft-extensions --enable-features=SharedArrayBuffer --disable-features=AsmJsToWebAssembly --flag-switches-end"

If i add these criteria in
puppeteer.launch({args});

I receive them before the "--flag-switches-begin" line (I'm watching the command that chrome was ran with in: "chrome://version").
Thank you very much!

A: Follow these steps, please.

*

*puppeteer.defaultArgs() will provide you all default flags. You this method to get them, then filter the array to remove flags that you want to.
https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerdefaultargs
const args = puppeteer.defaultArgs().filter(arg => arg !== '--enable-asm-webassembly')

*Now, add some flags to the array.
args.push('--enable-webgl-draft-extensions', '--shared-array-buffer')

*Enable ignoreDefaultArgs flag when launch a new instance of browser. Also, provide the list of arguments we made above.
const browser = await puppeteer.launch({ ignoreDefaultArgs: true, args })

A: await puppeteer.launch({
      args: [
        '--disable-features=LookalikeUrlNavigationSuggestionsUI'
      ]
})

Try something like this.
You can launch Chromium, switch your flag and then go "chrome://version/", to see what has changed in the command line.
In my case, when i switch "Navigation suggestions for lookalike URLs" to disabled,relaunch Chrommium, then i found --disable-features=LookalikeUrlNavigationSuggestionsUI in the command line。

A: Previous answer already points in the right direction, but it can be made simpler. The key point is that you need to split your arguments into an array. The code can simply be:
const browser = await puppeteer.launch({args:["--flag-switches-begin", "--enable-webgl-draft-extensions", "--enable-features=SharedArrayBuffer", "--disable-features=AsmJsToWebAssembly", "--flag-switches-end"]});

A: The correct args are:
await puppeteer.launch({headless: headless, devtools: true, args: ['--disable-web-security', '--disable-features=IsolateOrigins', ' --disable-site-isolation-trials']});
But puppeteer kept crashing.
The reason was that I used an old puppeteer version, puppeteer 1.8.0.
After upgrading to puppeteer@8.0.0, it works.
You can check that isolation is disabled in:
chrome://process-internals
Suggested in https://stackoverflow.com/a/51320323/337587
More information on the flag: https://www.chromium.org/Home/chromium-security/site-isolation


text:
Q: How to execute perl file from shell script I have a question about how to execute the perl file inside of a shell script
I have 2 files now, "test.sh" and "test.pl", here are example of my scripts
SHELL script
#!/bin/bash
perl FILEPATH/test.pl
......

PERL script
#!/usr/bin/perl
my $a = "hello"
sub saysomething
{
    print $a;
}
.....

The way I call the shell script is : under the path of shell scripts, execute "./test.sh"
All mentioned above are working under the environment
GUN bash, version 4.2.24(1)-release (i686-pc-linux-gnu) + perl (v5.14.2)
But if I put those scripts on server (which I couldn't change the bash / perl version)
GNU bash, version 4.2.10(1)-release (x86_64-pc-linux-gnu) + perl (v5.12.4), I got the followign message:
FILEPATH/test.pl: line 2: my: command not found
Does anybody know how can I solve this problem?
BTW, if I execute the perl script individually (perl FILEPATH/FILENAME.pl), it works perfectly.

A: In order to execute a perl script by .sh script you dont need to use perl prefix, but only:
#!/bin/sh

/somewhere/perlScript.pl

It will work without problem.

A: This problem is at least two-fold. One, you have to have the location of Perl in your environment PATH. Two, the location of Perl may be different on different machines. One solution to both problems that I, and others, have used for years is to make use of a "magic header" of some sort at the top of Perl programs. The header identifies itself as a sh shell script and leverages the fact that /bin/sh exists in every version/flavor of Linux/UNIX. The header's job is to fortify the PATH with various possible Perl locations and then run the Perl script in place of itself (via exec). Here is a "Hello World" example:
1  #! /bin/sh --
2  eval '(exit $?0)' && eval 'PERL_BADLANG=x;PATH="/usr/bin:/bin:/usr/local/bin:$PATH";export PERL_BADLANG;: \
3  ;exec perl -x -S -- "$0" ${1+"$@"};#'if 0;
4  exec 'setenv PERL_BADLANG x;exec perl -x -S -- "$0" $argv:q;#'.q
5  #!/bin/perl -w
6  +($0=~/(.*)/s);do(index($1,"/")<0?"./$1":$1);die$@if$@;__END__+if 0;
7  # Above is magic header ... real Perl code begins here
8  use strict;
9  use warnings;
10 print "hello world!\n";

Note: I added line numbers just to make it clear where lines start and end.

A: First check where perl is installed on your system, e.g. which perl and use that location in the shebang line instead of /usr/bin/perl, if it is different.
If all other recommendations fail, check the first line of the script on the machine where it is not running properly by doing this: head -1 test.pl | xxd. Does the output show the last two bytes as 0d 0a? If so, you probably copied over the file via Windows and didn't do a dos2unix conversion.

A: "command not found" is an error emitted by the shell. You are trying to run your Perl script by the shell, not by Perl.


text:
Q: How to draw multiple graphs with dot? I have a print_dot() function that outputs dot on stdout.
That way I can do:
$ ./myprogram < input | dot -T x11

It works great when I try to print one graph.
Now when I print several graphs, nothing shows up. The dot window is blank, X11 and dot take all the CPU. Nothing is printed on stderr.
$ echo -e "graph  { a -- b }" | dot -T x11 # work
$ echo -e "graph  { a -- b } \n graph { c --d }" | dot -T x11 # doesn't work

# it seems to be interpreted nonetheless
$ echo -e "graph  { a -- b } \n graph { c -- d } " | dot -T xdot
graph {
    ...
}
graph {
    ...
}

Also, when I remove the \n between the 2 graphs, only the first graph is interpreted (what a nice feature...):
$ echo -e "graph  { a -- b }  graph { c -- d } " | dot -T xdot
graph {
    ...
}

Piping the xdot output to dot again doesn't fix the problem.
So, how does one render multiple graphs with graphviz?

A: One calls dot multiple times. Or one puts everything into a single graph, taking care to avoid duplication of names.

A: Use gvpack
$ echo -e "graph { a -- b }\ngraph { c -- d }" | gvpack -u | dot -Tpng > graphs.png

Result

A: Simple script that reads graphs on stdin and opens multiple dot instance.
#!/usr/bin/perl

my $o;
my @l;

while(<>) {
    if(/^\s*(di)?graph/) {
        push @l, $o;
        $o = '';
    }

    $o .= $_;
}

if($o =~ /graph/) {
    push @l, $o;
}

for(@l) {
    if(fork() == 0) {
        open my $p, '| dot -T x11' or die $!;
        print $p $_;
        close $p;
        exit 0;
    }
}


text:
Q: expandable upwards div creating empty space below I have added some jQuery to expand my div vertically, however it's creating a space below itself the same type of height the expandable container is. Need this to be removed.
The div in question is the one attached to the footer. Content is "ABOUT PENDLEY MANOR". If there is also a way to decrease the div back to how it was before expanded would be helpful.
Live URL: http://bit.ly/1fIuBqa
HTML

ABOUT PENDLEY MANOR

this is a test

JQUERY

CSS
#index .index-about-expandable { background-color: #433131; padding: 1px 10px; color: #fff; width: 240px; margin-top: 27px; position: relative; z-index: 5; overflow: hidden; height: 45px; }
#index .index-about-expandable i { font-size: 14px; float: left; margin-top: 15px; }
#index .index-about-expandable h2 { float: left; margin-right: 20px; }

A: This is caused by relative positioning. It frequently gives me some big headaches and I usually try to avoid it.
I suggest moving the div#expand into the footer. If the footer is not relatively positioned, then give #expand a wrapping container with a relative position.
Then, position #expand as absolute with a negative Top property and an appropriate value.
For your javascript, you'll need to additionally modify the top property when you modify the height.
Cheers.


text:
Q: How to get price for configurable product I have configurable products like

I created observer and I got the price
Default price is for 1kg but customer can change the weight and flavor.
When customer changes weight and flavor price changes.
like

I created observer in that I have code like
public function saveProductMrpInOrder(Varien_Event_Observer $observer) {
        $order = $observer->getEvent()->getOrder();
        foreach($order->getAllItems() as $item) {
            $price = Mage::getModel('catalog/product')->load($item->getId())->getPrice();
            $item->setProductMrp($price);
        }
      return $this;
    }

    public function saveProductMrpInInvoice(Varien_Event_Observer $observer) {
        $invoice = $observer->getEvent()->getInvoice();
        foreach($invoice->getAllItems() as $item) {
            $price = Mage::getModel('catalog/product')->load($item->getProductId())->getPrice();
            $item->setProductMrp($price);
        }
      return $this;
    }

    public function saveProductMrpInShipment(Varien_Event_Observer $observer)
{
        $shipment = $observer->getEvent()->getShipment();
        foreach($shipment->getAllItems() as $item) {
            $product = Mage::getModel('catalog/product')->load($item->getProductId());
            $price = $product->getPrice();
            $item->product_mrp = $price;
        }
    }

But in that I am getting default price which is for 1kg
But I want price for product according to attributes selected
How can I get that price.
Hope you understand.

A: From your question, it is not sure in which context you need to get the configurable product price.
In any context what you are missing is, you need to populate custom attribute options of the configurable product. After that, when you call getFinalPrice() on your configurable product instance you will get the correct price.
For more details, you can refer my blog post here. It shows how can populate custom attribute options of the configurable product if we have both configurable product and corresponding associated product.
For quick reference, I am adding the code snippet here.
$product        = Mage::getModel('catalog/product')->load(357); //configurable product
$optProduct     = Mage::getModel('catalog/product')->load(282); //associated simple product
$confAttributes = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
$pdtOptValues   = array();
foreach ($confAttributes as $attribute) {
    $attrCode    = $attribute['attribute_code'];
    $attrId      = $attribute['attribute_id'];
    $optionValue = $optProduct->getData($attrCode);
    $pdtOptValues[$attrId] = $optionValue;
}
$product->addCustomOption('attributes', serialize($pdtOptValues));
echo $product->getFinalPrice();

A: Try this
if($_product->getTypeId() == "configurable"):
    $conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
    $simple_collection = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
    foreach($simple_collection as $simple_product){
        echo $simple_product->getSku() . " - " . $simple_product->getName() . " - " . Mage::helper('core')->currency($simple_product->getPrice()) . "<br>";
    }
endif;


text:
Q: Does OpenVPN server require a public IP address? Does OpenVPN server require a public IP address so that an OpenVPN client can connect from anywhere? I mean anywhere where internet access is granted.

A: Yes, OpenVPN server requires a public, routable IP address and uses port 1194/UDP by default.


text:
Q: Dropdown navbar complication i dont know where it goes wrong but everything i try isnt getting my dropdown to close
and stays a big block.
anyone can show me what i do wrong so i can remind the problem and what i did wrong in the first place?
i tried to rework it all but cant figure out how i get in to drop down insted of staying open like that.

body       {font-family:'Lucida Grande', Helvetica, Arial, sans-serif;
            padding:20px 50px 150px;
            font-size:13px;
            text-align:center;
            background:#666;}

.navbar a   {text-decoration:none;
            color:#FF0004}

.navbar ul         {text-align:left;
                display:inline;
                   margin:0px;
                   padding:15px 4px 17px 0;
                   list-style:none;
                   -webkit-box-shadow:0 0 5px rgba(0, 0, 0, 0.15);
                   -moz-box-shadow:0 0 5px rgba(0, 0, 0, 0.15);
                   box-shadow:0 0 5px rgba(0, 0, 0, 0.15);}

.navbar ul li      {font:bold 12px/18px sans-serif;
                   display:inline-block;
                   margin-right:-4px;
                   postion:relative;
                   padding:15px 20px;
                   background:#fff;
                   cursor:pointer;
                   -webkit-transition:all 0.2s;
                   -moz-transition:all 0.2s;
                   -ms-transition:all 0.2s;
                   -o-transition:all 0.2s;
                   transition:all 0.2s;}

.navbar ul li:hover {background:#555;
                    color:#FFF;}

.navbar ul li ul    {padding:0;
                    postion:absolute;
                    top:48px;
                    left:0;
                    width:150px;
                    visibility:hidden;
                    -webkit-transition:opacity 0.2s;
                    -moz-transition:opacity 0.2s;
                    -o-transition:opacity 0.2s;
                    -transition:opacity 0.2s;}

.navbar ul li ul li {backgound:#555;
                    display:block;
                    color:#FFF;
                    text-shadow:0 -01px 0 #000;}

.navbar li ul li:hover {backgound:#666;}

.navbar ul li ul li:hover ul {display:block;
                             opacity: 1;
                             visibility:visible;
                             }

Home

Recepten

Lactosevrij

Suikervrij

Glutenvrij

Abonneren

Basis

Standaard

Luxe

Contact

A: You had some typos and also targeting the wrong ul.

body {
  font-family: 'Lucida Grande', Helvetica, Arial, sans-serif;
  padding: 20px 50px 150px;
  font-size: 13px;
  text-align: center;
  background: #666;
}

.navbar a {
  text-decoration: none;
  color: #FF0004
}

.navbar ul {
  text-align: left;
  display: inline;
  margin: 0px;
  padding: 15px 4px 17px 0;
  list-style: none;
  -webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
  -moz-box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
}

.navbar ul li {
  font: bold 12px/18px sans-serif;
  display: inline-block;
  margin-right: -4px;
  position: relative;
  /*position typo */
  padding: 15px 20px;
  background: #fff;
  cursor: pointer;
  -webkit-transition: all 0.2s;
  -moz-transition: all 0.2s;
  -ms-transition: all 0.2s;
  -o-transition: all 0.2s;
  transition: all 0.2s;
}

.navbar ul li:hover {
  background: #555;
  color: #FFF;
}

.navbar ul li ul {
  padding: 0;
  position: absolute;
  /*position typo */
  top: 48px;
  left: 0;
  width: 150px;
  visibility: hidden;
  -webkit-transition: opacity 0.2s;
  -moz-transition: opacity 0.2s;
  -o-transition: opacity 0.2s;
  -transition: opacity 0.2s;
}

.navbar ul li ul li {
  background: #555;
  display: block;
  color: #FFF;
  text-shadow: 0 -01px 0 #000;
}

.navbar li ul li:hover {
  background: #666;
}

/* i refactored this selector */

.navbar ul li:hover ul {
  display: block;
  opacity: 1;
  visibility: visible;
}

Home

Recepten

Lactosevrij

Suikervrij

Glutenvrij

Abonneren

Basis

Standaard

Luxe

Contact


text:
Q: Как всегда получать единственный инстанс одного и того же объекта mongoengine? При получении объектов из коллекции их внутренние ссылки резолвятся каждый раз по отдельности и заново. Как сделать, чтобы ссылки на один и тот же объект резолвились в один и тот же инстанс?
# -*- coding: utf-8 -*-
from __future__ import print_function
from mongoengine import connect, Document, StringField, ReferenceField

class User(Document):
    name = StringField()

class Order(Document):
    user = ReferenceField(User)

db = connect(db='test_me')

user = User(name='User One').save()
order1 = Order(user=user).save()
order2 = Order(user=user).save()

print('One user is one instance:', order1.user is order2.user)  # True

orders = list(Order.objects(user=user))

print('One user is one instance:', orders[0].user is orders[1].user)  # False
print(orders[0].user.pk, '==', orders[1].user.pk, '==>', orders[0].user.pk == orders[1].user.pk)


text:
Q: Create and populate field with name of feature (Select by Location) ArcPy I am staring at 5600 individual points and 60 polygons. I need to create a new field in the point fc called 'Basin Name' and populate the field with the name of the Basin that it lies in. I am trying to develop a reusable script that can be used weekly to accomplish newly inputed points. I have two features, SSO which are points and Basins which are polygons. I have tried to follow this thread (Assigning field value based on location without join) but I keep receiving an error on the SelectLayerByAttributes.
The error I receive is "Runtime error Traceback (most recent call last): File "", line 19, in  File "j:\apps\arcgis\desktop10.3\arcpy\arcpy\management.py", line 7221, in SelectLayerByAttribute raise e ExecuteError: ERROR 000358: Invalid expression Failed to execute (SelectLayerByAttribute)."
import arcpy

arcpy.env.workspace = "Y:/SSO_BASINS/"

# Set overwrite option
arcpy.env.overwriteOutput = True

# KEEPING ORIGINAL LAYERS (NOT CREATING ADDITIONAL "JOINED" LAYER)
# Create FeatureLayers
arcpy.MakeFeatureLayer_management("Y:/SSO_BASINS/Basins.shp", "lyr_Basins")
arcpy.MakeFeatureLayer_management("Y:/SSO_BASINS/SSO.shp", "lyr_SSO")

# Add a "BASIN" field
arcpy.AddField_management("lyr_SSO", "BASIN", "TEXT")

# Create a search cursor for the states
rows = arcpy.SearchCursor("lyr_Basins")
for row in rows:
arcpy.SelectLayerByAttribute_management("lyr_Basins", "NEW_SELECTION",
"\"OBJECTID\"  " + str(row.getValue("OBJECTID")))
arcpy.SelectLayerByLocation_management("lyr_SSO", "INTERSECT", "lyr_Basins",
"", "NEW_SELECTION")
arcpy.CalculateField_management("lyr_SSO", "BASIN",
"'{0}'".format(str(row.getValue("BASIN"))), "PYTHON_9.3", "")

A: The error indicates a bad SQL statement.
You want something like this:
"OBJECTID" = 7
Your code ("\"OBJECTID\"  " + str(row.getValue("OBJECTID"))) will yield this:
"OBJECTID" 7
Change your code to include the equal sign:
"\"OBJECTID\" = " + str(row.getValue("OBJECTID"))
I like .format for a bit cleaner code:
'"OBJECTID" = {}'.format (row.getValue("OBJECTID"))
Also, your field calculate expression is going to produce an error because you use single quotes instead of double quotes.
Your code:
"'{0}'".format(str(row.getValue("BASIN")))
needs a quick fix:
'"{0}"'.format(str(row.getValue("BASIN")))
At the end of the day though, I'd skip the cursor and the iterating of rows and just use a Spatial Join.

A: Since you're using ArcMap 10.3 you should use the arcpy.da.SearchCursor instead of the deprecated arcpy.SearchCursor. Also, your arcpy.SelectLayerByLocation_management syntax is backward. You are selecting within your lyr_SSO layer when you want to be selecting within the lyr_Basins feature. The SelectLayerByAttribute_management step is unnecessary since you are already looping through the rows. You can use the SHAPE@ field as your selection location.
import arcpy

# Set overwrite option
arcpy.env.overwriteOutput = True

# KEEPING ORIGINAL LAYERS (NOT CREATING ADDITIONAL "JOINED" LAYER)
# Create FeatureLayers
lyr_basin = arcpy.MakeFeatureLayer_management("Y:/SSO_BASINS/Basins.shp", "lyr_Basins")
lyr_sso = arcpy.MakeFeatureLayer_management("Y:/SSO_BASINS/SSO.shp", "lyr_SSO")

# Add a "BASIN" field
arcpy.AddField_management(lyr_sso, "BASIN", "TEXT")

with arcpy.da.UpdateCursor(lyr_sso, ["BASIN", "SHAPE@"]) as ssoCursor:
    for row in ssoCursor:
        arcpy.SelectLayerByLocation_management(lyr_basin, "INTERSECT", row[1], "", "NEW_SELECTION")
        with arcpy.da.SearchCursor(lyr_basin, ["BASIN"]) as basCursor:
            for brow in basCursor:
                row[0] = brow[0]
                ssoCursor.updateRow(row)


text:
Q: Date range selector similar to Google Analytics date range selector? I'm building a web app where the vast majority of our target audience likely have experience with Google Analytics - and as a part of that website there is a date range selector.  I was hoping to find an off-the-shelf javascript/jquery date range selector to customize to my needs, but I'm not a fan of the stock version that jquery provides because it lacks the actual date inputs, it only has the two visual calenders.  I listed what I'm looking for below.
What I'd love:

*

*Select a start and end date on a
single calender (preferably with two
months shown).

*Enter the start and end date manually
into an input box

*Highlighting of selected date range
(changing background-color of dates
within 'start' and 'end').

*Fairly easy to get at the CSS /
layout elements
What I don't need:

*

*A timeline selector

*Compare to past

Thanks for helping out!

A: jquery-ui-datepicker do not have date range selector. Just found out this nice plugin which does that - http://www.eyecon.ro/datepicker/
update
Recently started using another open source plugin and it's working great too.
https://github.com/dangrossman/bootstrap-daterangepicker

A: I like this one due to the quick select of common ranges such as year to date, today etc. The code looked pretty readable, so i guess it would be possible rewrite it slightly to align with use cases for the application.
http://www.filamentgroup.com/examples/daterangepicker_v2/

A: jquery-ui-datepicker
http://jqueryui.com/demos/datepicker/#multiple-calendars
here is also a listing of other plug ins
http://www.bloggingdeveloper.com/post/8-Widely-Used-Calendar-Date-Picker-and-Time-Formatting-jQuery-Plugins-that-Web-Developers-Should-Know.aspx


text:
Q: Java project - mariadb syntax error when i try to create a procedure I am developing a script in Java with which I manipulate files and execute queries on the DB, in particular I use MariaDB.
In the script I need to create a procedure, called NP_update_collection_state.
But when I run the script the error You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'delimiter ;; CREATE PROCEDURE ....
Do you have any suggestions or advice? It is the first time that this error has occurred to me and I cannot understand the problem.
Reading about problems here on stack I noticed that the problem could come from delimiter, I tried to remove it but I always get syntax error.

*

*My procedure:

String sqlCreaNP =  "DROP PROCEDURE IF EXISTS `NP_aggiorna_stato_riscossione`; "+
 "delimiter ;; "+
 "CREATE PROCEDURE `NP_aggiorna_stato_riscossione`() "+
 "BEGIN "+
 " "+
 " "+
   "DECLARE finito INTEGER DEFAULT 0; "+
   "DECLARE M_saldato INTEGER DEFAULT NULL ;"+
   "DECLARE M_parametroDiTolleranza decimal(11,2) DEFAULT 3; "+
   "DECLARE contatore INT DEFAULT 0; "+
   "DECLARE righeTrovate INT DEFAULT 0; "+
   "DECLARE W_eseguito INT DEFAULT 0; "+
   " "+
    "DECLARE W_idDoc bigint(13) unsigned zerofill DEFAULT NULL; "+
    "DECLARE W_docImporto decimal(11,2) DEFAULT 0; "+
    "DECLARE W_versato decimal(11,2) DEFAULT 0; "+
    "DECLARE W_ancoraDaVersare decimal(11,2) DEFAULT 0; "+
    " "+
    " "+
    "DEClARE CF_cursor CURSOR FOR "+
        "SELECT tbl_versamenti_f24.idDoc, tbl_documento.docImporto, sum(importoDebito), (tbl_documento.docImporto - sum(importoDebito)-tbl_statoriscossione.docVersato) "+
        "FROM tbl_versamenti_f24 INNER join tbl_documento on tbl_versamenti_f24.idDoc=tbl_documento.idDoc "+
        "inner join tbl_statoriscossione on tbl_statoriscossione.idDoc=tbl_versamenti_f24.idDoc "+
        "where tbl_versamenti_f24.idDoc is not null "+
        "group by tbl_versamenti_f24.idDoc "+
        "order by 4; "+
        " "+
        " "+
    "DECLARE CONTINUE HANDLER "+
    "FOR NOT FOUND SET finito = 1; "+
    " "+
    " "+
    "SELECT ' ' as '*** Inizio riconciliazione ***', curdate() as 'data iniziale', curtime() as 'ora iniziale'; "+
    "INSERT INTO tbl_splog (marcatura,evento,valore) values (current_timestamp(),'Inizio riconciliazione','NP'); "+
" "+
" "+
    "SELECT eseguito into W_eseguito from tbl_controllo where evento = 'NP_aggiorna_stato_riscossione'; "+
    " "+
    " "+
        "update tbl_statoriscossione "+
            "set docPagato = 1 "+
            "where docImporto <=0; "+
 " "+
    "OPEN CF_cursor; "+
    "set righeTrovate = FOUND_ROWS(); "+
    "select righeTrovate; "+
 " "+
 " "+
 "get_dati: LOOP "+
    "FETCH CF_cursor INTO W_idDoc,W_docImporto,W_versato,W_ancoraDaVersare; "+
    "IF finito THEN "+
        "LEAVE get_dati; "+
    "END IF; "+
    " "+
        "set M_saldato = 0; "+
        "if (M_parametroDiTolleranza > W_ancoraDaVersare)  "+
        "then "+
            "set M_saldato = 1; "+
        "end if; "+
        "UPDATE tbl_statoriscossione "+
        "SET docVersato = W_versato, quantoManca = W_ancoraDaVersare, docPagato = M_saldato "+
        "where idDoc = W_idDoc; "+
 " "+
 "END LOOP get_dati; "+
 " "+
 "CLOSE CF_cursor; "+
 " "+
 " "+
 " "+
 " "+
 " "+
   " -- update tbl_rata A join tbl_versamento_new S on S.idBol = A.idBol "+
   " -- set A.pagato = 1; "+
" "+
" "+
" "+
" "+
 "END "+
 ";; "+
 "delimiter ;";


text:
Q: Magento 2 Design Configuration error I am trying to open the Design configuration in Magento 2 but it entered in infinite loop of loading,and when i inspect the page i got this error
Uncaught TypeError: Constr is not a constructor in layout.js:66,can anyone help me in that?

Uncaught TypeError: Constr is not a constructor
      at Object.initComponent (http://127.0.0.1:7777/Magento/pub/static/version1493554470/adminhtml/Magento/backend/en_US/Magento_Ui/js/core/renderer/layout.js:66:25)
      at fire (http://127.0.0.1:7777/Magento/pub/static/version1493554470/adminhtml/Magento/backend/en_US/jquery.js:3099:30)
      at Object.fireWith [as resolveWith] (http://127.0.0.1:7777/Magento/pub/static/version1493554470/adminhtml/Magento/backend/en_US/jquery.js:3211:7)
      at Object.deferred.(anonymous function) (http://127.0.0.1:7777/Magento/pub/static/version1493554470/adminhtml/Magento/backend/en_US/jquery.js:3301:34)
      at fire (http://127.0.0.1:7777/Magento/pub/static/version1493554470/adminhtml/Magento/backend/en_US/jquery.js:3099:30)
      at Object.fireWith [as resolveWith] (http://127.0.0.1:7777/Magento/pub/static/version1493554470/adminhtml/Magento/backend/en_US/jquery.js:3211:7)
      at Object.deferred.(anonymous function) [as resolve] (http://127.0.0.1:7777/Magento/pub/static/version1493554470/adminhtml/Magento/backend/en_US/jquery.js:3301:34)
      at http://127.0.0.1:7777/Magento/pub/static/version1493554470/adminhtml/Magento/backend/en_US/Magento_Ui/js/core/renderer/layout.js:59:20
      at Object.execCb (http://127.0.0.1:7777/Magento/pub/static/version1493554470/adminhtml/Magento/backend/en_US/requirejs/require.js:1650:33)
      at Object.context.execCb (http://127.0.0.1:7777/Magento/pub/static/version1493554470/adminhtml/Magento/backend/en_US/mage/requirejs/resolver.js:131:31)

A: It seems like you website deploy is not properly completed. Use the below commond and deploy again:
rm -rf var/*
rm -rf pub/static/*
php bin/magento setup:upgrade   //(only for new extensin)
php bin/magento setup:static-content:deploy
chmod -R 7777 var pub


text:
Q: google maps api convert polygon to circle I have a geoJson for a polygon which represents a circle and I need to draw a circle from the polygon geometry.
I get the geoJson from a DB and I can draw the polygon but if the geoJson was made from a circle I need to draw a circle instead of a polygon.
Update:
I found a way to compute the radius, now I need just a way to compute the coordinate for center.
var geometry = JSON.parse(retZones["GeoJSON"]);
var data = {
    type: "Feature",
    geometry
};

var geoJsonLayer = new google.maps.Data();
var newFeature = geoJsonLayer.addGeoJson(data);
var newGeometry = newFeature[0].getGeometry();

// If the geoJson represents a polygon (I get this info from DB) I draw the polygon
if (retZones["TypeGeometry"] == "Polygon") {
    var shape = [];
    for (var i = 0; i < newGeometry.getLength(); i++) {
        var shapeData = newGeometry.getAt(i).getArray();
        shape.push(shapeData);
    }

    var newShape = new google.maps.Polygon({
        paths: shape,
        fillColor: '#ffff00',
        fillOpacity: 0.4,
        strokeWeight: 2,
        clickable: true,
        zIndex: 1,
        editable: false
    });
}
// If the geoJson represents a circle I have to draw a circle
else if (retZones["TypeGeometry"] == "Circle") {
    var p1 = { lat: newGeometry.getAt(0).getArray()[0].lat(), lng: newGeometry.getAt(0).getArray()[0].lng() };
    var p2 = { lat: newGeometry.getAt(0).getArray()[180].lat(), lng: newGeometry.getAt(0).getArray()[180].lng() };
    var c = ; // How to compute the center?
    var r = google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 2;

    var newShape = google.maps.Circle({
        center: c,
        radius: r,
        fillColor: '#ffff00',
        fillOpacity: 0.4,
        strokeWeight: 2,
        clickable: true,
        zIndex: 1,
        editable: false
    });
}

A: I found out this solution and it seems to work. If someone have a better way please let me know.
var ns = newGeometry.getAt(0).getArray().length;
var N = 0;
var E = Math.round(ns / 4);
var S = E * 2;
var W = E * 3;
var p1 = { lat: newGeometry.getAt(0).getArray()[N].lat(), lng: newGeometry.getAt(0).getArray()[N].lng() };
var p2 = { lat: newGeometry.getAt(0).getArray()[S].lat(), lng: newGeometry.getAt(0).getArray()[S].lng() };
var p3 = { lat: newGeometry.getAt(0).getArray()[E].lat(), lng: newGeometry.getAt(0).getArray()[E].lng() };
var p4 = { lat: newGeometry.getAt(0).getArray()[W].lat(), lng: newGeometry.getAt(0).getArray()[W].lng() };
var c = { lat: p2.lat - ((p2.lat - p1.lat) / 2) , lng: p4.lng - ((p4.lng - p3.lng) / 2) };
var r = google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 2;


text:
Q: using SQL to directly delete CoreData data from my DB There are times when i will need to delete say 10,000 rows from my CoreData data store and looping through those records individually each time takes way too long.
Is there a way to use SQL to directly delete from my data store quickly?

A: Modifying the CoreData store directly risks corrupting the database and is very highly discouraged. Your best bet is to delete with a CoreData query that is able to select all of the rows to be deleted at once.
When I say it risks corrupting, I don't mean that anything would be wrong with your SQL query, but that CoreData also inserts a lot of metadata into the database to help its indexing.


text:
Q: How to prevent group creation in GitLab I have setup GitLab 7.12 in my firm. But users start creating groups (and groups and groups ...) and it will become a total mess very soon.
Does anyone know how to restrict groups creation to administrators of the platform ?
The idea is to have people creating projects in their personal space, and reserving groups for official ones.

A: *

*Enter the Admin control panel

*Select 'Users'

*Select the user(s) in question and click 'Edit'

*Scroll down to 'Access' and un-tick 'Can Create Group'

If you want to disable group creation for new users, at the moment you will have to edit the gitlab.yml, specifically the setting default_can_create_group, and set it to false.
See gitlab.yml#L63@712d1768.

A: For existing users, you can also use the following command on gitlab-rails console:
irb(main):001:0> User.update_all can_create_group:false

A: For an Omnibus install, the correct place is:
   /etc/gitlab/gitlab.rb
      gitlab_rails['gitlab_default_can_create_group'] = false

Then you'll need to execute sudo gitlab-ctl reconfigure and sudo gitlab-ctl restart to apply the changes.

A: And for old users, use something like (in rails console):
irb(main):012:0> @users.each do |u|
irb(main):013:1*  u.can_create_group= false
irb(main):014:1> u.save
irb(main):015:1> end

A: For old users, the GitLab Users API: User modification (a REST API) can also be used for this purpose (set the value of can_create_group to false) and can be easily used for bulk changes in a for loop:
curl --request PUT https://gitlab.example.com/api/v4/users/:id?can_create_group=false

Note: Please have a look at available authentication methods at GitLab API Authentication.

A: GitLab 15.5 (October 2022) can help:

Admin Area setting to prevent users from creating groups
GitLab administrators can now use the Admin Area to disable users' permission to create top-level groups. Previously, administrators with access to the instance's file system could change this setting only in the gitlab.rb file.
See Documentation and Issue.

issue 367754: "Shift option to prevent users from creating groups to Instance Admin UI", resolved with MR 2763:

Deprecate default_can_create_group setting
In MR 96746 (merged), we are migrating the setting default_can_create_group and its current value from the configuration file to the UI/API and hence this setting cannot be controlled via the configuration file anymore.

And:

Make this setting available in ApplicationSetting, so that an Admin can control this setting via the UI/API and does not have to change the value in the gitlab.yml file anymore.
Moving this setting to ApplicationSetting would also mean that GitLab admins won't have to restart the instance for the change to take effect.

Hence the notice:

global.appConfig.defaultCanCreateGroup setting has been deprecated.
Starting with GitLab 15.5, this setting cannot be controlled via the configuration file anymore.
Follow the steps at Account and limit settings, to configure this setting via the Admin UI or the API.

A: In regard to helm deployment, changing this on the config is not available anymore, https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/templates/NOTES.txt#L138
`global.appConfig.defaultCanCreateGroup` setting has been deprecated. Starting with GitLab 15.5, this setting cannot be controlled via the configuration file anymore. Follow the steps at https://docs.gitlab.com/ee/user/admin_area/settings/account_and_limit_settings.html#prevent-users-from-creating-top-level-groups, to configure this setting via the Admin UI or the API.


text:
Q: Проверить вызов конструктора суперкласса из наследника в нем же Есть класс, который наследуется парой других. В них значения переменной unit принадлежат другим emun'ам. Необходимо проверить, что конструктор суперкласса вызывается наследником или же нет.
Подскажите, пожалуйста каким образом это можно реализовать?
public CellSpec(String unit, String name, Integer index, String type, boolean emptiness) {
        this.index = index;
        this.name = name;
        try {
            this.type = Config.VariableType.valueOf(type);
        } catch (IllegalArgumentException e) {
            this.type=null;
        }

        this.emptiness = emptiness;
        try {
            this.unit = Config.AfdxStructUnit.valueOf(unit);
        }catch (IllegalArgumentException e){

            //**Здесь нужна проверка на вызов конструктора из класса наследника**

            this.unit=null;
        }

    }

A: Если вы в конструкторе родительского класса хотите знать, не вызван ли он из дочернего,  то это указывает на проблемы в дизайне ваших классов.
Вам стоит передавать unit не строкой, а enum-ом. Если enum-ов несколько - заставьте их имплементировать общий интерфейс.
В качестве костыля здесь-и-сейчас: дочерние классы могут передавать в конструктор родительского параметр типа boolean или Class. Но, повторюсь, это плохо и когда-нибудь выстрелит вам в ногу.
Еще можно сделать ваш нынешний конструктор приватным, и обернуть в static-метод, чтобы не позволить потомкам его вызвать. А для потомков сделать отдельный protected-конструктор.
Я имею в виду что-то вроде такого:
private CellSpec(String unit, String name, Integer index, String type, boolean emptiness) {
    // ваш текущий код
}

protected CellSpec(String name, Integer index, boolean emptiness) {
  // конструктор для потомков
}

// фабрика для пользователя
public static CellSpec create(String unit, String name, Integer index, String type, boolean emptiness) {
    return new CellSpec(unit, name, index, type, emptiness);
}

Но лучше избавиться от всей этой логики с исключениями в конструкторе и то что станет enum-ом передавать как enum.


text:
Q: Generating event when user clicks in textarea with disabled=true, to tell them they can't modify it I want to tell the user they can't modify a textarea that's been disabled for update, when they try to click in it.  How can I tell them why it is disabled in this case, e.g. with an alert?
The problem is/was, when I give the textarea a disabled attribute, the events for it don't fire off either (at least in Chrome).

A: I'm guessing your main concern is that the disabledattribute doesn't allow events on IE.
The readonlyattribute, however, does:
<texarea readonly onclick="alert('Please do not edit me!');">

A: Use the onclick property in the textarea tag. You could do it something like this:
<textarea onclick="alert('CAN'T TOUCH THIS!')">
    blahblahblahblahblahblahblah
</textarea>

Here's another example:
<textarea onclick="textareaclicked();">
    blahblahblahblahblahblahblah
</textarea>

One final example:
<textarea onclick="textareaclicked('Someone set up us the bomb :(');">
    blahblahblahblahblahblahblah
</textarea>

A: I think you should only use a disabled html attribute and do some stylish to disabled elements like a gray color:

<textarea disabled="disabled" class="disabled" title="Disable for update"></textarea>

A: I would say wrap it in a span and give that the event. (note to all, it doesn't allow a click event on a disabled textarea in chrome).
http://jsfiddle.net/yU7ku/
HTML
<textarea disabled></textarea>

jQuery
$("[disabled]")
    .wrap("")
    .parent()
    .click(function(){
        alert("this "+this.firstChild.nodeName+" is disabled");
    });


text:
Q: Создание страницы из категории. Drupal 8 Доделываю сайт на drupal 8.
Есть страница , допустим кровати, на которой есть фильтр по кроватям. Фильтр такой "синие, зеленые, красные, двухярусные".
Финальная цель такая:
Есть пункт меню "кровати" в котором подпункты "кровати, двухярусные".
при переходе на страницу двухярусных должны показаться только двухярусные кровати.
Смотрел в сторону таксономии. На странице двухярусные кровати, на которую перехожу из пункта, таксономии, нечего нет)
Как можно такое вывести?

PS
понимаю что описал очень мыльно, мутно.

Задавайте вопросы пожалуйста наводящие, если не понятно.
ГУГЛИЛ, по документации ХОДИЛ. Нечего не понятно
PPS Я начинающий юзверь bitrix, с drupal-ом на ВЫ.

A: делайте так что каждый товар буде иметь поле Категории типа Taxonomy term, потом выводите страницу с помощью views.
При этом добавив в созданой view CONTEXTUAL FILTERS, это параметры которые с урла будут считываться. Потом просто в меню указиваете ссилки с этими параметрами
Здесь нужно понимать эти инструменты, сейчас не могу описать их но всегда можно доку посмотреть или example


text:
Q: Query with no terms uses index.php template instead of archive.php I'm using the Query Multiple Taxonomies plugin to get a page of search results (all of which are a custom post type - car).
If any search terms are added, so the url looks like this:
http://mysite.com/car/?makemodel=ford&body=&gearbox=&fuel=&minprice=&maxprice=

then the archive.php template is used. However, if the user clicks search without adding any terms, so the url looks like this:
http://mysite.com/car/?makemodel=&body=&gearbox=&fuel=&minprice=&maxprice=

then index.php is used instead. I'd like to ensure this 'empty' search uses the archive.php template too.
These bits from my functions file may be relevant:
// Ensure Custom Post Type is included in query

add_action( 'pre_get_posts', 'add_my_post_types_to_query' );

function add_my_post_types_to_query( $query ) {
    if ( is_home() && $query->is_main_query() )
        $query->set( 'post_type', array('car' ) );
    return $query;
}

// Tweaks to taxonomy layered search

function my_qmt_base_url( $base ) {
    return get_bloginfo('home').'/car/';
}
add_filter( 'qmt_base_url', 'my_qmt_base_url' );

function my_qmt_reset_url( $reset_url ) {
    $url = get_permalink();
    return $url;

}
add_filter( 'qmt_reset_url', 'my_qmt_reset_url' );

Any help would be much appreciated!
Graham

A: You could filter template_include:
add_filter( 'template_include', 'wpse_97347_force_archive' );

function wpse_97347_force_archive( $template )
{
    if ( isset ( $_GET['makemodel'] ) && empty ( $_GET['makemodel'] ) )
        return get_archive_template();

    return $template;
}

Not tested.


text:
Q: How would you store and access data in Android app? I am making a dictionary app and need to store and access my data from the app. My goal is to make a completely offline dictionary.
I have all the data needed in JSON format (the file is about 9 MB), so I can convert it into any other format or even into sqlite database.
I try to dig some guides, but it appears to me that Android apps use sqlite only for user data. But I know that there are plenty of other offline dictionaries.
How do they store words and translations internally in the app? And what is the best way to do that?

A: For the amount of data you need to store, SqlLite is the best option. Sqlite has a wide array of applications in Android apps; their scope is not limited to storing user data. The next best option would be to save the Json in a text file. You can then load the Json data in memory (when the app starts) and transform that to a dictionary structure with the JSON parsers.
Downside of JSON: You need to load your entire stored JSON in memory before parsing it. With 9MB, its not a good idea.
SQLite is the best option if you do not want your 'entire' dictionary in memory at all times and need values only on a look up basis. You also get the full functionality of basic SQL statements with SQLite. Also, there is a lot of SQLite help online; choosing tried and tested technology is always good.

A: Take a look at the developers website: http://developer.android.com/guide/topics/data/data-storage.html


text:
Q: Is there a way to run a command line "inside" a symlink? I have a symlink named example.avi that points to a real example.avi video file.  When a program tries opens the symlink, it really opens the video file.  But now I would like execute a command line whenever a program tries to open the symlink file.
Is that possible?
ps: windows

A: No, there is no built-in way of creating a symlink or other file system object that causes a command to be executed when it is opened by an application.
It should in principle be possible to do this with a file system filter driver.  But that's very complicated.  I believe there are some third-party tools to simplify this sort of task, but I don't have any experience with them.

A: While I am clearly ignorant on the subject of symlinks in Windows (see my comments on your question).  I just played with it and proved that you could basically do this by symlinking to a wrapper for your avi.  I.e. symlink to an exe or a batch file, etc. which does what you want and then opens the avi.  Here's a test I ran with txt files and notepad:
Create a file called test.txt with some text.  Create a file next to it called test.bat.  Here's the batch:
notepad test.txt

When you run the batch, it just opens the txt in notepad.
Then I added a symlink:
mklink test2.txt test.bat

Now, when I type test2.txt in the command prompt, or double click on it, it runs the batch and opens the test.txt file.  Obviously, you can use the same basic logic.  It doesn't, however, fire the batch off when I open the symlink in Notepad++.  It just opens to batch for editing instead.
Of course, maybe you don't want a second file, in which case you need to literally embed your avi in some wrapper.  I guess we ned to know more about what you want to do.  It sounds like an attempt at malware hidden in a video to me...


text:
Q: Знаки вопроса из MySQL Проблема с выводом из БД. Везде utf-8. База utf8_general_ci . Вот код.
<!doctype html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<?php
$mysqli = mysqli_init();

if (!$mysqli->real_connect('localhost', 'roly', 'O1z6H7v8', 'sushiris')) {
    die('Ошибка подключения (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
    mysql_query("SET NAMES utf-8");
}

$products = array();
if ($result = $mysqli->query('SELECT * FROM products')) {
    while($tmp = $result->fetch_assoc()) {
        $products[] = $tmp;
    }
    $result->close();
}
$mysqli->close();
?>

    <?php foreach($products AS $product) {?>
        <div class="col-sm-4 col-lg-4 col-md-4 <?php echo $product['filter'];?>">

<?php echo $product['title'];?>

                <img src="<?php echo $product['img'];?>" alt="" width="200">

<?php echo $product['price'];?> грн

<?php echo $product['description'];?>

Ссылка - #win<?php echo $product['id'];?>

Вес: <?php echo $product['weight'];?>гр

   <?php } ?>

Не могу понять почему везде знаки вопроса http://sushi.sushiris.kiev.ua/index-s.php

A: Попробуйте указать кодировку работы с базой после установления соединения.
$mysqli->set_charset("utf8");

Естественно кодировка базы, таблицы и полей должна быть идентичной, равно как у файла скрипта. А также необходимо задать кодировку по умолчанию.
.htaccess
AddDefaultCharset UTF-8

nginx
charset UTF-8;

A: Добавьте в начало
header('Content-Type: text/html; charset=utf-8');


text:
Q: how this code will work for bigger range number? if the range of d is 1<= d <= 10^101  and n is 1<= n <= 200. since the range of double is 2.3E-308 to 1.7E+308. when i take input 11111111111111111111 as d then the value d become 11111111111111111000.000 when i show the value to terminal. that means that it couldn't take the input correctly then how will it give correct value for 10^101. i need know the nth root of d. d will be always in form of p = k^n. that's why i added pow function to know the nth root. but the problem is that the range of p is huge. what i am trying is to solve this problem  Power of Cryptography !
int main(){

 double d,n;

 scanf("%lf%lf", &n, &d))
 {
     printf("%lf\n", pow(d, 1/n));
 }

  return 0;
}

A: A double precision number is not capable of holding all the values between  2.3E-308 to 1.7E+308, it is capable of holding a value between these numbers to a precision of about 15 decimal places.
That means some numbers (such as your example) require more precision than the 8 bytes of data can store.


text:
Q: Inequality and Euler's method
Let $y'(s)=y^2(s),y(0)=1$ be an ode on $s\in \mathbb{R}_+\setminus\{1\}$. Let $h_n=s_{n+1}-s_n$. Prove the following inequality with the Euler method $\forall n:s_n<1$ the following holds
  $$y_n\leq \frac{1}{1-s_n}$$
  The explicit Euler method is: $$y_{n+1}=y_n+h_nf(s_n,y_n)$$

The problem is, I don't know if I have to use somewhere Gronwall's lemma or if it is straight calculation. The solution to the ODE is $y(s)=\frac{1}{1-s}$ and here is what I've tried so far $$y_{n+1}=y_n+h_nf(s_n,y_n)$$
becomes
$$y_n=y_{n+1}-h_nf(s_n,y_n)$$
$$y_n=y_{n+1}-(s_{n+1}-s_n)y_n^2$$
But then I get stucked, since I don't see how I can remove the $y_{n+1}$ and $s_{n+1}$ terms without getting new recursive terms. Or do I have to use the geometric series?

A: Maybe a proof by induction. You have, since $s_0=0$,
$$
y_0=1=\frac{1}{1-s_0}.
$$
If
$$
y_n\leq\frac{1}{1-s_n}
$$
then
$$
\begin{aligned}
y_{n+1}&=y_n+h_n (y_n)^2\\
&\leq\frac{1}{1-s_n}+h_n\frac{1}{(1-s_n)^2}\\
&=\frac{1}{1-(s_{n+1}-h_n)}+h_n\frac{1}{(1-(s_{n+1}-h_n))^2}\\
&=\frac{1}{1-s_{n+1}}-\frac{h_n^2}{(1-s_{n+1})(1-s_{n+1}+h_n)^2}\\
&\leq\frac{1}{1-s_{n+1}}.
\end{aligned}
$$
We are done.

A: In recursions of the form $x_{n+1}=x_n+c_nx_n^2$ you can consider the reciprocal series $u_n=1/x_n$, $u_nx_n=1$, and use the geometric series/binomial identities to find helpful inequalities like
$$
u_{n+1}=\frac1{x_n(1+c_nx_n)}=u_n\frac{1-c_nx_n}{1-c_n^2x_n^2}>u_n-c_n
$$
Summation of this gives
$$
u_n>u_0-\sum_{k=0}^{n-1}c_k
$$
so that in the original series
$$
x_n<\frac{x_0}{1-x_0\sum_{k=0}^{n-1}c_k}
$$


text:
Q: Print width different on chrome and safari I'm implementing a report viewer on a modal view.
these are some of print styles:
@page{
   margin: 5mm;
}

body{
   visibility: hidden;
}
.modal-report{
   width: 100%;
   height: 100%;
   margin: 0;
}
#report-view-container-id, #report-view-container-id *{
   visibility: visible;
}
#report-view-container-id{
   width: 100%;
   height: 100%;
   position: absolute;
   top:0;
   left: 0;
}

.report-view-container-letter
{
   max-width: 23.59cm;
   max-height: 27.94cm;
   min-width: 23.59cm;
   min-height: 27.94cm;
   padding-right: 15px;
   padding-left: 15px;
}

On firefox when I try to print works great the width is perfect but on google chrome and safari the with is around 60%.
There is already a question asked 6 years ago but that say nothing.
On firefox:

On google chrome and safari:

This is a little plnkr trying to recreate my case

A: I ran into a similar issue when printing in Safari. The text was not wrapping and would run off of the right side of the page. To fix this I added the following to my style sheet. The most important element to nuke was Bootstrap's .container class.
@media print {
html, body, main, header, footer, .container {
    background: transparent !important;
    color: #000 !important;
    box-shadow: none !important;
    text-shadow: none !important;
    position: relative !important;
    text-indent: 0 !important;
    clear: both !important;
    width: auto !important;
    height: auto !important;
    border: none !important;
    overflow: visible;
    margin: 0 auto 0.5% auto !important;
    top: auto !important;
    left: auto !important;
    right: auto !important;
    bottom: auto !important;
    padding: 0 !important;
    text-align: left !important;
    max-width: none !important;
    min-width: auto !important;
    min-height: auto !important;
    max-height: auto !important;
    direction: ltr !important;
}}

BEFORE:

AFTER:

A: This isn't an answer yet, but a comment won't let me include the formatting I need…
@page isn't a valid media query and will just be ignored. For print styles, this should be @media print. The margin isn't being applied to anything - you want something like
@media print {
    mytargetelement {
        margin: 5mm
    }
}

Does that help your problem at all?

A: try giving width and min-width and position to your css class
width: 30%;
position: relative;
min-width: 20vh;


text:
Q: $C(X)$ separates points? Let $X$ be a compact Hausdorff space and $C(X)$ the space of continuous functions on $X$. In many proofs in abstract harmonic analysis we use the fact $C(X)$ separates points in $X$.
It might seem trivial but the only way I can think of why this is true is by applying Urysohn's lemma.
I wonder whether there is some more elementary way to show that $C(X)$ separates points.
Thanks!

A: Though I'm not an expert, it seems unlikely to me that you can have something better, more elementary, than Urysohn's lemma for what you want.
Even if you're right that it may seem that Urysohn's lemma is too much, because what it gives is the separation of closed sets and you're asking just for separation of points.
Moreover, at first glance, you can easily prove implications like the following ones. If there are enough continuous functions $f: X \longrightarrow [0,1]$

*

*to separate points (that is, for every pair of points $x,y \in X$ there is a continuous function $f$ such that $f(x)= 0$ and $f(y) = 1$), then $X$ must be a Hausdorff space. Indeed, $f^{-1}([0,1/2))$ and $f^{-1}((1/2, 1])$ are disjoint open sets, cointaining $x$ and $y$, respectively.

*to separate points from closed sets (that is, for every point $x$ and every closed set $A \subset X$, $x \notin A$, there exists a continuous function such that $f(x) = 0$ and $f(a) =1$ for all $a\in A$), then $X$ must be regular. An analogous prove aplies.

*to separate closed sets from closed sets, then $X$ must be normal. Ditto.

In this context, the Urysohn's lemma says that, in fact, the last implication is an equivalence; that is, an space is normal if and only if there are enough continuous functions to separate closed sets.
So, a natural question would be: Why aren't there analogous reciprocal implications in the other two cases? That is, why we don't have Urysohn type lemmas for Hausdorff and regular spaces?
Well, I know at least two reasons:

*

*In the case of regularity, the separation of points from closed sets with continuous functions is an stronger condition than separation with open sets. Together with the requirement of the space being Fréchet, this is called complete regularity. There are examples of regular spaces which are not completely regular ones; that is, spaces where you can separate points from closed sets with open sets, but not with continuous functions.  You can find such an example in the book of Munkress (section 5.2, exercise 6; see also example 1 after theorem 2.1 in the same section).

*I don't know the situation for the Hausdorff condition. [EDIT. See Brian M. Scott's comments: there is also a notion of "completely Hausdorff".] But I can tell you where the standard proof of Urysohn's lemma will break down with Hausdorff (or regular) spaces: you construct your separating function as a certain limit of step functions, which miraculously is continuous. You begin with $f_0$ the characteristic function of your point $y$. Then you find an open set $V$ such that $x\in V \subset \overline{V} \subset X\backslash \{ y\}$ and define $f_1$ as being $0$ on $x$, $1/2$ on $V\backslash \{x\}$ and $1$ on $X\backslash V$. In the following steps, you introduce new open sets at each inclusion $\{x\}\subset V  $ and $\overline{V} \subset X \backslash \{ y\}$ and define your next step function with $1/2^n$ height steps. The Hausdorff condition gives you that open set $V$ here, but the restriction about its clousure seems really necessary in order to assure the continuity of the limit of these step functions. This is unfortunate, because, for the next steps, you are going to need in general that,  given a closed set $A$ (that $\overline{V}$ that has already appeared in the first step) and an open set $U$ such that $A \subset U$, there exists an open set $V$ such that $A \subset V \subset \overline{V} \subset U$. And you can do this for every such $A$ and $U$ if and only if the space $X$ is normal.


text:
Q: LinkedIn "The token used in the OAuth request is not valid. consumer Key: 'value of consumer key' " I have an application in asp.net c#.
In which i can post anything and that post will also be posted on users own LinkedIn account.  I am getting exception

The token used in the OAuth request is not valid. consumer
  Key:Consumer key value from responseReader = new
  StreamReader(webRequest.GetResponse().GetResponseStream());

What is the meaning of this exception?
Note: I am setting Client API Key as consumer key And webRequest Header contains
oauth_token,realm,oauth_consumer_key,oauth_signature_method,oauth_token_secret,
`oauth_signature`, `oauth_timestamp`, `oauth_nonce`, `oauth_verifier`, `oauth_version=1.0`

But verifier and token secret is blank.
What should i do?

A: There can be various events which can cause an access token to become invalid:
1. Life of access token expires: Generally, lifetime of linkedin access token is 60 days. In case this time period is elapsed, the access token expires and becomes invalid.
2. User revokes permissions to your application from LinkedIn.com: If user has revoked the permissions to your application, then also access token becomes invalid.
In both the cases, your application then needs to take the user through the authorization flow again.
Also verify that the access token you are using for API call is a valid token.
For reference: https://developer-programs.linkedin.com/documents/handling-errors-invalid-tokens


text:
Q: Can 2 Linq Queries be run parallel? I have 2 Linq Queries, 1st Linq Query returns 1148 records and 2nd returns 6667 records. They take 8 minutes in execution. Is there any way to make them faster while running parallel?

var productbacklogworkitem =
               (from w in workItemcollectionList where w.Type.Name == "Product Backlog Item" select new {
                   Id = w.Id,
                   Name = w.Title,
                   FID = (w.WorkItemLinks.Count > 0) ? ((w.WorkItemLinks[0].LinkTypeEnd.Name.ToString() != "Child") ? w.WorkItemLinks[0].TargetId : 0) : 0,
                   Type = w.Type.Name,
                   State =w.State,
                   priorty = Convert.ToInt32(w.Fields["Priority"].Value),
                   Size = Convert.ToInt32(w.Fields["Effort"].Value),
                   StoryPoints = Convert.ToInt32(w.Fields["Story Points"].Value),
                   DoneStatus = w.Fields["Done Status"].Value.ToString(),
                   StoryOwner = w.Fields["Story Owner"].Value.ToString(),
                   Assignedto = w.Fields["Assigned To"].Value.ToString(),
                   StoryAuthor = w.Fields["Story Author"].Value.ToString(),
                   IterationPath = w.IterationPath
               }).ToList();
            var taskbugsworkitem =
             (from w in workItemcollectionList where (w.Type.Name == "Task" || w.Type.Name == "Bug") && (w.WorkItemLinks.Count > 0)   select new {
                 Id = w.Id,
                 Name = w.Title,
                 Type = w.Type.Name,
                 Storyid =  w.WorkItemLinks[0].TargetId,
                 status = w.State,
                 IterationPath = w.IterationPath,
                 Assignedto = w.Fields["Assigned To"].Value.ToString(),
                 priorty = Convert.ToInt32(w.Fields["Priority"].Value),
                 effort = Convert.ToInt32(w.Fields["effort"].Value),
                 Completed = (w.Type.Name== "Task") ? Convert.ToInt32(w.Fields["Completed"].Value):0
             }) .ToList();

A: You can use Task to make also two queries parallel.
Task<ResultClass1> t1 = Task<ResultClass1>.Run(() =>
    {
        var productbacklogworkitem =
        (from w in workItemcollectionList
         where w.Type.Name == "Product Backlog Item"
         select new ResultClass1
        {
            Id = w.Id,
            Name = w.Title,
            FID = (w.WorkItemLinks.Count > 0) ? ((w.WorkItemLinks[0].LinkTypeEnd.Name.ToString() != "Child") ? w.WorkItemLinks[0].TargetId : 0) : 0,
            Type = w.Type.Name,
            State = w.State,
            priorty = Convert.ToInt32(w.Fields["Priority"].Value),
            Size = Convert.ToInt32(w.Fields["Effort"].Value),
            StoryPoints = Convert.ToInt32(w.Fields["Story Points"].Value),
            DoneStatus = w.Fields["Done Status"].Value.ToString(),
            StoryOwner = w.Fields["Story Owner"].Value.ToString(),
            Assignedto = w.Fields["Assigned To"].Value.ToString(),
            StoryAuthor = w.Fields["Story Author"].Value.ToString(),
            IterationPath = w.IterationPath
        }).ToList();

        return ResultClass1;
    });

Task<ResultClass2> t2 = Task<ResultClass2>.Run(() =>
    {
        var taskbugsworkitem =
            (from w in workItemcollectionList
            where (w.Type.Name == "Task" || w.Type.Name == "Bug") && (w.WorkItemLinks.Count > 0)
             select new ResultClass2
            {
                Id = w.Id,
                Name = w.Title,
                Type = w.Type.Name,
                Storyid = w.WorkItemLinks[0].TargetId,
                status = w.State,
                IterationPath = w.IterationPath,
                Assignedto = w.Fields["Assigned To"].Value.ToString(),
                priorty = Convert.ToInt32(w.Fields["Priority"].Value),
                effort = Convert.ToInt32(w.Fields["effort"].Value),
                Completed = (w.Type.Name == "Task") ? Convert.ToInt32(w.Fields["Completed"].Value) : 0
            }).ToList();

        return taskbugsworkitem;
    });

Task.WaitAll(t1, t2);

// get results from these
t1.Result;
t2.Result;

A: You can try PLINQ, using AsParallel() on entity
var productbacklogworkitem =
               (from w in workItemcollectionList.AsParallel() where w.Type.Name == "Product Backlog Item" select new {
                   Id = w.Id,
                   Name = w.Title,
                   FID = (w.WorkItemLinks.Count > 0) ? ((w.WorkItemLinks[0].LinkTypeEnd.Name.ToString() != "Child") ? w.WorkItemLinks[0].TargetId : 0) : 0,
                   Type = w.Type.Name,
                   State =w.State,
                   priorty = Convert.ToInt32(w.Fields["Priority"].Value),
                   Size = Convert.ToInt32(w.Fields["Effort"].Value),
                   StoryPoints = Convert.ToInt32(w.Fields["Story Points"].Value),
                   DoneStatus = w.Fields["Done Status"].Value.ToString(),
                   StoryOwner = w.Fields["Story Owner"].Value.ToString(),
                   Assignedto = w.Fields["Assigned To"].Value.ToString(),
                   StoryAuthor = w.Fields["Story Author"].Value.ToString(),
                   IterationPath = w.IterationPath
               }).ToList();
            var taskbugsworkitem =
             (from w in workItemcollectionList.AsParallel() where (w.Type.Name == "Task" || w.Type.Name == "Bug") && (w.WorkItemLinks.Count > 0)   select new {
                 Id = w.Id,
                 Name = w.Title,
                 Type = w.Type.Name,
                 Storyid =  w.WorkItemLinks[0].TargetId,
                 status = w.State,
                 IterationPath = w.IterationPath,
                 Assignedto = w.Fields["Assigned To"].Value.ToString(),
                 priorty = Convert.ToInt32(w.Fields["Priority"].Value),
                 effort = Convert.ToInt32(w.Fields["effort"].Value),
                 Completed = (w.Type.Name== "Task") ? Convert.ToInt32(w.Fields["Completed"].Value):0
             }) .ToList();

For more info see: https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/introduction-to-plinq


text:
Q: Plotting non nummerical data from csv file using pgfplots so I'm trying to plot a csv file using pgfplots. The csv file looks like this but with more data:

Here is the download link for the csv: https://datawrapper.dwcdn.net/NDCZf/4/
I tried using the code from this post pgfplot: plot non-numerical data from CSV file . But I end up with something like this:

Here is the code:

\documentclass[ngerman]{scrbook}
\usepackage[utf8]{inputenc}

\input{../shared/twp-cfg}

\begin{document}

\pgfplotstableread[col sep=comma]{../shared/data.csv}\datatable
\begin{tikzpicture}
    \begin{axis}[
        ybar,
        xtick=data,
        xticklabels from table={\datatable}{X},
        xticklabel style={rotate=90,anchor=base,yshift=0.82cm},
    ]
    \addplot table [col sep=comma, x expr=\coordindex, y=Terawatt-Hours(TWh)] {../shared/data.csv};
    \end{axis}
\end{tikzpicture}

\end{document}

Is there a way to fix this and make the plot wider?
I'm new to LaTeX, so any help would be welcome. Thanks.

A: This example will help you get started.

\documentclass[12pt,a4paper]{article}

 \usepackage{tikz}
 \usepackage{pgfplots}
 \pgfplotsset{width=10cm,compat=1.9}
 \usetikzlibrary{dateplot}

\begin{filecontents*}[overwrite]{TRW.dat}
        date,  TRW
    2010-11-01, 0.2
    2010-12-01, 1
    2011-01-01, 2
    2011-02-01, 5
    2011-03-01, 9
    2011-04-01, 15
    2011-05-01, 9
    2011-06-01, 10
    2011-07-01, 10.5
    2011-08-01, 14
\end{filecontents*}

\begin{document}

    \begin{tikzpicture}
    \begin{axis}[
        date coordinates in=x,
        ybar,
        xtick=data,
        xticklabel style= {rotate=90,anchor=near xticklabel},
        xticklabel=\month --\year,
        title={Energy Consumption},
        xlabel={Date},
        ylabel={Monthly, in terawatt-hours (TWh)},
        ]
        \addplot table[col sep=comma,x=date,y=TRW] {TRW.dat};
    \end{axis}
\end{tikzpicture}

\end{document}


text:
Q: Why do big sites use 'bad practices'? I often see articles, posts and comments something like:

*

*globals are bad in javascript

*script tags should be at bottom of page

*CSS should be in external files and at the top of page

*scripts should be in external files, not plain script-tags.

*etc.

I've looked up the HTML source of some big sites and have noticed that they have a lot of plain javascript and CSS inside HTML markup. JavaScript and HTML are note always obfuscated, and so on.

A: Just because a site is big makes no guarantees about the quality of the code.
Have you ever viewed the source of Google's page? Is it pretty? No. Does it work? Yes!

A: Some possible reasons:

*

*Some Web code simply isn't very big or complicated and it really makes no difference in maintainability whether it follows best practices or not, and it works fine the way it is.

*Code is often written by inexperienced programmers, even on big, popular sites, and is never improved because it works fine the way it is.

*Best practices change from time to time and it's seen as wasteful to spend time redoing your code just to adhere to the latest, when it works fine the way it is.

*Adding new features is deemed more important than cleaning up old code, especially when, again, the old code works fine the way it is.

You may sense a recurring theme here. Rarely do programmers feel the need to fix what isn't broken.
Edit: If I were writing this now, more than two years later, I'd reword that final sentence to say "Rarely does management feel the need to fix what isn't broken." Most programmers love to revamp inelegant things, to the extent that they must sometimes be restrained by management in order to ship a product. I'd also throw in a mention of the concept of technical debt.

A: There are quite a few separate issues here.

*

*What you see when you "view source" is not usually what they develop with. It's usually a compressed / optimised form generated from "source" code.

*Claims about what is "best practice" are necessarily generic, and don't apply to all scenarios (especially if you're a big site and need specialised optimisation). These guidelines should be considered individually for each project.

*Best practice, or even clean code, doesn't directly translate to return on investment. It may be nice to have consistent naming schemes, but is it worth the time developing and enforcing the scheme across 100s of developers?

*Laziness, incompetence, or Friday nights.


text:
Q: How to create .bat file that will delete one txt file from folder and rename other? I need .bat file that will be capable to delete one txt file called 0.txt from folder and after deletion it will pick up next txt file (with random name) from same folder and rename it to 0.txt.
And again when i start the .bat file it will delete first the 0.txt and chose another txt file from folder and rename it to 0.txt
I got from one dude this
@echo off
if exist 0.txt del 0.txt
dir /b *.txt > %temp%\~txt.tmp
for /f "delims=" %%a in (%temp%\~txt.tmp) do set file=%%a & goto RenOne
:RenOne
ren "%file%" 0.txt
del %temp%\~txt.tmp
exit /b

but after the file is deleted the new 0.txt is not created (no file is renamed)

A: This is untested:
@echo off
if exist "0.txt" del "0.txt"
for %%a in (*.txt) do set "file=%%a"
ren "%file%" "0.txt"


text:
Q: laravel DB insert silent error when insert array key is named wrong When inserting [[..., 'wrong_key_name'=> value,...],...] as part of a larger array I seem to get nothing.... no error, no insert. This is the call I am using.
 DB::connection($dbc)->table($table)->insert($array);

Anybody else see this? Obviously I fix it by having the right name.