text:
Q: query without loop I want to query from the db records for a single post (title, body, date)
For example I have my query..
$query = 'SELECT * FROM posts WHERE id=$post_id';
From that query how can I echo the title for instance without a while or foreach loop?

A: You can just call mysql_fetch_assoc() (or any similar function) one. Like this:
$sql = "SELECT * FROM table";
$row = mysql_fetch_assoc( mysql_query($sql) );
echo $row['title'];

This is the easiest and most readable way to do this with the MySQL functions.

A: You can use mysql_result:
$sql = 'SELECT * FROM posts WHERE id=$post_id';
$query = mysql_query($sql);
echo mysql_result($query, 0, 'title');

This will echo the field titlefor the first(0) row.

A: You can use this code for select query without using while loop:
$conn is an database connection
$sql = "SELECT * FROM teacher_details";
$row = mysqli_fetch_assoc($conn->query($sql) );
$teacher_name = $row['teacher_name'];

A: When you use functions like mysql_fetch_array, you're not obligated to iterate. Even, when you do it, you're just getting the result of the next row available, until it returns null:
$query = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($query)) {
    var_dump($row);
}

So, doing this for each row in the query is technically the same:
$query = mysql_query("SELECT * FROM table");

$row = mysql_fetch_array($query)
var_dump($row);
// Array()
$row = mysql_fetch_array($query)
var_dump($row);
// Array()
$row = mysql_fetch_array($query)
var_dump($row);
// null < the "while" statment will stop here

Then, you can call mysql_fetch_array once and that's it.
Good luck!


text:
Q: PreAuthenticatedAuthenticationProvider UsernameNotFound exception returns 401 instead of denied page I use spring 4.1.6.RELEASE and spring-security 4.0.1.RELEASE.
There is RequestHeaderAuthenticationFilter and PreAuthenticatedAuthenticationProvider. I want my application to show 'denied' page, if user service throws UsernameNotFoundException.
Actually, application shows basic HTTP authorization form (simple browser popup for credentials) and provides 401 response if it cancelled.
Here is my configuration:
<s:http auto-config="true" use-expressions="true">
    <s:intercept-url pattern="/report/**" access="hasRole('ROLE_USER')"/>
    <s:csrf disabled="true"/>
    <s:custom-filter ref="preAuthFilter" position="PRE_AUTH_FILTER"/>
    <s:form-login
            authentication-failure-url="/denied.jsp"/>
</s:http>

<b:bean id="preAuthFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
    <b:property name="principalRequestHeader" value="REMOTE_USER"/>
    <b:property name="authenticationManager" ref="authManager"/>
</b:bean>

<s:authentication-manager id="authManager">
    <s:authentication-provider user-service-ref="userDetailsService"/>
</s:authentication-manager>

<b:bean id="userDetailsService" class="com.db.dump.tool.security.UserDetailsServiceImpl"/>

Class UserDetailsServiceImpl just checks user with DB and throws UsernameNotFoundException if user is not found. Maybe here is a problem?
Please, advise.
Thanks in advance,
Alex

A: This behaviour is due to the ExceptionTranslationFilter translating the final exception as:

Access is denied (user is anonymous); redirecting to authentication entry point

User is anonymous because your UserDetailsService threw exception. You are getting 401 response because it has been implemented that way in the BasicAuthenticationEntryPoint which acts as authentication entry point in case of a non XMLHttpRequest (your case) with anonymous user principal.
In case you wish to show an access denied page instead (not giving an anonymous user chance to authenticate), you need to plug in your own AuthenticationEntryPoint using the entry-point-ref attribute on the http element (and then may be also let the AccessDeniedHandler come into picture). The resulting implmentation would look something like this:
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;

public class CustomAuthEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(SC_FORBIDDEN); /* You can also call an access denied handler here and let it handle some meaningful exception that you pass into the handle method. */
    }
}

PS: Of course you'll need to configure your new authentication entry point as a spring bean before it starts working.

A: Solution which I found is to set no authorities for user and do not throw any exceptions. We have 403 error page in this case, which could be customized by access-denied-handler.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Validation in Jquery ajax form submission I am trying to validate user to enter a unique mobile number and email id.
It is checking and showing result mobile/email exist or not but if it exists still the form is submitting. Since I am new to jQuery validation I am not able to figure out how I should do it correctly nor can I find a perfect tutorial to do it in a right way.
Here is my code, I know lots of mistakes would be there and I apologize  for those small mistakes.
On my form I have given On blur function to check mobile number and email
From these two functions I am checking in database if exist or not
function check_availability() {
  //get the mobile number
  var main = $('#main').val();

  //use ajax to run the check
  $.post("tutor/check_mobile", {
      main: main
    },
    function(result) {
      //if the result is 1
      if (result == 1) {
        //show that the username is available
        $('#mobile_availability_result').html(' ');
      } else {
        //show that the username is NOT available
        $('#mobile_availability_result').html('Mobile Number already registered ');
      }
    });

}

function email_availability() {
    //get the email

    var main = $('#email_tuitor').val();
    //$email = urldecode("[email]")

    //use ajax to run the check
    $.post("<?php echo base_url(); ?>tutor/check_email", {
        main: main
      },
      function(result) {
        //if the result is 1
        if (result == 1) {
          //show that the username is available
          $('#email_availability_result').html(' ');
        } else {
          //show that the username is NOT available
          $('#email_availability_result').html('Email already registered ');
        }
      });
  }

This is the jquery ajax form submission is it possible to do every validation on blur ?
$(document).ready(function() {
  $('.error').hide();
  $("#next_tutor").click(function() {
    $('.error').hide();
    var main = $("#main").val();
    if (main == "") {
      $("label#main_error").show();
      $("input#main").focus();
      return false;
    }
    var name = $("#name").val();
    if (name == "") {
      $("label#name_error").show();
      $("input#name").focus();
      return false;
    }
    var email_tuitor = $("#email_tuitor").val();
    if (email_tuitor == "") {
      $("label#email_tuitor_error").show();
      $("input#email_tuitor").focus();
      return false;
    }
    var password_tuitor = $("#password_tuitor").val();
    if (password_tuitor == "") {
      $("label#password_tuitor_error").show();
      $("input#password_tuitor").focus();
      return false;
    }

    var tutor = $("#tutor").val();
    //  Returns successful data submission message when the entered information is stored in database.
    var dataString = 'main=' + main + '&name=' + name + '&email_tuitor=' + email_tuitor + '&password_tuitor=' + password_tuitor + '&tutor=' + tutor;
    // AJAX Code To Submit Form.
    //alert(dataString);
    //die;
    $.ajax({
      type: "POST",
      url: "<?php echo base_url(); ?>tutor/tutor_sub_ses",
      data: dataString,
      cache: false,
      success: function(result) {
        //alert(result);
        $("#abc").hide();
        $("#tutorreg2").slideToggle("slow").show();
      }
    });
    return false;
  });
});

<form class="form-horizontal" action="#">

Tutor Registration

      <input type="text" value="tutor" style="display:none" id="tutor">
      <input type="text" class="form-control" id="name" placeholder="Name">
      This Field Is Required

      <input type="text" class="form-control phone" id="main" placeholder="Mobile Number *This will be the key to your account*" onBlur="check_availability()">

      This Field Is Required

      <input type="text" class="form-control" id="email_tuitor" placeholder="Email" onBlur="email_availability()">

      This Field Is Required

      <input type="password" class="form-control" id="password_tuitor" placeholder="Password">
      This Field Is Required

      <button type="submit" class="btn btn-warning" id="next_tutor">Next</button>

</form>

A: The quick way will be to use a global switch to enable sending the form. I would to it this way:

*

*Create global variables with default values
var mobileApproved = false, emailApproved = false;

*Check status and prevent sending if value is false in click handler
$(document).ready(function() {

    ...

    $("#next_tutor").click(function() {

        if (!mobileApproved || !emailApproved) {
            return false;
        }
        ...
    })

    ...

})

*In your check functions manage approved status after each ajax response
...
$.post("tutor/check_mobile", {
    main: main
},
function(result) {
    //if the result is 1
    if (result == 1) {
        //show that the username is available
        $('#mobile_availability_result').html(' ');
        mobileApproved = true;
    } else {
        //show that the username is NOT available
        $('#mobile_availability_result').html('Mobile Number already registered ');
        mobileApproved = false;
    }
});

...
$.post("<?php echo base_url(); ?>tutor/check_email", {
    main: main
},
function(result) {
    //if the result is 1
    if (result == 1) {
        //show that the username is available
        $('#email_availability_result').html(' ');
        emailApproved = true;
    } else {
        //show that the username is NOT available
        $('#email_availability_result').html('Email already registered ');
        emailApproved = false;
    }
});

A: In order to stop the form from submission. You can keep a flag lets say formvalid.
Keep formValid as false initially. Based on your blur function, make it true if email and mobile are available else keep it false. In your form submission, put an if condition to check , if formvalid is true or not. If true then process with form submission else stop and throw error.


text:
Q: How can I find element in list that only half-matches DateTime object in Flutter/Dart? I have a list that contains DateTime like so:
[2021-03-05 00:00:00.000, 2021-03-12 08:00:00.000Z, 2021-03-19 08:00:00.000Z, 2021-03-26 08:00:00.000Z, 2021-04-02 08:00:00.000Z, 2021-04-09 08:00:00.000Z, 2021-04-16 08:00:00.000Z, 2021-04-23 08:00:00.000Z, 2021-04-30 08:00:00.000Z, 2021-05-07 08:00:00.000Z, 2021-05-14 08:00:00.000Z, 2021-05-21 08:00:00.000Z, 2021-05-28 08:00:00.000Z, 2021-06-04 08:00:00.000Z, 2021-06-11 08:00:00.000Z]

I need the full DateTime list items, however I want to be able to query for "half-matches" like so:
if (dates.contains(DateTime(2021, 3, 12))) {
    print('Afermative');
  } else {
    print('Nope');
  }

Currently prints nope, obviously.
Is there a simple way of querying for such "half-matches" like above?

A: There is no such built-in method. You should create your own.

*

*Define a method that returns if two DateTime objects have the same date:

bool areSameDay(DateTime one, DateTime two) {
  return one.day == two.day && one.month == two.month && one.year == two.year;
}

*Call firstWhere on the list:

final targetDate = DateTime(2021, 3, 12);

try {
  final dateTime = dates.firstWhere((date) => areSameDay(date, targetDate));
  // Found
} catch (_) {
  // Not found
}

Also note that contains() would not do even for complete matches. This is because it compares references to DateTime objects and not their contents. To compare DateTime object contents, use dateTime.compareTo(DateTime other)

A: You'll have to format your date.
You can look up the options of the format of the dates here - Link
var newFormat = DateFormat("yyyy-MM-dd");

if (dates.singleWhere(
        (element) =>
            element.contains(newFormat.format(DateTime(2021, 3, 12))),
        orElse: () => null) !=
    null) {
  print('Afermative');
} else {
  print('Nope');
}

A: Try to use Jiffy package, it supports date querying. See below
var jiffy = Jiffy(DateTime(2021, 3, 12));

dates.forEach((date) {
    var isSame = jiffy.isSame(date);
    if (isSame) {
      print('Afermative');
    } else {
      print('Nope');
    }
  });


text:
Q: Can somebody help me on a simple chain rule differentiation problem [As level] It's my first time using this forums so please let me know if I'm doing anything wrong and pardon for my stupid question.
So I believe that when you differentiate $2$ functions e.g $y = f(g(x))$, you would differentiate the inner one first, then the outer one with the inner function acting as $x$ like this:
$$y = g'(x) \cdot f'(g(x))$$
However, I'm struggling to see where the definition of a function is.
Let me illustrate:
So in my book it says.
$$y = 3\sin(2x)$$
Is this the same as f(g(y(x)))
Where
$$f(x) = 3x$$
$$g(x) = \sin{x}$$
$$y(x) = 2x$$
In this case, It would differentiate to obtain:
$$y'(x) \cdot g'(y(x)) \cdot f'(g(y(x)))$$
which would be $2 \cdot \cos{2x} \cdot 3(\sin{2x})$
However, this is wrong. The answer is $6\cos{2x}$
Could somebody please explain why or where I went wrong.
It seems like that $f(x)$ is not considered as a function. But then I think about $f(x) = 3x$  and it seems to me to be like a function by itself (which is take a number and multiply it by $3$) Anyways, I'm not very sure as to how to approach this and make sure I don't get this wrong again
Thanks for helping :)

A: $$f(x)=3x$$
$$g(x)=\sin{x}$$
$$h(x)=2x$$
Composing:
$$f(g(h(x))=3\sin{2x}$$
$$(f(g(h(x)))'=f'(g(h(x))(g(h(x)))'=f'(g(h(x))g'(h(x))h'(x)$$
$$f'(g(h(x))=3$$
$$g'(h(x))=\cos{2x}$$
$$h'(x)=2$$
Then:
$$(f(g(h(x)))'=6\cos{2x}$$


text:
Q: IIS doesn't process other requests on awaiting task At below, i do simple await call via ajax request on the page and  i try to visit other pages or i try to visit page again on another tab but i am not able to visit other pages until Delay action complete.
I tested it on my local IIS Express and on server with full IIS versions. Why my website is not responsive while waiting on await call?
public async Task<ActionResult> Delay()
{
    await Task.Delay(TimeSpan.FromSeconds(30));
    return Content("success");
}

A: There is only one possible reason about the issue. ASP.NET doesn't process requests from same user concurrently if session is used. Access to session locks all other requests of the same user and concurrent requests are handled one by one.
Other similar questions
ASP.NET MVC: how to prevent a session lock?
I just discovered why all ASP.Net websites are slow


text:
Q: Bash script syntax I want to create a .sh script which will

*

*execute a python file called match_scraper.py,

*update a psql db as shown,

*call a scrapy spider to execute.

When I create the .sh script how do I call those commands properly? This is what I have come up with:
#!/bin/bash

~Documents/dota2/dotaapi2/ python match_scraper.py

psql dota2apidb
update games set online=1 where online is null;

~Documents/dota2/gosugamers/gosugamers/spiders/ scrapy crawl dota

A: First you need to make sure each line/part of your bash script work in a shell (outside of a script). I cannot tell if yours will so you'll have to check that yourself.
And to execute a python script you need python BEFORE the path to the script
Also:

*

*~ is a shortcut to the home directory of the current user

*~asdf is a shortcut to the home directory for the asdf user

*~/Documents is the path to the Documents folder in the home directory of the current user

*~Documents is looking for the home directory of the Directory user which is invalid unless you have a user called Directory

As @muru pointed out, you probably meant ~/Documents. So your bash script would probably look something like this
#!/bin/bash

python ~/Documents/dota2/dotaapi2/match_scraper.py

psql dota2apidb
update games set online=1 where online is null;

python ~/Documents/dota2/gosugamers/gosugamers/spiders/scrapy crawl dota

Again, I do not know if this will work since I have no clue if each line will work. For example, does python ~/Documents/dota2/gosugamers/gosugamers/spiders/scrapy crawl dota actually work when you run it on the command line?
And I do not know psql but I suspect you need to pass it some command line paramater to get it to run that update... command?


text:
Q: What is the limit on dropped candies? I'm playing Candy Box 2 and on the Candy Box home screen you can drop 10 candies, I'm already in the room with huge candies and all the dude is doing is eating them, is there something after those candies that he is eating or does he just eat them no matter how many you drop?

A: You've hit the end. It's just a loop of candy eating after that. You can keep throwing as many as you want though!
(The loop starts at 1770.)


text:
Q: Calculate price per square metre I'm selling rolls that come in two widths. The user can choose which width is required however the user can also type in the length in metres. Then a price is calculated.
For instance if the price is £5 square metre, and the user chooses the 4m option and types in a length of 4.5m then the total cost should be 5 x 4 x 4.5
Is there an existing extension, is this simple to program?

A: I haven't used or tested this, but you can give it a try, or at least investigate further:  http://www.fmeextensions.com/magento-length-area-volume-pricing-calculator.html. It claims it does what you need (price per surface) and more: price per volume, support for different unis of measure....
This one also claims the same: http://www.micosolutions.com/advanced-variation-pricing.
I haven't used any of these and I'm in no way associated with the developers. I just found these on a quick search.

A: I have used both of the extensions mentioned by @Marius, and I can say that they might meet your needs. In my case, they were not robust enough for us to use.
I ended up having to write my own solution, here's the basic flow:

*

*Created a custom product type

*Custom product type uses it's own template for the product_type_data block where I can include my own form fields for the user to enter dimensions.

*Custom product type main model class has a setPrice method where I can use my own calculations to determine the price

*I have an observer on the sales_quote_add_item event where I can take the request and pass it along to the setPrice method.

*The custom product type's type model uses _prepareProduct to add the user's choices as custom options added to the additional_options option.

This should be enough to get you started. Depending on your requirements, there might be additional things to code so that, for example, a user is able to edit their choices when clicking the "edit" button in the cart.


text:
Q: cameraOverlayView to crop the result in UIImagePickerController When I use UIImagePickerController with cameraOverlayView, can I get the only a selective region from my overlay view?
http://tinyurl.com/2fqy9nq

A: *

*Add an UIImageView as child to your cameraOverlayView.

*Create a black PNG image size 320x480. Cut a rectangle in the middle to produce a hole (transparent pixels).

*Assign the PNG image to the UIImageView.

Alternatively you could overwrite your cameraOverlayView's - (void)drawRect:(CGRect)rect like this (untested out of my head):
// Request draw context
CGContextRef context = UIGraphicsGetCurrentContext();

// Draw background
CGContextSetRGBFillColor(context, 0.0f, 0.0f, 0.0f, 1.0f);
CGContextFillRect(context, rect);

// Cut hole
CGContextSetBlendMode(context, kCGBlendModeClear);
CGContextFillRect(context, CGRectMake(40, 40, 100, 100);

I have done something similar in my Faces app (http://faces.pixelshed.net/). Feel free to write a comment if one of the steps seems unclear.


text:
Q: Call to a member function item() on null MX/Modules.php Line Number: 8 ckeditor and kcfinder I have trouble about ckeditor and kcfinder in codeigniter, i used HMVC from
wiredesignz
codeigniter-modular-extensions-hmvc, when i want to browse images error like this
Fatal error: Call to a member function item() on null in C:\xampp\htdocs\mypro\abbas_eterna\application\third_party\MX\Modules.php on line 8

A PHP Error was encountered
Severity: Error
Message: Call to a member function item() on null
Filename: MX/Modules.php
Line Number: 8
Backtrace:
When i do not use HMVC to access ckeditor and browse image from kcfinder is good, and when use HMVC is trouble. I already search reference in this stackoverflow and google but not same trouble with me. i already declare in application/config.php
    $config['modules_locations'] = array(
    APPPATH.'modules/' => '../modules/',
);

and configurasi file index in root folder
$system_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'system';
$application_folder = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'application';

and i use session that i setting in folder asset/kcfinder/conf/config.php
ob_start();
include('./../../index.php');
ob_end_clean();
$CI =& get_instance();
$CI->load->driver('session');
if(@$_SESSION['upload_image_file_manager'] == TRUE){
    $codeigniterAuth = false;
} else {
    $codeigniterAuth = true;
}

A: <?php (defined('BASEPATH')) OR exit('No direct script access allowed');

(defined('EXT')) OR define('EXT', '.php');

global $CFG;

/* get module locations from config settings or use the default module location and offset */
is_array(Modules::$locations = $CFG->item('modules_locations')) OR Modules::$locations = array(
    APPPATH.'modules/' => '../modules/',
);

/* PHP5 spl_autoload */
spl_autoload_register('Modules::autoload');

A: That error appeared cause there is the global var, at the beginning, this file
You can do this
Modules::$locations = array(
    APPPATH.'modules/' => '../modules/',
);

instead
is_array(Modules::$locations = $CFG->item('modules_locations')) OR
Modules::$locations = array(
    APPPATH.'modules/' => '../modules/',
);


text:
Q: How to copy text field entity ursina? I created a text entity that you can copy using the TextField version of the text entity in ursina .
my code was:
test = TextField(max_lines=100, scale=3, register_mouse_input = False, text='1234')

The error :
NameError: name 'selectedText' is not defined. Did you mean: 'selected_text'?

any idea why this is happining?

A: Firstly, the register_mouse_input parameter should be True, now the Actual fault is in text_field.py, You can find it in the ursina/prefabs folder, the get_selected function sould return selected_text not selectedText, the function's code should be:
def get_selected(self):
    if not self.selection or self.selection[0] == self.selection[1]:
        return None

    sel = self._ordered_selection()
    start_y = int(sel[0][1])
    end_y = int(sel[1][1])
    lines = self.text.split('\n')

    selected_text = ''
    # selected_text = lines[start_y][]

    for y in range(start_y, end_y+1):
        if y > start_y:
            selected_text += '\n'
        selected_text += lines[y][(int(sel[0][0]) if y == start_y else 0) : (int(sel[1][0]) if y == end_y else len(lines[y])) ]

    return selected_text

I have submitted a pull request on GitHub here, so that they can fix it.


text:
Q: How to make IntersectionObserver work with transform translate animations? I want to create an animation for an element with following properties:

*

*it animates the element when it enters the viewport

*if the element left the viewport and then enters it again it should be animated again

*depending on the scroll direction/intersected side (from top or bottom) the animation should be different

For this purpose I use an IntersectionObserver and I came close to the desired outcome.
The only problem I am facing is, when I translate the element in the scroll direction (which is in this case transform: translateY) during the animation. This will cause the IntersectionObserver to trigger multiple or even infinite times.

function isIntersectingFromTop(entry){
  return entry.boundingClientRect.bottom != entry.intersectionRect.bottom;
}

function isIntersectingFromBottom(entry){
  return entry.boundingClientRect.top != entry.intersectionRect.top;
}

var count = 0;

function incrementCounter(entry){
  document.querySelector(".counter").textContent += "intersectionRation (" + count + "): " + entry.intersectionRatio + "\n";
  count++;
}

let observer = new IntersectionObserver(
function (entries, observer) {
  entries.forEach(function(entry){
    incrementCounter(entry)
    if (entry.isIntersecting) {
       if(isIntersectingFromTop(entry)){
         entry.target.classList.add("animated--up-in");
       } else if(isIntersectingFromBottom(entry)) {
         entry.target.classList.add("animated--down-in")
       }
    } else {
      /** element is not in viewport anymore
        * this will be triggered right after the animation starts
        * since the translate is moving the elment out of the view
        * which is causing a new intersection (isIntersecting = false)
        */
      entry.target.classList.remove("animated--up-in");
      entry.target.classList.remove("animated--down-in");
    }
  });
});

observer.observe(document.querySelector(".to-animate"));
.container {
  height: 1000px;
  width: 100%;
}

.box{
  position: static;
  width: 100px;
  height: 100px;
  background: red;
  margin-top: 10px;
}

.to-animate{
  background: blue;
  opacity: 0;
}

.animated--up-in {
  animation: animateUpIn 1.5s forwards ease;
}

.animated--down-in {
  animation: animateDownIn 1.5s forwards ease;
}

@keyframes animateUpIn {
  from {
    transform: translateY(100px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes animateDownIn {
  from {
    transform: translateY(-100px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.counter {
  position: fixed;
  top: 10%;
  left: 30%;
  color: black;
  height: 80%;
  width: 50%;
  overflow-y: auto;
  padding: 10px;
}

Question
How can I "tell" the IntersectionObserver to ignore translated position and just use the initial/original position to calculate intersections (with no extra element)? Is this even possible?

A: I think that in this case you need to track the position on the screen of the stationary containers in which the animated elements will be nested.

A: I have a similar problem with translateX on mobile device
Animation has translateX(-100% or 100%);
threshold: 0.1
Block has width 100%, but it should work with a visibility of 10% (threshold 0.1), therefore it cannot work, the animation switches back and forth, endlessly.
If it's 90%, then it will work


text:
Q: Intead of update & after update on same table not fired? I have two trigger one is Instead of update and other is after update on same table for same task but after updation only Instead of trigger is fired while if i have two after trigger then both are fired on updation. what's reason for that happened?
create trigger tr_tmp_instead on emp
 Instead of update
 as
 begin
 declare @name varchar(50),@message varchar(200)='Updated name Entered Successfully';
 select @name=d.name from inserted d;
 insert into tmp_Instead values(getdate(),@message,@name)
 Print 'Trigger Fired, Updated name Entered Successfully Into tmp_Instead Table..'

 end

create trigger tr_tmp on emp
 after update
 as
 begin
 declare @name varchar(50),@message varchar(200)='Updated name Entered Successfully';
 select @name=d.name from inserted d;
 insert into tmp values(getdate(),@message,@name)
 Print 'Trigger Fired, Updated name Entered Successfully Into tmp Table..'
 end

A: An INSTEAD OF trigger overrides the default action it's defined on.
When you call an UPDATE on emp, no actual update happens to emp and AFTER UPDATE ON emp never fires.


text:
Q: Setting the 'Expires' cookie with Google Appengine I am taking Udacity's Web Development course with Google Appengine and Python.
I'd like to set a cookie to expire, for example, 29 days from the time it is set. How do I achieve this?
I am assuming it is something like this:
def set_cookie(expire):
    self.response.headers.add_header(
        'Set-Cookie',
        'Expires=%s; Path=/' % (expire_date))

What format is the 'Expires' value in? How can I set its expiry to be + 29 days (or minutes, hours, weeks, months, etc.)?

A: You dont have to add the Set-Cookie header manually, instead you can do:
import datetime

def yourFunction(...):
    expireTime = datetime.datetime.now()  #Check the docs, about adding 29 days, etc.
    self.response.set_cookie('name', 'value', expires=expireTime, path='/', domain='example.com')


text:
Q: binding location on map in windows phone 8.1 I'm trying to bind images on locations on map in windows phone 8.1:
<Maps:MapControl x:Name="RestoMap" MapServiceToken="" Height="520" Margin="0,50,0,0" Width="380" ZoomLevel="8">
        <Maps:MapItemsControl x:Name="MapIcons" >
            <Maps:MapItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Background="DarkSlateBlue" Width="170" Height="170">
                        <Image Margin="0,0,0,0" HorizontalAlignment="Center" Source="{Binding picture}" Width="150" Height="100" Maps:MapControl.Location="{Binding location}"/>
                    </StackPanel>
                </DataTemplate>
            </Maps:MapItemsControl.ItemTemplate>
        </Maps:MapItemsControl>
    </Maps:MapControl>

Code: the image didn't appear on map any help
{
double latitude = ....;
double longitude = ....;
Location location = new Location();
location.Latitude = latitude;
location.Longitude = longitude;
locations.Add(location);
}
MapIcons.ItemsSource = this.locations;

A: The binding is wrong.
According to your XAML, the class should have these two properties, one is picture to show the image, and the other is location to set the image location on the map. I rename them as MapPicture and MapLocation to follow the CamelCase naming convention.
The class:
class MapIcon
{
    public ImageSource MapPicture { get; set;}
    public Location MapLocation { get; set; }
}

and the updated XAML-just rename the 2 properties:
<DataTemplate>
    <StackPanel Background="DarkSlateBlue" Width="170" Height="170">
        <Image Margin="0,0,0,0" HorizontalAlignment="Center" Source="{Binding MapPicture}" Width="150" Height="100" Maps:MapControl.Location="{Binding MapLocation}"/>
    </StackPanel>
</DataTemplate>

And how you bind a collection of MapIcon's to the MapItemsControl.
ObservableCollection<MapIcon> icons = new ObservableCollection<MapIcon>();

private void ShowMapIcons()
{
    BitmapImage img = new BitmapImage(....);
    double latitude = ....;
    double longitude = ....;
    Location location = new Location();
    location.Latitude = latitude;
    location.Longitude = longitude;
    MapIcon icon = new MapIcon() { MapLocation = location,  ImageSource = img };

    icons.Add(icon);

    MapIcons.ItemsSource = icons;
}


text:
Q: How to add multiple icons to tree item in tree model This is my current Data function of Tree model
QVariant TreeModel::data(const QModelIndex &index, int role) const
{

    if (!index.isValid())
        return QVariant();

    TreeItem *item = getItem(index);
    if (item)
    {
        switch (role)
        {
            case Qt::DisplayRole: case Qt::EditRole:
                return QString::fromStdString(item->data().GetName());
                break;
            case Qt::DecorationRole:
            {
                Container *cont = item->GetContainer();
                if (cont->GetGeometry()->isValid())
                {
                    QString qstrIconName =  cont->GetGeometry()->GetType().c_str();
                    QString qstrIconPath = QCoreApplication::applicationDirPath();
                    QPixmap pixmap;
                    QIcon icon;
                    qstrIconPath = qstrIconPath + "/Icons/" + qstrIconName + ".png";
                    pixmap.load(qstrIconPath);
                    icon.addPixmap(pixmap, QIcon::Normal, QIcon::On);
                    return icon;
                }
                 // Function returns from here since we have returned the icon
                 // How can i add next icon to the same tree item

                int numberOfFunctions = cont->getNumberOfFunctions();
                if (numberOfFunctions > 0)
                {
                    QString qstrIconName = "FUNCTION";
                    QString qstrIconPath = QCoreApplication::applicationDirPath();
                    QPixmap pixmap;
                    QIcon icon;
                    qstrIconPath = qstrIconPath + "/Icons/" + qstrIconName + ".png";
                    pixmap.load(qstrIconPath);
                    icon.addPixmap(pixmap, QIcon::Normal, QIcon::On);
                    return icon;
                }
                break;
            }
        }
        return QVariant();
    }
}

//////////////////////////////////////////////////////////////////////////////////
I am able to set only icon how can i set multiple icons in the Tree Item.
I am able to set the either of the icons on the tree model but not the both icons.

A: I used a QStyledItemDelegate to acheive this and this is the paint function
void PixelDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option , const QModelIndex &index) const
{
    int offset = 0;
    int offsetIcon = 0;
    const QAbstractItemModel *model = index.model();
    const TreeModel *myModel = (TreeModel*)(model);
    TreeItem* item = myModel->getItem(index);
    Container* cont = item->GetContainer();
    if (option.state & QStyle::State_Selected)
            painter->fillRect(option.rect, option.palette.highlight());

    painter->save();
    painter->setRenderHint(QPainter::Antialiasing, true);
    painter->setPen(Qt::NoPen);
    painter->translate(option.rect.x(), option.rect.y());
    painter->scale(.4, .4);
    if (option.state & QStyle::State_Selected)
        painter->setBrush(option.palette.highlightedText());
    else
        painter->setBrush(option.palette.text());

    if (cont->GetGeometry()->GetType() != "NO_TYPE")
    {
        QString qstrIconName = cont->GetGeometry()->GetType().c_str();
        QString qstrIconPath = QCoreApplication::applicationDirPath();
        QPixmap pixmap;
        qstrIconPath = qstrIconPath + "/Icons/" + qstrIconName + ".png";
        pixmap.load(qstrIconPath);
        QImage image = pixmap.toImage();
        painter->drawImage(0, 6, image);
        offset += 20;
        offsetIcon += 50;
    }
    if (cont->getNumberOfFunctions() > 0)
    {
        QString qstrIconName = "FUNCTION";
        QString qstrIconPath = QCoreApplication::applicationDirPath();
        QPixmap pixmap;
        qstrIconPath = qstrIconPath + "/Icons/" + qstrIconName + ".png";
        pixmap.load(qstrIconPath);
        QImage image = pixmap.toImage();
        painter->drawImage(offsetIcon, 6, image);
        offset += 20;
        offsetIcon += 50;
    }
    if (cont->GetNumberOfAnimationChannels() > 0)
    {
        QString qstrIconName = "ANIMATION";
        QString qstrIconPath = QCoreApplication::applicationDirPath();
        QPixmap pixmap;
        qstrIconPath = qstrIconPath + "/Icons/" + qstrIconName + ".png";
        pixmap.load(qstrIconPath);
        QImage image = pixmap.toImage();
        painter->drawImage(offsetIcon, 6, image);
        offset += 20;
    }
    painter->restore();
    QStyleOptionViewItem newoption = option;
    newoption.rect.setX(option.rect.x() + offset + 3);
    newoption.rect.setY(option.rect.y());
    QStyledItemDelegate::paint(painter, newoption, index);
}


text:
Q: airwatch-sdk-plugin not recognised in ionic 3 app I've created a brand new blank ionic 3 app and run the command "npm i airwatch-sdk-plugin" and then "ionic cordova platform add android".
In app.components I have this code ...

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();

      window.plugins.airwatch.setSDKEventListener( function( event, error ) {
        if( event === "initSuccess" ) {
          alert( 'airwatch initialised' );
        }
      },
      (error) => {
        alert( 'airwatch error: ' + JSON.stringify( error ) );
      });

    });
  }
}

The editor Visual Studio Code on Windows 10 is reporting the plugins does not exist on type window. I can change this line to ...

(<any>window).plugins

to remove the editor error, but when I run the project with "ionic serve" the browser will report this error ...
TypeError: Cannot read property 'airwatch' of undefined
What am I doing wrong?

A: As per the installation guide, below command should be added before any other plugin is added to the app:
ionic cordova plugin add airwatch-sdk-plugin

As per the installation guide, the functions are available in the window.plugins.airwatch object. Hence you need to declare window variable as shown below:
declare var window: any;

Hope it will help you.


text:
Q: Postfix Multiple Sender bcc I am trying to configure postfix to send mails to multiple email address using sender_bcc, if I send caterpillar@domain.com it should send a bcc mail to xyz@domain.com as well as abc@gmail.com.
Example :
caterpillar@domain.com ----> xyz@domain.com,
caterpillar@domain.com ----> abc@gmail.com
how to configure it?

A: I have never actually configured postfix but just found this tutorial and I am not sure if it will help you... the last comment on the site shows using more than one forwarder by separating emails by a comma
Tutorial Link
This page use virtual_alias_maps instead *_bcc parameter as you proposed in question. So I was wondering if you could bcc to one email and then use postfix virtual to then forward to the addresses you require?
hope that helps


text:
Q: How to check if a Popen subprocess is still running on Linux - Python I do have a code that runs the same python script with different arguments at the same time in different Shell windows.
The following code do this, but I need do monitor if any subprocess created have finished its execution, and then stop all other subprocesses running, how can I do this monitoring on Linux?
I have tried to check the PID status, but it changes to 'zombie' after the terminal is opened

import multiprocessing
import subprocess
import psutil
import shlex

if __name__ == '__main__':

    arg_list = ["gnome-terminal -- python3 teste.py ./get_data/datasets/training_out.xlsx 140.10.61.1 0 2 102 4 OUTPUT 0 632 MEMORY 0 3885 1 0",
            "gnome-terminal -- python3 teste.py ./get_data/datasets/training_out2.xlsx 140.10.61.1 0 2 102 1 OUTPUT 0 272 MEMORY 0 3885 1 1",
            "gnome-terminal -- python3 teste.py ./get_data/datasets/training_in.xlsx 140.10.61.1 0 2 102 2 INPUT 0 632 MEMORY 0 3885 1 2",
            "gnome-terminal -- python3 teste.py ./get_data/datasets/training_in2.xlsx 140.10.61.1 0 2 102 2 INPUT 0 272 MEMORY 0 3885 1 3",
            "gnome-terminal -- python3 teste.py ./get_data/datasets/training_in3.xlsx 140.10.61.1 0 2 102 1 INPUT 0 274 MEMORY 0 3885 1 4"
            ]

    p1 = subprocess.Popen(shlex.split(arg_list[0]))
    psProcess1 = psutil.Process(pid=p1.pid)

    p2 = subprocess.Popen(shlex.split(arg_list[1]))
    psProcess2 = psutil.Process(pid=p2.pid)

    p3 = subprocess.Popen(shlex.split(arg_list[2]))
    psProcess3 = psutil.Process(pid=p3.pid)

    p4 = subprocess.Popen(shlex.split(arg_list[3]))
    psProcess4 = psutil.Process(pid=p4.pid)

    p5 = subprocess.Popen(shlex.split(arg_list[4]))
    psProcess5 = psutil.Process(pid=p5.pid)


text:
Q: temporarily disable mysql remote access I need to disble remote access during nightly mysql maintenance on Linux server so that no one can query the database during that time.  I can't do SERVICE MYSQL STOP because then I couldn't do what I needed to do (truncate and rebuild a couple tables).  Is there a way to turn off external access for a short time?
Thanks in advance.

A: Here is a great way without touching anything in the OS:
Step 1) Export all users to SQL file like this:

mysql -h localhost -u root
  -p rootpassword --skip-column-names -A -e"SELECT CONCAT('SHOW GRANTS FOR ''',user,'''@''',host,''';') FROM
  mysql.user WHERE user<>''" | mysql
  -hlocalhost -uroot -prootpassword --skip-column-names -A | sed 's/$/;/g' > /root/MySQLGrants.sql

Step 2) Disable all users except root@localhost
DELETE FROM mysql.user WHERE CONCAT(user,host) <> 'rootlocalhost';
FLUSH PRIVILEGES;

Step 3) Perform your maintenance
Step 4) Reload the Grants
mysql -h localhost -u root -p rootpassword < /root/MySQLGrants.sql

Give this a Try !!!!
PS
service mysql restart --skip-networking
would still be the simplest and fastest way plus logging off all connections before maintenance
just run service mysql restart after your maintenance

A: Since 5.7.5 there's an "official way" to deal with that:

MySQL Server now supports an "offline mode" with these
  characteristics:
Connected client users who do not have the SUPER privilege are
  disconnected on the next request, with an appropriate error.
  Disconnection includes terminating running statements and releasing
  locks. Such clients also cannot initiate new connections, and receive
  an appropriate error.
Connected client users who have the SUPER privilege are not
  disconnected, and can initiate new connections to manage the server.
Replication slave threads are permitted to keep applying data to the
  server.
Only users who have the SUPER privilege can control offline mode. To
  put a server in offline mode, change the value of the new offline_mode
  system variable from OFF to ON. To resume normal operations, change
  offline_mode from ON to OFF. In offline mode, clients that are refused
  access receive an ER_SERVER_OFFLINE_MODE error.

A: Disable the login credentials used by the remote apps?
Firewall the MySQL port so it can't be accessed by the remote apps?

A: There are some another method to temporary disable access to MySQL database during maintenance.
Edit /etc/mysql/my.conf'
Change bind-address to:
bind-address = 127.0.0.1
Restart MySQL:
service mysql restart --skip-networking
Nobody will access MySQL server from remote until you have change bind-address to original value and restart MySQL again.


text:
Q: One UIPickerView Two Data Sources/Views works once then crashes I am trying to display a single UIPickerView in my app and depending on what button is selected a UIPickView will popup and populate with the relevant data for the button selected. No sure if it matters but one UIPickerView has three columns and one has two. I can get both of them to work perfectly when the are separate but the minute that I nest them into if statements it breaks.
On the third time when I select the button that fires the opposite UIPickerView it crashes and give me the error of NSRangeException and that it is trying to find the object at index 2 in an array [0...1]. My understanding is that the program thinks that there is an object in a spot in the array that doesn't exist.
I have tried the [picker reloadAllComponents] method and have it called each time the button is selected but as stated above that only works once and then it quits. The strange thing is that if I select the button that I pressed for the second set of code it works perfectly. It is when I select a button that would make the UIPickerView have to change its view that it crashes.
I am really new to iOS development and Objective C and hope that someone out there knows what I am doing wrong. I will post any code that you guys need and will post a couple samples just to understand what is going on.
Here is one of the buttons methods that sets an int to 2 and also calls the method to show the picker.
-(IBAction)linePopupPicker{
picker = 2;
[self pickerShow];
}

This code is the other method which is pretty much the same as the other (I am aware that I haven't implemented the UserDefaults into the second button yet)
-(IBAction)namePicker{
field  = 1;
picker = 1;
NSLog(@"The value of field is:%i", field);
NSUserDefaults *pickerViewSelectionDefaults = [NSUserDefaults standardUserDefaults];
[tipPicker selectRow:[pickerViewSelectionDefaults integerForKey:@"pickerViewSelectionKey"] inComponent:0 animated:NO];
[tipPicker selectRow:[pickerViewSelectionDefaults integerForKey:@"pickerViewNameColor"] inComponent:1 animated:NO];
[tipPicker selectRow:[pickerViewSelectionDefaults integerForKey:@"pickerViewNameFontSize"] inComponent:2 animated:NO];

[self pickerShow];
}

This is the method that calls the UIPickerView. I have it so that it emerges onto the view rather than being static. I thought that this would be the best place to reload the components.
-(IBAction)pickerShow{

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
CGAffineTransform transform = CGAffineTransformMakeTranslation(0, 240);
pickerView.transform = transform;
[self.view addSubview:pickerView];

[tipPicker reloadAllComponents];

[UIView commitAnimations];
}

Finally here is just a sample of the code that is used throughout the various methods that need to be called for the UIPickerView.
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
if (picker ==2) {
    switch (component)
    {
        case 0:
        {
            UILabel *lineColorLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 130, 44)] autorelease];
            lineColorLabel.backgroundColor = [UIColor clearColor];
            NSString *lineTempColor = [colorArray1 objectAtIndex:row];
            //NSLog(@"The String Color Name:%@", tempColor);
            UIColor *myColor1 = [UIColor performSelector:NSSelectorFromString(lineTempColor)];
            lineColorLabel.backgroundColor =  myColor1;
            return lineColorLabel;
        }
        case 1:
        {
            UILabel *alphaLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0,40, 44)] autorelease];
            alphaLabel.text = [alphaArray objectAtIndex:row];
            alphaLabel.font = [UIFont systemFontOfSize:18];
            alphaLabel.textAlignment = UITextAlignmentCenter;
            alphaLabel.backgroundColor = [UIColor clearColor];
            alphaLabel.shadowColor = [UIColor whiteColor];
            return alphaLabel;
        }
        default:
            break;
    }
}

else if (picker == 1)
 {
    switch (component)
    {
        case 0:
        {
            UILabel *fontLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 130, 44)] autorelease];
            fontLabel.backgroundColor = [UIColor clearColor];
            fontLabel.shadowColor = [UIColor whiteColor];
            fontLabel.text = [fontNames objectAtIndex:row];
            NSString *font = [fontNames objectAtIndex:row];
            fontLabel.font = [UIFont fontWithName:font size:18.0];
            fontLabel.textAlignment = UITextAlignmentLeft;
            return fontLabel;
        }
        case 1:
        {

            UILabel *colorLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 35, 44)] autorelease];
            NSString *tempColor = [colorArray objectAtIndex:row];
            //NSLog(@"The String Color Name:%@", tempColor);
            UIColor *myColor = [UIColor performSelector:NSSelectorFromString(tempColor)];
            colorLabel.backgroundColor =  myColor;

            return colorLabel;
        }
        case 2:
        {
            UILabel *sizeLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0,40, 44)] autorelease];
            sizeLabel.text = [fontSizeArray objectAtIndex:row];
            sizeLabel.font = [UIFont systemFontOfSize:18];
            sizeLabel.textAlignment = UITextAlignmentCenter;
            sizeLabel.backgroundColor = [UIColor clearColor];
            sizeLabel.shadowColor = [UIColor whiteColor];
            return sizeLabel;
        }
        default:
            break;
    }

}

    return 0;
}

Here are the data methods:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
if (picker == 2) {
    return 2;
}else if (picker == 1) {
    return 3;
}

//return 3;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { // This method also needs to be used. This asks how many rows the UIPickerView will have.
if (picker == 2) {
    if (component == 0) {
        return [colorArray1 count];
    }
    return [alphaArray count];
}else if (picker == 1) {
    if (component == 0) {
        return [fontNames count];
    }else if (component == 1) {
        return [colorArray count];
    }
    return [fontSizeArray count];
}

}

I hope this post provides all of the information that is need to help me get this fixed. I really appreciate it and hope that I am just missing something really simple. Thank you in advanced.
I am really new to iOS development and Objective C so this problem is really stumping me.

A: case 1 in the if ( picker == 2) switch statement has an opening brace but no closing one.
EDIT
- (void) savePickerOne {
    [pickerViewSelectionDefaults setInteger:[tipPicker selectedRowInComponent:0] ForKey:@"pickerViewSelectionKey"];
    [pickerViewSelectionDefaults setInteger:[tipPicker selectedRowInComponent:1] ForKey:@"pickerViewNameColor"];
    [pickerViewSelectionDefaults setInteger:[tipPicker selectedRowInComponent:2] ForKey:@"pickerViewNameFontSize"];
}


text:
Q: Receiving JSON Using Asp.net webform or WCF how can i receive JSON data that is sent to the server using POST ?
for example : i want to write a web service that receives JSON form the clients
and save it to the DB.

A: In "classic" ASP.NET you can always resort to an IHttpHandler that would handle a "raw" HTTP request. See this question.

A: Trivial example in WCF:
public interface IHelloWorld
{
    [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    HelloWorldResponse Hello(HelloWorldAsk request);
}

DataContracts
[DataContract]
public class HelloWorldAsk
{
    [DataMember]
    public string MyName { get; set; }
    [DataMember]
    public string MyEmail { get; set; }
}

[DataContract]
public class HelloWorldResponse
{
    [DataMember]
    public string YourName { get; set; }
    [DataMember]
    public string YourId { get; set; }
}

Implementation (Service1.svc):
public class Service1 : IHelloWorld
{

    public HelloWorldResponse Hello(HelloWorldAsk request)
    {
        //Do what you need to do - e.g. verify then save to db

        return new HelloWorldResponse
        {
            YourId = request.MyEmail,
            YourName = request.MyName
        };
    }
}

Client: Web page using JQuery (slightly modified from above linked sample):
var $data = JSON.stringify({ "MyName": "Ed", "MyEmail": "Ed@foo.com" });

function CallHandler() {
    $.ajax({
        url: "Service1.svc/hello", //Service.svc is the wcf service, Hello is the service method you are invoking
        contentType: "application/json; charset=utf-8",
        type: 'POST',
        dataType: "json",
        data: $data,
        success: OnComplete,
        error: OnFail
    });
    return false;
}

function OnComplete(result) {
    alert("Your name is: " + result.YourName + " and your email is: " + result.YourId);
    console.log(result);
}
function OnFail() {
    alert('Request Failed');
}

To test call CallHandler() anywhere in the web page.
Response: {"YourId":"Ed@foo.com","YourName":"Ed"}
Response Header:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8

Hth...


text:
Q: Getting only the models related to a Django queryset I don't have much experience with Django (I'm using 1.3) so I have the feeling on the back of my head that this is a dumb question... But anyway:
I have models like this:
class User(models.Model):
    name = models.CharField()

class Product(models.Model):
    name = models.CharField()
    public = models.BooleanField()

class Order(models.Model):
    user = models.ForeignKey(User)
    product = models.ManyToManyField(Product, through='OrderProduct')

class OrderProduct(models.Model):
    product = models.ForeignKey(Product)
    order = models.ForeignKey(Order)
    expiration = models.DateField()

And let's say I do some query like this
Product.objects.filter(order__status='completed', order__user____id=2)

So I'd get all the products that User2 bought (let's say it's just Product1). Cool. But now I want the expiration for that product, but if I call Product1.orderproduct_set.all() I'm gonna get every entry of OrderProduct with Product1, but I just want the one returned from my queryset.
I know I can just run a different query on OrderProducts, but that would be another hit on the database just to bring back data the query I ran before can already get. .query on it gives me:
SELECT "shop_product"."id", "shop_product"."name"
FROM "shop_product"
INNER JOIN "shop_orderproducts" ON ("shop_product"."id" = "shop_orderproducts"."product_id")
INNER JOIN "shop_order" ON ("shop_orderproducts"."order_id" = "shop_order"."id")
WHERE ("shop_order"."user_id" = 2  AND "shop_order"."status" = completed )
ORDER BY "shop_product"."ordering" ASC

If I could SELECT * instead of specific fields I'd have all the data that I need in one query. Is there anyway to build that query and get only the data related to it?
EDIT
I feel I need to clarify some points, I'm sorry I haven't been clearer:

*

*I'm not querying against OrderProduct because some products are public and don't have to be bought but I still have to list them, and they'd not be returned by a query against OrderProduct

*The result I'm expecting is a list of products, along with their Order data (in case they have it). In JSON, it'd look somewhat like this
[{id: 1, order: 1, expiration: 2013-03-03, public: false},
 {id: 1, order: , expiration: , public: true
Thanks

A:
I'm gonna get every entry of OrderProduct with Product1, but I just
  want the one returned from my queryset.

You just want which "one"? Your query is filtering on the Product model, so all Users, Orders, and OrderProducts associated with each of the Products in the returned queryset will be accessible.
If you want one specific OrderProduct, then you should be filtering as op = OrderProduct.objects.filter(xxxxx) and then accessing the models up the chain like so:
op.product, op.order, etc.

A: I would have suggested the method prefetch_related, but this isn't available in Django 1.3.
Dan Hoerst is right about selecting from OrderProduct, but that still hits the database more than necessary. We can stop that by using the select_related method.
>>> from django.db import connection
>>> len(connection.queries)
0
>>> first_result = OrderProduct.objects.select_related("order__user", "product")
...               .filter( order__status="completed",
...                        order__user__pk=2 )[0]
>>> len(connection.queries)
1
>>> name = first_result.order.user.name
>>> len(connection.queries)
1
>>> product_name = first_result.product.name
>>> len(connection.queries)
1


text:
Q: Laravel query with distinct() methode how can i get branch_id value but with different program_id condition?
$data   = Peserta::where('branch_id',$branch_id)
                ->select('program_id')->distinct()
                ->with('program','branch');
                return DataTables::of($data)
                ->addColumn('program', function ($data) {
                    return $data->program->name;
                })
                ->addColumn('action', function ($data) {
                    $btn = 'program->id.'" class="btn btn-sm btn-info"> check ';
                    return $btn;
                })
                ->rawColumns(['program','action'])
                ->make(true);

A: Group the results using branch_id:
$data   = Peserta::where('branch_id',$branch_id)
                ->select('program_id')->distinct()
                ->with('program','branch');
                return DataTables::of($data)
                ->addColumn('program', function ($data) {
                    return $data->program->name;
                })
                ->addColumn('action', function ($data) {
                    $btn = 'program->id.'" class="btn btn-sm btn-info"> check ';
                    return $btn;
                })
                ->rawColumns(['program','action'])
                ->groupBy('branch_id') // grouping the results
                ->make(true);


text:
Q: A LNK 2019 Error with my class I created I have beeen using this template to make my classes to store data for various parts of my program.
//Classs that DOES NOT work
//"MiningPars.h"
#pragma once
#ifndef MININGPAR_H
#define MININGPAR_H
#include <iostream>
#include <fstream>
using namespace std;
class MiningPars
{
public:
    int NumYears;
    double iRate;
    int MaxMineCap;
    int MaxMillCap;
    int SinkRate;
    double ReclaimCost;
    double PitSlope;

public:
    MiningPars();

    MiningPars(int numYears,double irate,int maxMineCap,int maxMillCap,
        int sinkRate, double reclaimCost, double pitSlope): NumYears(numYears),
        iRate(irate),MaxMineCap(maxMineCap),MaxMillCap(maxMillCap),SinkRate(sinkRate),
        ReclaimCost(reclaimCost),PitSlope(pitSlope) {}
            };
            #endif

when I just declare a new mining par, it gives me the error
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall MiningPars::MiningPars(void)" (??0MiningPars@@QAE@XZ) referenced in function "void __cdecl `dynamic initializer for 'par''(void)" (??__Epar@@YAXXZ)

i.e. my code looks like this:
    #include "MiningPars.h"

    MiningPars par;//Error
    vector <PredecessorBlock> PREDS;//is okay
    void main()
    {
        par.iRate = .015;
        //... etc.
    }

most MSDN and other google searches say that i am not declaring things correctly or i haven't added appropriate dependanies, but it is the same format that I created another class.  an example of my other work can be seen here:
//Classs that works
#pragma once

#ifndef PREDECESSOR_H
#define PREDECESSOR_H
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

class PredecessorBlock
{
public:
    int BLOCKID;
    vector <int> PREDS_IDS;
    int PredCount;

public:
    PredecessorBlock();

    PredecessorBlock(int blockID,vector<int>predsids,
        int predcount) : BLOCKID(blockID),
        PREDS_IDS(predsids), PredCount(predcount)
    {}

};

#endif

so this has been confusing for me.  I appreciate any advice you may give

A:
main.obj : error LNK2019: unresolved external symbol "public: __thiscall MiningPars::MiningPars(void)"

Linker is complaining about not providing default constructor definition for MiningPars.
class MiningPars
{
    ...
     MiningPars(); // This is declaration.
                   // Have you forgotten to provide the definition of it
                   // in the source file ?

And
MiningPars par;

the above statement invokes default constructor. If the definition is empty then do -
MiningPars() {}

in the class definition like you did for the parameterized constructor.

A: When you write
MiningPars par;

a par object of type MiningPars is created on the stack. To create an object, the constructor (in this case the default one, that is the one with no arguments) is called, but you don't define the constructor in your MiningParsclass.
To solve this, either define the constructor in your class cpp file, or if the constructor doesn't need to do anything, you can write the empty inline definition in the header file:
class MiningPars
{
public:
    MiningPars() {}
...
};

or just don't declare the default constructor, the compiler will generate a empty one for you.

A: I agree with Mahesh
inside your class
         MiningPars(){}


text:
Q: UIPanGestureRecognizer to pull down UITableView Very similar to composing a new mail in the stock iOS mail app, I am constructing my own pull-down view:

I have the pan gesture added to TableViewController.view from the ContainerViewController. This works fine except when the TableView's content is too tall and has to scroll. Then, my original pan gesture is completely ignored.
I am trying to get the behavior similar to the iOS pull-down modal view.

UPDATED
class CotainerViewController: UIViewController {

 ...

    func viewDidLoad() {

       self.addChild(self.tableViewController)
       tableViewController.didMove(toParent: self)
       self.tableViewController.delegate = self
       self.view.addSubview(self.tableViewController.view)

       self.panGestureRecognizer.maximumNumberOfTouches = 1
       self.panGestureRecognizer.minimumNumberOfTouches = 1
       self.panGestureRecognizer.cancelsTouchesInView = true
       self.panGestureRecognizer.addTarget(self, action:#selector(self.handlePanGesture(gestureRecognizer:)))        self.tableViewController.view.addGestureRecognizer(self.panGestureRecognizer)

    }


text:
Q: listview: getting subitem text i have a listview with the following columns id, surname, firstname. i want to get the surname when a row is selected how do i do it using visual c# 2008?

A: subscribing SelectedIndexChanged for ListView1:
ListView1.SelectedItems[0].Subitems[1].Text

you have some tons of microsoft documentation about it..
http://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.listviewsubitem.aspx

A: You have to obtain the selected Item: SelectedItem, then look in the SubItems collection. In general we can say that is better to have some object bound to the item ( for example in the tag ) and obtain back th einformation from it.

A: Create a SelectedIndexChanged Event or ItemActivate (if you want to double click the item before it fires whatever work you want).
listView1.SelectedItems[0].Subitems[1].Text

Remember that SubItems start at zero index and in your surname column is in index of 1. Column id takes the zero index.


text:
Q: Mysql not accepting user account BUT root@localhost My php application can accept the login and password for root@localhost, but when I change it to the DB user, I see

Access denied for user 'eramba'@'localhost' (using password: YES)

*

*mysql user query output

*first image - database.php settings

*GRANT for eramba@localhost

I had flush privileges after adding the eramba user. I have no anonymous users.
.

I'm lost


text:
Q: How to use Ninject with HttpClient What would be the recommended way to use Ninject to inject the same HttpClient object to all Controller instances in an application?
Currently, I am injecting an EntityFramework Database context following Adam Freeman's MVC book as follows. However, this creates a new dbContext for each controller instance, which is probably not ideal for HttpClient, since HttpClient is meant to be reused across all controllers in an MVC application.
Constructor:
public class AccountController : Controller
{
  MyDBContext dbContext = new MyDBContext();

  public AccountController(MyDBContext context)
  {
    dbContext = context;
  }

  ...
}

And the Ninject Factory is as follows:
/// Class based on Adam Freeman's MVC book to use dependency injection to create controllers
public class NinjectControllerFactory : DefaultControllerFactory
{
  private IKernel ninjectKernel;

  public NinjectControllerFactory()
  {
    ninjectKernel = new StandardKernel();
    AddBindings();
  }

  protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
  {
    return controllerType == null
      ? null
      : (IController)ninjectKernel.Get(controllerType);
  }

  private void AddBindings()
  {
    ninjectKernel.Bind<MyDBContext>().ToSelf().InTransientScope();
  }
}

A: You just have to change your configuration to:
ninjectKernel.Bind<MyDBContext>().ToSelf().InRequestScope();

For more information about request scoping, please read this.

A: Thanks Steven. Currently, I find that the following works. I created a static HttpClient property in the NinjectController and bound it as constant in singleton scope. Daniel's book was helpful in better understanding Ninject.
/// Class based on Adam Freeman's MVC book to use dependency injection to create controllers
public class NinjectControllerFactory : DefaultControllerFactory
{
  private IKernel ninjectKernel;
  private static HttpClient WebAPIClient; // added

  public NinjectControllerFactory()
  {
    ninjectKernel = new StandardKernel();

    WebAPIClient = new HttpClient();  // added
    WebAPIClient.BaseAddress = new Uri("http://localhost:1153");  // added

    AddBindings();
  }

  protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
  {
    return controllerType == null
      ? null
      : (IController)ninjectKernel.Get(controllerType);
  }

  private void AddBindings()
  {
    ninjectKernel.Bind<MyDBContext>().ToSelf().InTransientScope();
    ninjectKernel.Bind<HttpClient>().ToConstant(WebAPIClient).InSingletonScope();  // added
  }
}


text:
Q: How to check if a string only contains numbers in Swift 2? Before Swift 2 I used this extension to check if a string only is made out of numbers:
func isNumbersOnly() -> Bool {
        let regexNumbersOnly = NSRegularExpression(pattern: ".*[^0-9].*", options: nil, error: nil)!
        return regexNumbersOnly.firstMatchInString(self, options: nil, range: NSMakeRange(0, self.length())) != nil
}

but now with Swift 2 I get the error

Cannot invoke initializer for type 'NSRegularExpression' with an
  argument list of type '(pattern: String, options:
  NilLiteralConvertible, error: NilLiteralConvertible)'

Is there a better known way now? Thnx!

A: In Swift 2 NSRegularExpression "throws" so you have to use it with try.
Also you can't pass nil for options anymore: if you don't want to specify options, pass an empty array (same for firstMatchInString).
And self.length() should become self.characters.count.
Last note: if the goal is to determine if a String contains only numbers, and since you're naming it "isNumbersOnly", the resulting Boolean should be true if there's only numbers: it's currently the inverse. I've fixed this in my example.
Ignoring errors:
let regexNumbersOnly = try! NSRegularExpression(pattern: ".*[^0-9].*", options: [])
return regexNumbersOnly.firstMatchInString(self, options: [], range: NSMakeRange(0, self.characters.count)) == nil

With proper error handling:
do {
    let regexNumbersOnly = try NSRegularExpression(pattern: ".*[^0-9].*", options: [])
    return regexNumbersOnly.firstMatchInString(self, options: [], range: NSMakeRange(0, self.characters.count)) == nil
} catch let error as NSError {
    print(error.description)
}

A: Instead of using regular expressions, you can use CharacterSets to check for the existence (or absence) of certain characters. To check if the string is only digits you can use the following:
extension String {
    var isDigits: Bool {
        if isEmpty { return false }
        // The inverted set of .decimalDigits is every character minus digits
        let nonDigits = CharacterSet.decimalDigits.inverted
        return rangeOfCharacter(from: nonDigits) == nil
    }
}

This method can be applied to any type of CharacterSet and, in my opinion, is a lot cleaner than using regex strings.

A: Swift 2 has adjusted the error-handling process; you should now try the call, not specifying an error and be prepared to catch an exception.
E.g.
do {
    let regexNumbersOnly = try NSRegularExpression(pattern: ..., options: nil)
    ... etc ...
} catch _ {}

... given that you're electing not to handle error states.


text:
Q: Run command after system start automatically I am using ubuntu 10.04 and I want to run "gnome-panel &"  command after my system starts.Because my desktop top panel is missing when i restart my system.and when i m running gnome-panel & comand it is coming back.
If i put in .bashrc i m getting continously enter password prompt because my usrt is not in sudo group , can i put in /home/user/.bashrc or /root/.bashrc.Or can anyone tell me alternate methode to run command or shell script after system start automaticaly.

A: Put your command at last of /etc/rc.local but before exit. Or add your command to ~/.profile file or /etc/profile file
Add these lines (to give your user root access without password) to sudoers file (/etc/sudoers)  as :
Execute sudo gedit /etc/sudoers in terminal and add following lines to it at the end of "%admin ALL = (ALL) ALL"
user_name ALL = (ALL) NOPASSWD:ALL

Replace user_name with your user name


text:
Q: Symfony Default timezone doesn't want to work if changed At the moment i am trying to make a symfony app, but it gave me an error and couldn't start it's server when using the server:run command. It said that it couldn't run because of the timezone. If I change the timezone in the default php.ini file on a mac, it still gives me the error:
[Symfony\Component\Debug\Exception\ContextErrorException]
  Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezo
  ne_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone
  'UTC' for now, but please set date.timezone to select your timezone.
Can someone help me? I tried a lot, but can't figure this one out.
I want to change the timezone in the php.ini file that is being used by Symfony. But i don't know what i am doing wrong.

A: you can set it in your AppKernel (app folder):
class AppKernel extends Kernel
{
    // the usuals.....

    // Add this

    public function __construct($environment, $debug) {
      date_default_timezone_set('Europe/Warsaw');
      parent::__construct($environment, $debug);
    }

}


text:
Q: Django on Digital Ocean So I am beginner Django Developer and have been learning by developing local apps. I am looking to finally deploy something so people can use it. I have been looking around at various hosting providers and I am wondering what it's like using Digital Ocean for Django hosting. Specifically what exactly is involved/required with managing a Django app on Digital Ocean. Hostgator, which is another host I've been looking at, does not offer any "one-click" install for stuff like Nginx or anything else which I noticed Digital Ocean does have, so I would have to install that that as well as anything else I'd need myself. I guess my question is after that one click install what is involved with managing a Django app on Digital Ocean? Do I have to learn how to do a ton of other stuff regarding managing a server and dealing with Nginx (I would have to do that on HostGator) or does that One-click install for Django handle all that? Also other than Django, are there any skills that I have to learn in order to be able to do this?

A: Digital Ocean is more than a hosting service, it's a development platform. Digital Ocean works around the element of "droplets", where each droplet is a virtual machine typically running a UNIX system. Basically if you are looking for a service where you can both host a website and do some development, Digital Ocean may be the way to go, but it is not free. But yes, you would have to configure everything yourself with regards to setting-up Django, proxies, and other network-related tasks.
If you are looking for an easier, alternative solution, you might want to take a look at Django on Heroku.

A: As far as I know, there are no one-click solutions for Django. There is an official tutorial, though, which is where I would start, along with a quick read in the Django docs.
My experience hosting small Django apps on DO has generally been good. DO is very stable nowadays with no noticeable downtime (unless you must guarantee HA to your users, which I don't).

A: I have been using Digital Ocean/DO for my Django deployment last 6 months and have a great experience.
I use Django On Click Django 1.8.7 in Ubuntu 16.04 Image for all my website development.
Do provides extensive tutorials/documentations and very developer/tinker friendly. I was able to config my Do box Nginx to host 4 different websites on one single box and even manage to run a Ethereum node on it.
I wrote this tutorial on How to Deploy Multiple Websites on 1 single DO Droplets - Tutorial Link


text:
Q: LINQ to XML At least one object must implement IComparable I want to get the highest attribute "ID" from my XML file.
My code:
    var doc = XElement.Load("invoices.xml");

    var q = (from f in doc.Element("ListOfInvoices").Elements("Invoice")
             orderby f.Attributes("ID") descending
             select f.Attribute("ID")).FirstOrDefault();

When in my XML file is one of Invoice code works, but when is for example 2 invoice I have an error:
At least one object must implement IComparable.

A: Try casting f.Attributes("ID") into an int if it's numeric or a string if it's alphanumeric like this:
var q = (from f in doc.Element("ListOfInvoices").Elements("Invoice")
             orderby (int)f.Attribute("ID") descending
             select f.Attribute("ID")).FirstOrDefault();

A: You have to explicitly access XAttribute.Value explicitly:
doc.Element("ListOfInvoices")
.Elements("Invoice")
.Select(f => f.Attribute("ID").Value)
.OrderByDecending(a => a).FirstOrDefault();

A: There was a typo on the orderby. You wrote Attributes instead of Attribute.
You need to use the Value property to get the attribute value:
        var q = (
            from f in doc.Element("ListOfInvoices").Elements("Invoice")
            orderby f.Attribute("ID").Value descending
            select f.Attribute("ID").Value
            ).FirstOrDefault();


text:
Q: how to vertically center text beside image Whatever I seem to do I have a problem making the take vertically center alongside of the image.
Any ideas of why this is? I've searched but to no avail, any help would be appreciated! Thanks!
(You may have to make the results window wider to see what I am talking about.)
FIDDLE
HTML:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
       Quisque varius pulvinar imperdiet. Cras quam orci,

       Duis vulputate risus rutrum, elementum purus non,

CSS:
p {
    margin: 0;
    padding: 1em 0;
    font-size: 1.8em;
    line-height: 1.5;
}

.first {
    height: 100%;
    vertical-align: middle;
    line-height: 0;
}

.first p {
    display: inline-block;
    width: 49%;
}

.ipad {
    display: inline-block;
    width: 49.2%;
}

A: I think the following CSS may do the trick:
p {
    margin: 0;
    padding: 1em 0;
    font-size: 1.8em;
    line-height: 1.5;
}

.first {
    height: 100%;
    line-height: 0;
}

.first p {
    vertical-align: middle;
    display: inline-block;
    width: 49%;
}

.ipad {
    vertical-align: middle;
    display: inline-block;
    width: 49.2%;
}

Apply vertical-align: middle to .first p and .ipad.
The vertical-align property is not inherited, so you need to specify it for the child elements that need adjusting.
Reference: http://www.w3.org/TR/CSS2/visudet.html#propdef-vertical-align
See fiddle demo: http://jsfiddle.net/audetwebdesign/UwffH/

A: I suggest you use
 but it's not a good programming practice.
HTML:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque varius pulvinar imperdiet. Cras quam orci,
 Duis vulputate risus rutrum, elementum purus non,

CSS:
p {
    margin: 0;
    padding: 1em 0;
    font-size: 1.8em;
    line-height: 1.5;
}

.first {
    height: 100%;
    vertical-align: middle;
    line-height: 0;
}

.first p {
    display: inline-block;
    width: 49%;
}

.ipad {
    display: inline-block;
    width: 100%;
}


text:
Q: WordPress adding paragraph tag around image First, I am new to WordPress, second I have read all of the posts, blogs, etc. related to this issue and so far nothing makes sense.
I have a simple three page site.  All three pages use this basic code at the top of the page to display a banner type image:

Two of the pages work just fine.  ONLY ONE of the pages, the contact form page, WordPress is wrapping the image in a paragraph tag.  Why only this page?  I could hack it by wrapping it myself and set some CSS to remove the margins.  But why?  Why would WordPress be inconsistent here?

A: WordPress automatically inserts
 and
 tags which separate content breaks.
To disable the wpautop filter, you can use:
remove_filter('the_content', 'wpautop');

A: It is might be because you are using contact form plugin or something , anyway you can add your own style but please do it on the child theme.


text:
Q: How to create different clickable parts from the gameobject I want to create a gameobject which is clickable on 2 different ways.

This picture is just an example but this is what I want. There are two different clickable "hitpoints" which have different functions. The first(black one) should move the gameobject on the x- and y-coordinates. The yellow part should change the angle of the gameobject. I allready tried some things with raycast but I didn't get it. Do someone have a good example maybe? Would be nice...
Greets
Sander

A: You can have multiple colliders in the same game object, and change their Center and Size properties to position them correctly. I think this is the simplest way.
Than you use the hook OnCollisionEnter(Collision collision) like this example:
public class CollisionHandler : MonoBehaviour {

    private IDictionary<Collider, string> colliders;
    void Start () {
        int i = 0;
        colliders = new Dictionary<Collider, string>();

        foreach (var collider in GetComponents<Collider>())
            colliders.Add(collider, "collider_" + i++);
    }

    void OnCollisionEnter(Collision collision)
    {
        Debug.Log(colliders[collision.contacts[0].thisCollider]);
    }
}

I similar approach would be having 2 empty game objects as children of your game object; they would only have one collider each, and a script to handle the collision.


text:
Q: GlobalLock and Global memory in kernel mode? How to use globallock in kernel mode?
A driver linked with kernel32.lib always give me system error 127.(The environment is correct)
How could I use it or is there anything working in kernel mode?

A: Global/local memory doesn't make any sense in kernel mode.
You might want to use ExAllocatePoolWithTag for kernel memory allocation.

A: The way to convert a HGLOBAL handle to pointer in kernel mode is NtUserCreateLocalMemHandle located in Shadow SSDT.
After read code from reactos, it could be done like this.
 HANDLE hRetVal;
    PVOID mem = NULL;
    NTSTATUS status;
    PDWORD size = NULL;
    DWORD dwordsize = 4;
    DWORD realsize = 0;
    KAPC_STATE apcstate;

    ZwAllocateVirtualMemory(NtCurrentProcess(), &size, 0, &dwordsize, MEM_COMMIT, PAGE_READWRITE)
    KeStackAttachProcess(PsGetCurrentProcess(),&apcstate)
    hRetVal = NtUserGetClipboardData(uFormat, pParam);//I am calling it in my hook
    status = NtUserCreateLocalMemHandle(hRetVal, NULL, 0, size);
    realsize = *size;
    if(status == STATUS_BUFFER_TOO_SMALL)
    {
      ZwAllocateVirtualMemory(NtCurrentProcess(),&mem,0,size,MEM_COMMIT,PAGE_READWRITE);
      status = NtUserCreateLocalMemHandle(hRetVal, mem, realsize, NULL);
      ZwFreeVirtualMemory(NtCurrentProcess(),&mem,size,MEM_DECOMMIT)
    }
   if(mem != NULL)
   {
      ZwFreeVirtualMemory(NtCurrentProcess(),&size,&dwordsize,MEM_DECOMMIT);
   }
   KeUnstackDetachProcess(&apcstate);

...Free memory and something else.


text:
Q: "Andrew looked at him in the mirror": can "him" refer to Andrew?
(1) Andrew looked at him in the mirror.
  (2) Andrew looked at himself in the mirror.

Does (1) include (2)'s possibility? Or does him in (1) only refer to someone other than Andrew?

A: The two are separate from one another:
In [1], 'him' must mean someone else, as it is not a reflexive pronoun (that is, a pronoun ending in 'self'). Andrew is thus looking at another person.
In [2], 'himself' is a reflexive pronoun, so Andrew is looking at Andrew('s reflection).


text:
Q: Базовый конструктор с передачей параметров Есть ли какой-то другой способ вызова базового конструктора с передачей параметров? У меня в производном классе всего 2 поля, но мне надо опять переписывать все поля базового. Геморрой...
class SpecialTourPackage : TourPackage
{
    private int discount;
    private int peopleNumberForDiscount;

    public SpecialTourPackage(string travelType, int travelDuration, int priceForOnePerson, int groupCapacity, int discount, int peopleNumberForDiscount) : base
                             (travelType, travelDuration, priceForOnePerson, groupCapacity)
    {
        this.discount = discount;
        this.peopleNumberForDiscount = peopleNumberForDiscount;
    }
}

A: Конечно есть:
public SpecialTourPackage(int discount, int peopleNumberForDiscount) : base("", 0, 0, 0)
{
  ...

A: Если я вас правильно понял, вы хотите упростить код создания множества объектов класса SpecialTourPackage, у которых значения параметров для базового класса будут одинаковыми. Если это так, предлагаю обернуть все параметры базового класса в отдельный класс TourPackageParams и передавать их в конструктор. Получится примерно так:
class SpecialTourPackage : TourPackage
{
    private int discount;
    private int peopleNumberForDiscount;

    public SpecialTourPackage(TourPackageParams tourPackageParams, int discount, int peopleNumberForDiscount) : base(tourPackageParams)
    {
        this.discount = discount;
        this.peopleNumberForDiscount = peopleNumberForDiscount;
    }
}

class TourPackage
{
    private string travelType;
    private int travelDuration;
    private int priceForOnePerson;
    private int groupCapacity;

    public TourPackage(TourPackageParams tourPackageParams)
    {
        travelType = tourPackageParams.TravelType;
        travelDuration = tourPackageParams.TravelDuration;
        priceForOnePerson = tourPackageParams.PriceForOnePerson;
        groupCapacity = tourPackageParams.GroupCapacity;
    }
}

public class TourPackageParams
{
    public string TravelType { get; }
    public int TravelDuration { get; }
    public int PriceForOnePerson { get; }
    public int GroupCapacity { get; }

    public TourPackageParams(string travelType, int travelDuration, int priceForOnePerson, int groupCapacity)
    {
        TravelType = travelType;
        TravelDuration = travelDuration;
        PriceForOnePerson = priceForOnePerson;
        GroupCapacity = groupCapacity;
    }
}

И использование:
var tourPackageParams = new TourPackageParams("travelType", 1, 2, 3);

var specialTourPackage1 = new SpecialTourPackage(tourPackageParams, 1, 2);
var specialTourPackage2 = new SpecialTourPackage(tourPackageParams, 3, 4);
var specialTourPackage3 = new SpecialTourPackage(tourPackageParams, 5, 6);


text:
Q: Neo4j Cypher get direct and indirect dependencies/relationships of a service I have the following use case where I would like to get a graph and table of all direct and indirect dependencies of a specific service.
For example.
(a)-[:DEPENDS_ON]->(b), (c)-[:DEPENDS_ON]->(b), (d)-[:DEPENDS_ON]->(c)
The output I am looking for is a graph starting with service a and showing something like
(a)->(b)<-(c)<-(d)
I tried the following cypher query but it does not seem to return the expected results
MATCH p=(a)-[:DEPENDS_ON*]-() RETURN p
Any ideas on how I can achieve the above outcome and also limit the depth of indirect relationships?


text:
Q: shapeless HList mapping I try
import shapeless._
val ilist = List(1,2,3) ;
val slist = List("a", "b", "c") ;
(ilist :: slist :: HNil).map(list: List[_] => list -> list.length)

and compiler says that it needs argument type in the map function or it cannot find list value when type List[_] is provided. Is there a simple example of mapping?
There is no such problem with plain Scala lists
    val list1 = 1 :: 2 :: Nil; val list2 = 3 :: 4 :: Nil
    (list1 :: list2 :: Nil) map {list => list -> list.length}

compiles fine.

A: I'm a no shapeless expert, but I'm sure you can do that with ~>>. The thing is that map accepts Poly, so you need a Poly function that returns a constant. This is what ~>> is.
  import shapeless._
  import poly._
  val ilist = List(1,2,3) ;
  val slist = List("a", "b", "c") ;

  object fun extends (List ~>> Int) {
    override def apply[T](f: List[T]): Int = f.size
  }

  println((ilist :: slist :: HNil).map(fun))

Note, that ~>> is actually:
type ~>>[F[_], R] = ~>[F, Const[R]#λ]


text:
Q: Real Analysis/Probability - Sequence (Verify solution?) QUESTION::
Let $X_1$, $X_2$ , ... $X_n$ be IID random variables with
P($X_i$ = 1) = P($X_i$ = -1) = $p$
and P($X_i$ = 0) = $1- 2p$ $\forall i = 1, ... , n$
Define $a_n$ = P ($\prod_{i=1}^n X_i = 1$) ; $b_n$ = P ($\prod_{i=1}^n X_i = -1$) ; $c_n$ = P ($\prod_{i=1}^n X_i = 0$)
Estimate convergence of $ a_n , b_n ,  c_n $ as $ n \to \infty$
SOLUTION ::
$a_n = p^n = b_n $ and $c_n = (1-2p)^n$
As $ n \to \infty$
$ a_n \to 0 , b_n \to 0 ,  c_n \to 1$
Is this the right approach ? Or is there something missing ?

A: Hints:
$$c_n=1-P\left(\prod_{i=1}^nX_i\neq0\right)=1-(2p)^n$$
As Kavi made clear in his comments also your calculations of $a_n$ and $b_n$ are not correct.
Further note that $a_n+b_n+c_n=1$ for every $n$.
Try to prove that $a_n=b_n$ for every $n$ which leads to $a_n=b_n=\frac12(1-c_n)$.


text:
Q: Ordering in NodeJS promises I need help with the processing order of promises in NodeJS.
I put console.log commands to show the order the code is executing, but I don't get the right order. I want the log in 1,2,3 order, but I get 1,3,2.
Can anyone see what I am doing wrong?
app.get('/', async  (req, res) => {
  var device=new api(/* Host */'138.118.87.76' , '1420'/*, Timeout */);

  const data = await connect(device);
  console.log('3');
  res.json(data)
})

async function connect(device){
  await device.connect()
  .then(([login])=>login(passwords.mikrotikEquipamentUser,passwords.mikrotikEquipament))
  .then(async function(conn) {
    var c1=conn.openChannel();
    c1.write('/ip/address/print');
    console.log(1);

    c1.data // get only data here
      .subscribe(function(data) { // feeds in one result line at a time.
        console.log('2');
        return(api.resultsToObj(data))
      })
  })
  .catch(function(err) {
    console.log("Error during processing:",err);
  });

}

A: I'm not sure how your conn.openChannel works, but the problem seems to be that .subscribe is calling its callback, but no Promise is returned there (api.resultsToObj(data) will not be returned either).
Assuming the subscribe will only be called once, a solution would be:
return new Promise((resolve, reject)=>{
     c1.data // get only data here
         .subscribe(function(data) { // feeds in one result line at a time.
            console.log('2');
            resolve(api.resultsToObj(data))
         })
})

This way, a promise that "waits" for the callback is returned, and the await on const data = await connect(device); will wait until it is resolved.


text:
Q: Detailed and specific use of Asp.net Sessions? Can any one help me in explaining the detailed and proper use of ASP.NET Sessions.
i read many web portals and blogs but i do not understand how to and where to use the sessions.
we create many sessions on page, for login, transfering some values from one page to another. but what is its impact on multiple users like more than 10000 users accessing the website, server transfer rate. memory storage, etc.
This may help many beginners, and also experienced person to properly use sessions in their project.
Any help is appreciated.

A: This is roughly how it works:
When the user visits your webpage, a session ID is set in a cookie in the user's browser. Each time the browser sends a request to the server, the browser will pass the cookie containing the session ID to the server. This allows the server to recognize the user and associate data with the user across multiple page requests (you can use sessions without cookies if you want to).
The server will by default store this data in memory. However, if multiple webservers are running the application and serving the same user, they will all need to know about the user's session data. Thus, you can configure your application to store session data using the "ASP.NET State Server" Windows service, or you can store the data in a SQL database (or you can write your own Session State Provider and store the data wherever you like). Moreover, storing the session data in memory is obviously a bad choice if you are worried your machine might crash (that obviously should worry you).
As for the "proper and detailed" use of ASP.NET sessions it is hard to say - it depends on what you are trying to achieve.
If you can help it, you should store only small amounts of data in sessions, as the combined sessions of all users visiting your website may take up quite a lot of space. Moreover, if you are using the ASP.NET State Server or the SQL Server session state stores the data you store needs to be serialized and deserialized, which will take a non-trivial amount of time for data of non-trivial size.
If what you are planning to store isn't confidential, an alternative approach might be to store the data in a cookie. That way your server will not have to worry about storing the data at all. This way you are trading memory (or disk space or whatever storage mechanism you choose) for bandwidth, as the cookie will now be part of the payload for every request.


text:
Q: Как отсортировать массив объектов, чтобы объединить все объекты с определенным ключом? /JavaScript Есть масcив вида:
 [{
    "def": 900,
    "from": 100000,
    "before": 199999,
  },
  {
    "def": 900,
    "from": 200000,
    "before": 299999,
  },
  {
    "def": 901,
    "from": 111111,
    "before": 222222,
  } ...]

Как его отсортировать по ключу def, чтобы получить только уникальные def, но со всеми значениями from и before, т.е. из них получить массив из значений всех таких объектов.
Получиться должен массив:
  [{
    "def": 900,
    "from": [100000, 200000, ...]
    "before": [199999, 299999, ...]
  },
  {
    "def": 901,
    "from": [111111, 222222, ...]
    "before": [222222, 333333, ...]
  }, ...]

A: вам не отсортировать надо, а пересобрать, т.е. вам надо

*

*пройти по всем элементам списка

*записывать данные как в словарь
2.1) если ключ def уже существует, то добавлять записи в поля from и before,
2.2) если ключ def не существует, то добавлять сразу всю структуру (с def, from, before)
кстати раз у вас from, before - это массивы, а не значения, то не лучше ли объединить данные в пары и записывать в виде
data: [[11, 22], [33, 44]]

и т.д. или как
data: [{'after': 11, 'before': 22}, {'after': 33, 'before': 44}]

A: Как-то так думаю.

*

*Сортируете по ключу def, если равны то по from если равны то по before

*reduce по массиву и строим искомый объект. Если существует то добавляем новый элемет в существующий. Если нет его в результате то добавляем новый предварительно подготовивв объект

let array = [{
    "def": 900,
    "from": 1000000,
    "before": 199999,
  },
  {
    "def": 900,
    "from": 200000,
    "before": 299999,
  },
  {
    "def": 901,
    "from": 111111,
    "before": 222222,
  }];

let result = array
   .sort((a, b)=> a.def != b.def? a.def - b.def: a.from != b.from? a.from - b.from: a.before - b.before)
   .reduce( (acc, item) => {
    let key = acc.find(i => i.def == item.def);
    if (key != null) {
      key.from.push(item.from);
      key.before.push(item.before);
    } else {
      acc.push({def: item.def, from: [item.from], before: [item.before]});
    }
    return acc;
}, []);

console.log(result);


text:
Q: Constructing mysql tablenames in query This is properly going to be really obvious but been driving me insane for far to long.
I have a bunch of tables in a MySql database, example of these are
//Table Names 000001_table1, 000001_table2, 000002_table1, 000002_table2, 000003_table1, 000003_tabel2
In php i can programmatically create these tables
$db->query("CREATE TABLE {$tablenum}_table1 (ID INT PRIMARY KEY AUTO_INCREMENT, COL1 TEXT, COL2 TEXT, COL3 TEXT)")

However when i come to read these tables I'm getting issues
Using the following query
$db->query("SELECT COUNT(*) from {$tablenum}_table1")

I get the error
Table 'database.000001' doesn't exist[]

If i put backspaces around it, i get the error
Can't find file: '.\database\000001@000d@000a_table1.frm' (errno: 22 - Invalid argument)[]
If i try constructing the table name before the query i get the same issue.
Any ideas
Thanks

A: Use backticks around your tablename:
$db->query("SELECT COUNT(*) from `" . $tablenum . "_table1`")

Hope it helps.

A: looks like your {$tablenum}_table1 converts it to
{$tablenum}._table1
(an extra dot is inserted and he thinks it is 00001.table1 which means:
table1 FROM database 00001

A: Try to use the variable tablename like this:
$db->query("SELECT COUNT(*) from ${tablenum}_table1")


text:
Q: Is there a way to force-invoke the overridden method? The code scenario is as follows:
class ParentClass {
    void foo();
    virtual void doSomething() { foo(); }
};

class ChildClass : public ParentClass {
    virtual void doSomething();
};

Now, is there a way to force the child class to call the parent class' doSomething()? Let's assume that calling foo() is vital and should always be called when doSomething() is called. The child class can of course call ParentClass::doSomething(), but it seems a bit "risky" as it is not enforced.
I have come up with a "dirty" solution which is something like this:
class ParentClass {
    void foo();
    void doSomething() final {foo(); doSomethingChild(); }
    virtual void doSomethingChild() = 0;
};

class ChildClass : public ParentClass {
    virtual void doSomethingChild();
};

This way, child classes have to do the implementation and foo() is always called, but the method is not the same anymore. Is there any solutions that are more elegant?

A: This is not a dirty solution, but the non-virtual interface idiom (or template method pattern) that you discovered by yourself.
By defining a non-virtual function that calls a virtual function (among other things), you force every implementation of your class to implement the behavior of the non-virtual. The implementation are only free to modify part of this behavior, that is, the call to the virtual function.
This is usually done like so:
class Base {
public:
    void foo() {
        //do stuff
        fooImpl();
        //do other stuff
    }
private:
    virtual void fooImpl(); //pure or not
};

class Derived : public Base {
private:
    virtual void fooImpl(){
    // Implement or change fooImpl behavior
    }
};

Making the non virtual public and the virtual private ensures as well that nobody can call fooImpl on these classes, which is what you want as you need some stuff to be perfom before and/or after the call to fooImpl.

A: Let see could this work :
class parent {
     void foo() {...}
     virtual void doFinal() {...}
     void doSomething (){foo(); doFinal();}
}

class child {
    virtual void doFinal() {...}
}

So you can reimplement doFinal ans use doSmthing.


text:
Q: Database access in a web service I'm currently working on a web service implementation to a combined web/desktop application (ie. access from different sources).
Now there are two questions I can't really find an answer to:

*

*How would I access the database in the right way (static class? singleton? DI?)? I didn't find any information on using a Web Service in a DI container to help with the database access.

*What about writing access? Is this the right way to offer a posibility of writing to the database? Of course, the requests would be protected with a userID and a key.
Note: this is NOT wcf, but the normal web service (ie. asmx file extension).

A: There are many "right" ways of accessing a database from a web service.  Personally, I often use ADO.NET inside a static class (or, more accurately, a class with a bunch of static methods) that generally returns a DataTable (wrapped in a DataSet, which can be serialized and thus easily returned from a web service).  You could also use an ORM (like NHibernate), although these invariably have a larger overhead than ADO.NET and thus are a potential source of load problems on your server.
There's no particular reason not to allow write access to your database from your web service.  If your application design requires that the database be written to (obviously a pretty common requirement) then it's perfectly fine to do so from the web service.


text:
Q: AngularJS route failed when refresh After i start the server, it works fine when i click the link to these page. but when i refresh the page it failed, it seems send the route url to server and not found. the backend is spring rest
app.config([ '$routeProvider', '$locationProvider',
            function($routeProvider, $locationProvider) {
                $locationProvider.html5Mode(true).hashPrefix('!');
                $routeProvider.when('/k3/test', {
                    controller : 'liantestCtrl',
                    templateUrl : '/views/lian.html'
                })otherwise({
                    redirectTo : '/k3/fu'
                });
            } ]);

Error :
HTTP ERROR 404

Problem accessing /k3/test. Reason:

   Not Found
Powered by Jetty://

do i need any other settings

A: The reason is probably because you have no URL rewriting in place, so the server cannot resolve the requested URL.
You should add a rewrite rule to redirect all requests to index.html where the URL will be managed by AngularJS.