Q: Is it possible to create single SQL query for dozens of UPDATE statements? Should it increase performace? How should it look like in my case? I have a problem. In code below there is a foreach loop, where is created query string for each object truck inside of trucks collection. The loop iterates 100 times (100 objects in the collection, for the example). And method with the loop is called 2000 times.
I resigned from using of ORM to get better performance. But, unfortunatelly, I am still disapointed a bit with code execution speed.
Please note, that for each iterated object there is created string query, that looks, for the example, like this:
UPDATE dbo.Trucks
SET OfficialNumber = '5124095'
, Status = 'Undefined'
, PerformancesUpdate = @PerformancesUpdate
, PictureLink = 'http://www.somewebsite.com/photos/middle////.jpg'
WHERE TruckId = 405664;

and next, after parsing command.Parameters, if they exists (in this case @PerformancesUpdate), the query is sent via library method with int rows = command.ExecuteNonQuery(); //execute SQL. And so on, 100 times. Please note, that query string depends on object properties, so every case will be different a bit.
Here are my questions. I am wondering, is it possible to create one query for all 100 objects in the loop and sending it at once? If yes, should it increase performance? If yes, How the sample query should look like?
And here is the code that creates loop, where are created and executed SQL queries:
using (SqlConnection connection = GetConnection(_connectionString))
                using (SqlCommand command = connection.CreateCommand())
                {
                    connection.Open();

                    foreach (SomeObject truck in trucks)
                    {
                        Console.WriteLine("Updating " + counter++ + " of " + trucks.Count);

                        //clean up string for basic data
                        truck.Status = CleanUpStringCases(truck.Status);
                        truck.Destination = CleanUpStringCases(truck.Destination);
                        //clean up string for full AIS data
                        if (dataType == "full")
                        {
                            truck.TruckType = CleanUpStringCases(truck.TruckType);
                        }

                        //PARSE

                        SomeObject existing = new SomeObject();

                        //find existing truck to be updated
                        if (truck.OfficialNumber > 0) existing = _context.trucks.Where(v => v.OfficialNumber == truck.OfficialNumber).FirstOrDefault();
                        StringBuilder querySb = new StringBuilder();

                        if (existing != null)
                        {
                            //update for basic data
                            querySb.Append("UPDATE dbo." + _trucksTableName + " SET OfficialNumber = '" + truck.OfficialNumber + "'");
                            if (existing.MNCI == 0) if (truck.MNCI.HasValue) querySb.Append(" , MNCI = '" + truck.MNCI + "'");
                            if (truck.LatestActivity.HasValue) querySb.Append(" , LatestActivity = @LatestActivity");
                            if (truck.ETA.HasValue) querySb.Append(" , ETA = @ETA");
                            if (!string.IsNullOrEmpty(truck.Status)) querySb.Append(" , Status = '" + truck.Status + "'");
                            if (!string.IsNullOrEmpty(truck.Destination)) querySb.Append(" , Destination = '" + truck.Destination + "'");
                            if (!string.IsNullOrEmpty(truck.Area)) querySb.Append(" , Area = '" + truck.Area + "'");

                            if (truck.HeadingTo.HasValue) querySb.Append(" , HeadingTo = @HeadingTo");
                            if (truck.Lat.HasValue) querySb.Append(" , Lat = @Lat");
                            if (truck.Lon.HasValue) querySb.Append(" , Lon = @Lon");
                            if (truck.Speed.HasValue)
                            {
                                querySb.Append(" , Speed = @Speed");
                                if ((existing.SpeedMax < truck.Speed || existing.SpeedMax == null) && truck.Speed != 0) querySb.Append(" , SpeedMax = @Speed"); //update speed max
                            }

                            //string for full AIS data
                            if (dataType == "full")
                            {
                                if (truck.PerformancesUpdate.HasValue) querySb.Append(" , PerformancesUpdate = @PerformancesUpdate");
                                if (!string.IsNullOrEmpty(truck.TruckType)) querySb.Append(" , TruckType = '" + truck.TruckType + "'");
                                if (!string.IsNullOrEmpty(truck.PictureLink)) querySb.Append(" , PictureLink = '" + truck.PictureLink + "'");
                                if (truck.LOA.HasValue) querySb.Append(" , LOA = '" + truck.LOA + "'");
                                if (truck.Height.HasValue) querySb.Append(" , Height = '" + truck.Height + "'");
                            }

                            querySb.Append(" WHERE truckId = " + existing.truckId + "; ");
                        }

                        try
                        {
                            string query = querySb.ToString();

                            command.CommandText = query;
                            if (query.Contains("LatestActivity ="))
                                command.Parameters.AddWithValue("@LatestActivity", truck.LatestActivity);
                            if (query.Contains("ETA ="))
                                command.Parameters.AddWithValue("@ETA", truck.ETA);
                            if (query.Contains("PerformancesUpdate ="))
                                command.Parameters.AddWithValue("@PerformancesUpdate", truck.PerformancesUpdate);
                            if (query.Contains("HeadingTo ="))
                                command.Parameters.AddWithValue("@HeadingTo", truck.HeadingTo);
                            if (query.Contains("Lat ="))
                                command.Parameters.AddWithValue("@Lat", truck.Lat);
                            if (query.Contains("Lon ="))
                                command.Parameters.AddWithValue("@Lon", truck.Lon);
                            if (query.Contains("Speed ="))
                                command.Parameters.AddWithValue("@Speed", truck.Speed);

                            command.CommandTimeout = 30;
                            command.CommandType = CommandType.Text;

                            int rows = command.ExecuteNonQuery(); //execute SQL
                            command.Parameters.Clear();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    connection.Close();
                }

Solution:
Martin`s approach is marked as a solution. And answering question about increasing performance, after testing his approach on local DB I can tell, that DB update speed increases directly proportional on quantity of updated rows in single query. For the example, when updating 300 rows, it took me around 30s, together with API requests. When updating 1000 rows, it all takes around 80s. And, as guys mentioned, the only limitation is the number of parameters, so I am just converting doubles and DateTime to SQL format, getting rid of parameters, and voila.

A: Yes, it is possible to send multiple update commands on one operation.
You would need to add the commands to your string builder and number the SQL parameters.
SqlCommand command = connection.CreateCommand()
var querySb = new Stringbuilder();

for(int i = 0; i < trucks.Count; i++)
{
    [...]

    if (truck.Speed.HasValue)
    {
        querySb.Append(" , Speed = @Speed" + i);
        command.Parameters.AddWithValue("@Speed" + i, truck.Speed);
    }

    querySb.AppendLine();
}
command.CommandText = querySb.ToString();
command.ExecuteNonQuery();

You might create smaller batches of rows (not send all rows at once), maximum number of parameters in one command is 2,098.

A: I recommend using some kind of bulk operations, since multiple separate db roundtrips produces excess overhead (as you have noticed).
Bulk updates can be implemented i.e with following methods:

*

*By using external library which is specialized on high-speed Bulk operations

*By crafting sql stored procedure which takes array of data as parameter. More information about table-valued parameters can be found in https://learn.microsoft.com/en-us/sql/relational-databases/tables/use-table-valued-parameters-database-engine

*Store all the rows with a BULK INSERT operation to a temporary table and run the T-SQL MERGE operation from temp table to actual data table with a single database transaction.


Q: Nightwatch: Basic auth with access_key not working I created nightwatch.json file like below (with username and access_key properties):
"test_settings": {
        "default": {
            "launch_url": "http://localhost",
            "selenium_port": 4444,
            "selenium_host": "localhost",
            "silent": true,
            "cli_args": {
                "webdriver.firefox.profile": "testprofile"
            },
            "screenshots": {
                "enabled": false,
                "path": "screenshots/"
            },
            "desiredCapabilities": {
                "browserName": "firefox",
                "javascriptEnabled": true,
                "acceptSslCerts": true
            },
            "username": "examplelogin",
            "access_key": "password"
        }

but basic auth don't work and I get login window to fill my password and login after running tests. I looked at packets in fiddler and no authorization header was present. Any ideas what I'm doing wrong?
Nightwatch v0.9.6

A: from: https://groups.google.com/d/msg/nightwatchjs/n-B4HnnzYg8/rmaipXiTsuwJ

Replying to my own post before - please don't confuse the username and
  access_key vars as 'basic auth' ones. They are selenium based
  authenticators which can optionally be used for authenticating against
  cloud solutions. Best solution for basic auth is the good old URL way.
  Try:  ``` browser.url('https://' + userName + ':' + password + '@' +
  yourUrl)

A: You can do this in globals.js. It will preserve credentials and skip basic auth prompt.
beforeEach: function (browser, cb) {
  if (browser.globals.basic_auth_url) {
    browser.url(browser.globals.basic_auth_url, cb);
  } else {
    cb();
  }
},

basic_auth_url - add full URL with credentials.
Do not add credentials to launch_url


Q: Javascript Rich Text Editor and associated class to filter and clean the input? I realise there are several rich text editors for jQuery but I cannot find any that have an associated class that does the filtering and cleaning required to accept the input into a database.
Does such a class exist?
I am particularly interested for a PHP library, but .NET would be interesting too.

A: If you would use FCKeditor it would allow to you get clean HTML or XHTML (editor.GetXHTML()) which you could then write into DB.
Actually it's not that much important what you write into DB, because usially you write original HTML (you can always strip from it saspicious tags if needed). In order to prevent XSS attacks it is essential to properly encode content before displaying it on the web-page. For .NET there is AntiXSS library for that at CodePlex.com
For PHP you may want to look at the following libraries:

*

*Zend_Filter

*HTML Sanitizer

*PHP Input Filter
And also this article:

*

*Avoiding XSS security attacks to sites that use HTML editors


Q: Ionic 3: Menutoggle keeps getting hidden I have implemented a hamburgermenu in Ionic 3, but I am facing an issue. When I run the application on my Android device the hamburgermenu keeps disappearing i.e. the button to open the side menu is gone. However, it only happens sometimes. I tried to run the application while inspecting it with Google Chrome, and what I noticed is that the menutoggle gets hidden for some reason, but I don't know why. I don't control the visibility in the .ts class.
<ion-header>
  <div>
    <ion-navbar>
      <button ion-button menuToggle> // this becomes "<button ion-button menuToggle hidden>"
        <ion-icon name="menu"></ion-icon>
      </button>
      <ion-title>Frontpage</ion-title>
    </ion-navbar>
  </div>
</ion-header>

A: I am having similar issue for menu toggle.
I added below code for my page.
Header html code:
<ion-header>
 <ion-navbar text-center color="navBar">
  <ion-buttons right>
   <button class="menu" ion-button menuToggle="right" icon-only>
    <ion-icon name="menu"></ion-icon>
   </button>
  </ion-buttons>
  <ion-title>Password Reset</ion-title>
 </ion-navbar>
</ion-header>

Header css code:
.menu {
    display: block !important;
}


Q: delete Single Core Data Item from a uicollectionviewCell using a button I am trying to delete a single element of the coreData set using a button inside a collectionviewcell. So the cell has a label with the result of the core data fetch. When I hit the button it should delete the cell making it no longer appear. Also the the core data single set item should be perementley deleted. I have scence this used before in protocols but not using core data.The core data is var itemName.
class CustomCell: UICollectionViewCell {
 @objc func delete() {
}}
class ViewController: UIViewController {
    var itemName : [Item] = []
}

A: In My Case Working 100%
Try This
import CoreData

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell Identifier name ", for: indexPath) as! Cellname
    cell.YourButtonNamw.tag = indexPath.row
    cell.YourButtonNamw.addTarget(self, action: #selector(delete), for: .touchUpInside)
     return cell
    }

     @objc func delete(_ sender:UIButton){
      let itemName1 = itemName[sender.tag]
     let context = APP_DELEGATE.persistentContainer.viewContext
            var albums = [YourTableName]()
            let request = NSFetchRequest<YourTableName>(entityName: YourTableName)
            request.predicate = NSPredicate(format: "itemName = %@" , itemName1)
            do
            {
                albums = try context.fetch(request)

                for entity in albums {
                    context.delete(entity)
                    do
                    {
                        try context.save()

                    }
                    catch let error as Error?
                    {
                        print(error!.localizedDescription)

                    }
                }

            }
            catch _ {
                print("Could not delete")

            }

    }


Q: Counting unique variables within a unique variables [R] Suppose this is my data:
X   Y   Z
1   1   2323
1   1   45
1   1   67
1   2   1
1   2   90
1   3   34
1   3   1267
1   3   623
1   4   81
1   4   501
2   1   456
2   1   78
2   2   41
2   2   56
2   3   90
2   3   71
2   4   24
2   4   98
2   5   42
2   5   361

How do I count the values of Z for each unique variable Y for each separate X so that I can get a dataframe that looks like:
X   Y   Z
1   1   2435
1   2   91
1   3   1924
1   4   582
2   1   534
2   2   97
2   3   161
2   4   122
2   5   403

A: Assuming that dataframe is named 'dat' then aggregate.formula which is one of the generics of aggregate:
 > aggregate( Z ~ X + Y, data=dat, FUN=sum)

  X Y    Z
1 1 1 2435
2 2 1  534
3 1 2   91
4 2 2   97
5 1 3 1924
6 2 3  161
7 1 4  582
8 2 4  122
9 2 5  403

Could also have used xtabs which returns a table object and then turn it into a dataframe with as.data.frame:
 as.data.frame( xtabs( Z ~ X+Y, data=dat) )


Q: Git Stash - Local Changes - Git Stash - Git Stash Apply - Undo Need some help, I screwed up. Please reserve judgement.
Alright, this is what I did.

*

*git stash

*made some changes to the code.

*git stash (again)

*git stash apply
Is there any way I can get back to the code I had before the first git stash.
Any help would be appreciated.
Thanks, in advance.

A: Appreciate that applying or popping a Git stash just alters the working directory and/or stage.  It does not make a new commit.  Therefore, simply doing a hard reset should get you back to where you were before the first stash:
# from your branch
git reset --hard

That being said, if you wanted to retain some permutation of the changes since the first stash, that is another story and would require more work and thought to pull off.
Note: Generally speaking, popping a Git stash is risky, because if something goes wrong along the way, you can't reapply the same stash as it has already been popped from the stack.  Use git stash apply for best results.

A: git stash list
<shows all the saved stashes>

git stash show 'stash{0}'
<displays changes in this stash>
<change index according to the one you want, 0 is the last saved stash>

git stash apply 'stash{0}'
<applies the stash>


Q: Triggering events from async/await functions in the right order I have problems ensuring the order of events in my asynchronous task. The class from which other async tasks inherit has the following functions and takes the EventHandlers (ExecutionProgress, ExecutionStarted, ExecutionCompleted) in the constructor arguments:
public abstract Task Operation(IProgress<EventArgs> progress);

public virtual void Execute()
{
    ExecuteAsync()
}

private void ReportProgress(EventArgs args)
{
    if(ExecutionProgress != null) ExecutionProgress(this, args);
}
private async Task ExecuteAsync()
{
    if(ExecutionStarted != null) ExecutionStarted(this, EventArgs.Empty)
    await Operation(new Progress<EventArgs>(ReportProgress));
    if(ExecutionCompleted != null) ExecutionCompleted(this, EventArgs.Empty)

}

Now in one of my classes, that inherits from asynchronous tasks, i override Operation with the following:
public override async Task Operation(IProgress<EventArgs> progress)
{
    // run the synchronous function in another thread
    JobResults results = await Task.Run(() => worker.DoYourJob());
    progress.Report(results);
}

Running this code often, but not always, results in NullReference Exception in the ExecutionCompleted event handler when trying to access the JobResults. This is because ExecutionProgress event which writes the member variable usually gets fired after ExecutionCompleted for whatever reason. I think the standard says nothing about event ordering, but I'm looking for a nice solution to ensure deterministic ordering here.  I want to fire ExecutionCompleted only after all ExecutionProgress events have been handled.
What would be a nice looking solution here? Is there any way to await until all progress reporting events have been handled.

A: The events are all fired in order.  If your event handlers are asynchronous, which seems to be the case, then the code firing the events is going to continue executing as soon as it starts the event handlers, not when they complete.
If the code firing the events needs to not continue on until all of the handlers have finished, then you need to restructure this class such that the event handlers have some means of indicating to this class when they're done.  There are any number of ways to do this, from passing a parameter in the event that allows handlers to tell it when they're done, or to having the signature of the event handlers return a Task rather than being void (you'll need to await those tasks when firing the event).


Q: Copy Woocommerce product short description to ACF I want to copy the short description of all the products to an acf custom field that i created. The custom field's name is sxolia . I don't know how can i catch this ACF Field with a query to the database.
UPDATE `wp_posts`
SET `post_excerpt` = `?`
WHERE `post_type` = 'product'
AND `post_status` = 'publish'

A: You can use ACF function update_field($selector, $value, $post_id); to set the value of a specific field.
More info here: https://www.advancedcustomfields.com/resources/update_field/


Q: testing monaca backend only possible on device, why? When I test my app on my device I'm able to connect to the backend user and collection features. Why isn't that working when I preview the app in the browser (Chrome)? Or is it possible and what should I do to fix this...

A: As stated in the Monaca Backend API Reference Guide, Monaca backend requires a phonegap plugin thus the browser does not have these installed and therefore you will not be able to access those systems.
Ultimately, there is nothing you can do other than to test in the app, although if you use the Monaca Cloud IDE, you do gain a web interface to manage the backend.  It is very useful.
Hope this helps!


Q: 2 SELECT in a query with ORDER BY I need to create a MYSQL query that will return the following:
excel
this is my query
    SELECT  t1.fecha_salida,
        t1.agencia,
        t2.fecha_salida,
        t2.directa
FROM   (SELECT fecha_salida, COUNT(*) AS agencia
        FROM   ventas
        WHERE  ventas.eliminado = 0 AND ventas.cliente_id !=2
        GROUP BY fecha_salida) AS t1,
       (SELECT fecha_salida, COUNT(*) AS directa
        FROM   ventas
        WHERE  ventas.eliminado = 0 AND ventas.cliente_id =2
        GROUP BY fecha_salida) AS t2
        GROUP BY t1.fecha_salida

my table is:
|------ |Columna|Tipo|Nulo|Predeterminado |------
   |//**venta_id**//|int(11)|No| |usuario_id|int(11)|No|
   |tour_id|int(11)|No| |cliente_id|int(11)|No| |vehiculo_id|int(11)|No|
   |cashflow_id|int(11)|No| |total_compra|int(6)|No|
   |total_pagado|int(6)|No| |total_iva|int(6)|No|
   |total_comision|int(11)|No| |a_pagar|int(11)|No|
   |fecha_venta|datetime|No| |fecha_salida|date|No|
   |concretada|tinyint(1)|No| |pasajeros|int(3)|No|
   |nombre|varchar(500)|Sí|NULL |direccion|varchar(500)|Sí|NULL
   |observaciones|varchar(500)|Sí|NULL |forma_pago|tinyint(2)|No|
   |eliminado|tinyint(1)|No|

Can you help me

A: You can use UNION to combine two queries that have same structure , also you should select from combined result and then order them
SELECT * FROM (

    SELECT fecha_salida, COUNT(*) AS agencia
    FROM ventas
    WHERE `fecha_venta` between '2012-03-11 00:00:00' and '2019-08-30 23:59:00'
    and ventas.eliminado = 0
    AND ventas.cliente_id = 2
    GROUP BY fecha_salida

    UNION

    SELECT fecha_salida, COUNT(*) AS agencia
    FROM ventas
    WHERE `fecha_venta` between '2012-03-11 00:00:00' and '2019-08-30 23:59:00'
    and ventas.eliminado = 0
    AND ventas.cliente_id != 2
    GROUP BY fecha_salida

) RESULT
ORDER BY agencia


Q: How can you use subdirectories in a GitHub wiki checkout? I'd like to organize my GitHub wiki pages in subdirectories.  How do we refer to the pages in subdirectories?

A: github wiki / gollum-wiki doesn't inherently provide anything explicit for organizing pages into sub-directories. Any page can be linked from any other page irrespective of where it logically belongs. This is a powerful feature that makes wikis very flexible.
One way to implement a sub-directories structure would be to follow a naming convention.
Example: Having all pages related to subject1 have names that start with subject1, and so on.


Q: How can I build a regex to match a value? I need a regex that matches this kind of strings:
brand-new-car
brand-new-car-1
brand-new-car-100
307

and I just need to catch the "name" regardless of whether the string has -count; like this:
brand-new-car
brand-new-car
brand-new-car
307

This regex does not work properly. Its $1 is the full string, not without -count.
(\S+)(?:-\d+|)$

A: You need to make the first capture group "lazy" or non-greedy.
var re = new RegExp("^(\\S+?)(?:-\\d+)?$");

var testStrings = [
    "brand-new-car",
    "brand-new-car-1",
    "brand-new-car-100",
    "307"
];

for (var i=0; i<testStrings.length; i++) {
    var result = re.exec(testStrings[i]);
    say("result: " + result);
}

The results:
result: brand-new-car,brand-new-car
result: brand-new-car-1,brand-new-car
result: brand-new-car-100,brand-new-car
result: 307,307

A: Try this (?xms)(^[\w-]+.*?)(?=[\w-]+|\Z)
Here, below is an image of regex buddy
where you can catch the "name" regardless of whether the string has -count the yellow and blue foreground highlights the different selections.

A: Just remove the pipe '|', then it works
(\S+)(?:-\d+)$

Checked here rubular


Q: Is there a way to parameterize a jquery function name and call it? I'm trying to make a plugin for a modal and I want the users to be able to initialize the animate function picking from a jquery list of functions like fadeIn , SlideDown etc.
var myModal = new createModal({
    content: myContent,
   appendTo: ".modalSection"
});

$(".modal_trigger").on("click", function () {
   myModal.open();
});

createModal.prototype.open = function () {
    var functionVar = this.options.animateType;
    $(this.modal).fadeIn();
    //i want to replace this above line with the function name in this.options.animateType
}

Any way to do this ?

A: As a jQuery object is, as the name implies, an object, you can access its properties as you would any standard object.
In this case you can use bracket notation to call a function held in one of those properties. For example:
createModal.prototype.open = function () {
  var functionVar = this.options.animateType;
  $(this.modal)[functionVar]();
}


Q: Ending a while loop when it reaches matching numbers I need to end this while loop when it reaches a matching number such as 88, 77, and so on.
import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      int userNum = scan.nextInt();
      if ((userNum >= 20) && (userNum <= 98)){
         System.out.print(userNum + " ");
         while ((userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99)){
         userNum = userNum - 1;
           System.out.print(userNum + " ");
         }

      }
      else{
         System.out.print("Input must be 20-98");
      }
      System.out.print("\n");
   }
}

However, when it runs it never leaves the loop, even when the number reaches one of the matching ones I had in the while loop. please help.

A: if(userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99)

Will always be true, because userNum cannot be all of those values at once. Substitute || for &&:
if(userNum != 11) && (userNum != 22) && (userNum != 33) && (userNum != 44) && (userNum != 55) && (userNum != 66) && (userNum != 77) && (userNum != 88) && (userNum != 99)

This can be made easier using the modulus operator:
if(userNum % 11 != 0)

A: The problem lies in this line.
if(userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99)
If userNum is any number, it cannot be 11, 22, 33, 44, 55, 66, 77, 88, and 99 at once, which means your program will keep running. As @Carcigenicate stated, you want && (and) operators.

A: Try using the && operator here instead of OR
import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      int userNum = scan.nextInt();
      if ((userNum >= 20) && (userNum <= 98)){
         System.out.print(userNum + " ");
         while (userNum != 11 && userNum != 22&& userNum != 33 && userNum != 44 && userNum != 55 && userNum != 66 && userNum != 77&& userNum != 88 && userNum != 99){
         userNum = userNum - 1;
           System.out.print(userNum + " ");
         }

      }
      else{
         System.out.print("Input must be 20-98");
      }
      System.out.print("\n");
   }
}

A: Your code appears to be searching for multiples of 11, so I would prefer testing the remainder of eleven. Also, you can use x-- instead of x = x - 1. Finally, a do-while loop would make this a bit cleaner. Like,
Scanner scan = new Scanner(System.in);
int userNum = scan.nextInt();
if (userNum >= 20 && userNum <= 98) {
    do {
        System.out.print(userNum + " ");
        userNum--;
    } while (userNum % 11 != 0);
    System.out.println();
}

A: You can use following code to ending a while loop when it reaches matching numbers using array.
public class stopWhileTest{
    public static void main(String arg[]) {
        int[] number = {11, 22, 33, 44, 55, 66, 77, 88};
        Scanner scan = new Scanner(System.in);
        int userNum = scan.nextInt();
        if ((userNum >= 20) && (userNum <= 98)){
            System.out.print(userNum + " ");
            while(!contains(number,userNum)){
                userNum = userNum - 1;
                System.out.print(userNum + " ");
            }
        }
        else{
            System.out.print("Input must be 20-98");
        }
        System.out.print("\n");
        scan.close();
    }

    public static boolean contains(final int[] array, final int v) {
        boolean result = false;
        for(int i : array){
            if(i == v){
                result = true;
                break;
            }
        }
        return result;
    }
}

Hope this solution works.


Q: Set the title for the navigation control I converted window based application into navigation based but I am not able to set the title for the navigation bar.
controller = [[bookDisplayViewController alloc] initAndCreateView];

UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
nav.title=@"Application";
[window addSubview:nav.view];

A: Is it possible for you to place
self.navigationItem.title = @"YourName";

in the viewDidLoad of the other view? I'd try it that way and see if it works.

A: You must set the title from within the UIViewController. Try this:

controller.navigationItem.title=@"Application";

Infact apple docs on UINavigationItem for the "title" property  states that:

title
A localized string that represents the view that this controller manages.

@property(nonatomic, copy) NSString *title
Discussion
Subclasses should set the title to a human-readable string that represents the view to the user. If the receiver is a navigation controller, the default value is the top view controller’s title.

Availability
Available in iOS 2.0 and later.


Q: Error connecting web3js to react native application I ran into a problem connecting web3 to a React Native app.
Initially, the connection was made according to this guide.
Everything worked, but as soon as I restart the application, an error appears:

ReferenceError: Property 'Buffer' doesn't exist, js engine: hermes
ERROR Invariant Violation: Module AppRegistry is not a registered
callable module (calling runApplication). A frequent cause of the
error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine:
hermes

Then I comment on these lines in Live reloading mode
const Web3 = require('web3')
const web3Rospen = new Web3('https://ropsten.infura.io/v3/myKey')

I save the code, the application works, again, in Live reloading mode, I uncomment these lines back - the application works.
But initially, just taking and running the application from web3 does not work. Maybe someone faced such a problem?
Versions:
"react-native": "0.66.4",
"web3": "^1.7.3"


Q: JAXB default value for null elements when marshalling At the time of marshalling of JAXB object I want to set some defult value to the resulting XML.
I do not want to use nillable=true as it generates empty tag with unnecessary xsi:nil="true", and this is not for setting default value. Instead I want to generate the XML with some placeholder characters such as '?'.
Use case :  I am going to build a tool for WebService testing. There I need to present the entire request xml to the user (Like SOAPUI).

A:
Use case : I am going to build a tool for WebService testing. There I
  need to present the entire request xml to the user (Like SOAPUI).

The idea of the place holder character isn't really going to work.  For example ? is an ok default value for a string, but not an int, boolean, or for most complex values (i.e. representing the nested address information for a customer).  Instead you will want a value that reflects the type.

Then I would have to write large and complex reflection based code. Just assume that
  that is almost not possible in my case.

This reflection code probably won't be as bad as you are imagining.  A quick search will probably also reveal libraries that populate objects with "dummy" data.  When hooking it up with JAXB you could leverage a Marshaller.Listener to populate the object on the before marshal event.


Q: Update on blur the first time only I can defer model updating until blur with ng-model-options="{ updateOn: 'blur' }".  This prevents annoying the user with changing validation states while entering input the first time around.  However, when a user returns to a failed validation to revise it, the updateOn: 'blur' prevents the validation state from being updated when the user has fixed it (but before they leave the field).
How can I reset the updateOn option to allow the default model update schedule after one blur?

A: ngModelOptions directive $evals its value, but doesn't observe it for changes. In other words, you cannot achieve what you are looking for with something like the following:
<input ng-model="foo" ng-model-options="fooOptions">

and then change it in the controller:
$scope.fooOptions = {updateOn: "blur"};
$scope.changeOptions = function(){
  $scope.fooOptions = {updateOn: "default"};
}

For simple cases, you could add another variable that changes how you show validation messages:
<form name="form1">
   <input name="foo"
          ng-model="foo" ng-model-options="{updateOn: 'default'}"
          ng-blur="startShowingErrors = true" minlength="3">

   invalid entry
</form>

But, if you want the actual form state not update, then you'd need another directive as a facade to ngModelOptions to cause a $compile on every change.


Q: AJAX not rendering as it should I am at a loss with what’s stopping my code not rendering AJAX where it should be, I have a less serious JS ‘Parse error’ which I can’t work out also.
I have a default prevented rails form_for where upon submit event jQuery finds the element and its attribute values, posts them to the model via appropriate action, model then responds with the new object and is supposed to render the JSON  via a jbuilder form.
All is fine when I  get the page to render via a redirect, but not by a render ‘create’, content_type: :json, error displayed is  a missing template error. I also see from network response that it ‘failed to load response data’.  views/reviews/create.json.jbuilder is saved is in the correct place I believe, class and id names are all correct I believe, files and folders are named correctly and in the right place I believe, I can’t see anything wrong? Unsure whether it’s a jbuilder error, a controller syntax error, or a jQuery syntax error. Here is my code:
controllers/reviews_controller.rb:
def create
    @restaurant = Restaurant.find(params[:restaurant_id])
    @review = @restaurant.reviews.new(params[:review].permit(:thoughts, :rating))

    if @restaurant.reviews.find_by user_id: current_user.id
      flash[:notice] = "You already reviewed this restaurant!"
      redirect_to restaurants_path
    else
      @review.user = current_user
      @review.save
      # redirect_to restaurants_path, will do a redirect, but defeats AJAX purpose!
      render 'create', content_type: :json # results in a missing template error #'missing templete reviews/create' error
    end
  end

Assets/restaurants/restaurants.js:
$(document).ready(function(){
  $('.new_review').on('submit', function(event){
    event.preventDefault();
    var reviewList = $(this).siblings('ul');
    var currentRestaurant = $(this).parent();
    $.post($(this).attr('action'), $(this).serialize(), function(review){
      if review # This line results in Uncaught SyntaxError: Unexpected Identifier
      var newReview = Mustache.render($('#review_template').html(), review);
        reviewList.append(newReview);

        currentRestaurant.find('.review_count').text(review.restaurant.review_count)
        currentRestaurant.find('.average_rating_number').text(review.restaurant.average_rating);
        currentRestaurant.find('.average_rating_stars').text(review.restaurant.average_rating_stars);
    }, 'json');
  });
});

views/restaurants/index.html.erb (jbuilder template element):
<template id='review_template'>

    {{ star_rating }} -*- {{ thoughts }}

</template>

views/reviews/create.json.jbuilder:
json.thoughts @review.thoughts
json.star_rating star_rating(@review.rating)

json.restaurant do
  json.average_rating number_with_precision(@restaurant.average_rating,
  precision: 1)
  json.average_rating_stars star_rating(@restaurant.average_rating)
  json.review_count pluralize(@restaurant.reviews.count, 'reviews')
end

Been on this for hours now trying to solve this one, pfff!! any idea where I’m going wrong folks? Am I doing something really dim somewhere here? Thank you.

A: As you can see in the error message, rails is looking for a file called reviews/create[extension] or application/create[extension] and extensions allowed are .erb, .builder, .raw, .ruby, .coffee or .jbuilder.
I suggest to change you ajax call to ask for js, not json, create a file called reviews/create.js.erb, and add this kind of code :
<% if @restaurant.reviews.find_by user_id: current_user.id %>
  // do the code to show the error message in javascript
<% else %>
  reviewList.append("<%= j(render('create')) %>");
  currentRestaurant.find('.review_count').text(<%= pluralize(@restaurant.reviews.count, 'reviews') %>)
  currentRestaurant.find('.average_rating_number').text(<%= number_with_precision(@restaurant.average_rating, precision: 1) %>);
  currentRestaurant.find('.average_rating_stars').text(<%=star_rating(@restaurant.average_rating) %>);
<% end %>

This code should be executed after the success of the creation. You also have to create a file called reviews/_create.html.erb with the html you want to show. Finally, you have to delete some logic in  the javascript and in the controller.


Q: where does llvm.memcpy.p0i8.p0i8.i64 come from i test clang and compile a simple C file including struct asigning.when I see the  LLVM code ,there is llvm.memcpy.p0i8.p0i8.i64 ,where is from ? I not see the defination only see its declare as a fucntion.

A: It is a LLVM intrinsic function. As per the language reference:

LLVM provides intrinsics for a few important standard C library
  functions. These intrinsics allow source-language front-ends to pass
  information about the alignment of the pointer arguments to the code
  generator, providing opportunity for more efficient code generation.

The llvm.memcpy intrinsic specifically:

The ‘llvm.memcpy.*’ intrinsics copy a block of memory from the source
  location to the destination location.
Note that, unlike the standard libc function, the llvm.memcpy.*
  intrinsics do not return a value, takes extra isvolatile arguments and
  the pointers can be in specified address spaces.


Q: how to remove first two words of a strings output I want to remove the first two words that come up in my output string. this string is also within another string.
What I have:
for servers in `ls /data/field`
do
  string=`cat /data/field/$servers/time`

This sends this text:
00:00 down server

I would like to remove "00:00 down" so that it only displays "server".
I have tried using cut -d ' ' -f2- $string which ends up just removing directories that the command searches.
Any ideas?

A: Use -d option to set the delimtier to space
$ echo 00:00 down server | cut -d" "  -f3-
server

Note Use the field number 3 as the count starts from 1 and not 0
From man page
  -d, --delimiter=DELIM
              use DELIM instead of TAB for field delimiter

   N-     from N'th byte, character or field, to end of line

More Tests
$ echo 00:00 down server hello world| cut -d" "  -f3-
server hello world

The for loop is capable of iterating through the files using globbing. So I would write something like
for servers in /data/field*
do
  string=`cut -d" "  -f3- /data/field/$servers/time`
...
...

A: You can use sed as well:
sed 's/^.* * //'

A: Please, do the things properly :
for servers in /data/field/*; do
    string=$(cut -d" "  -f3- /data/field/$servers/time)
    echo "$string"
done

*

*backticks are deprecated in 2014 in favor of the form $( )

*don't parse ls output, use glob instead like I do with data/field/*
Check http://mywiki.wooledge.org/BashFAQ for various subjects

A: For the examples given, I prefer cut. But for the general problem expressed by the question, the answers above have minor short-comings. For instance, when you don't know how many spaces are between the words (cut), or whether they start with a space or not (cut,sed), or cannot be easily used in a pipeline (shell for-loop). Here's a perl example that is fast, efficient, and not too hard to remember:
 | perl -pe 's/^\s*(\S+\s+){2}//'

Perl's -p operates like sed's. That is, it gobbles input one line at a time, like -n, and after dong work, prints the line again. The -e starts the command-line-based script. The script is simply a one-line substitute s/// expression; substitute matching regular expressions on the left hand side with the string on the right-hand side. In this case, the right-hand side is empty, so we're just cutting out the expression found on the left-hand side.
The regular expression, particular to Perl (and all PLRE derivatives, like those in Python and Ruby and Javascript), uses \s to match whitespace, and \S to match non-whitespace. So the combination of \S+\s+ matches a word followed by its whitespace. We group that sub-expression together with (...) and then tell sed to match exactly 2 of those in a row with the {m,n} expression, where n is optional and m is 2. The leading \s* means trim leading whitespace.


Q: php recursive include function in 2 file with different path Hi all I've a problem with include function in php:
I have 4 file:
dir1/file1.php
dir4/dir2/file2.php
dir3/file3.php
dir3/file4.php

In file1.php I have:
include_once('../dir3/file3.php');

In file3.php I have:
required('../dir3/file4.php');

In file2.php I want write:
include_once('../../dir3/file3.php');

but the required function in file3 doesn't work because the path of file4 must be
../../dir3/file4.php

and not
../dir3/file4.php

How can I fix it?

A: You can use only dot (.) before your filename which will find that file from root of dir..for eg ./dir3/file4.php but it increase the overhead..Another way is to use
$base = __DIR__ . '/../';

require_once $base.'_include/file1.php';

A: If you are calling file3 from file2 you will have to go back 2 directories. The best way is using the full path like :
home/mysite/public_html/dir3/file3.php

It maybe (is) troublesome but good uptill some level.
Edit: DIR and rest is also handy, depending on your need

A: I FIX it with:
In file1.php I have:
$path = '..';
include_once($path.'/dir3/file3.php');

In file3.php I have:
required($path.'/dir3/file4.php');

In file2.php I want write:
$path = '../..'
include_once($path.'/dir3/file3.php');

This work for me.


Q: How to insert date value from jdatechooser to database table  private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
        String G_ID=gIDText.getText();
        String G_Title=(String) titleCombo.getSelectedItem();
        String FName=fNameText.getText();
        String SName=sureNameText.getText();
        String Sex=(String) genderCombo.getSelectedItem();
        String dob=(JTextField)dobDte.getDateEditor().getUiComponent().getText();//error
        int age=Integer.parseInt(ageText.getText());
        String country=contactText.getText();
        String nationality=nationText.getText();
        String ZipCode=zipCodeText.getText();
        String email=mailText.getText();
        String PassportNo=passportText.getText();
        String IssuedDate=(JTextField)issDte.getDateEditor().getUiComponent().getText();//Error
        String ExpiryDate=(JTextField).getDateEditor().getUiComponent().getText();//error
        String PIDNo=pidText.getText();
        int ContactNo=Integer.parseInt(contactText.getText());

        Guest guest=new Guest(G_ID,G_Title,FName,SName,Sex,dob,age,country,nationality,ZipCode,email,PassportNo,IssuedDate,ExpiryDate,PIDNo,ContactNo);
        try {
                boolean isAdded=GuestController.addGuest(guest);
                if (isAdded) {
                    JOptionPane.showMessageDialog(NewGuest.this,"Registered Success !");
                }else{
                    JOptionPane.showMessageDialog(NewGuest.this,"Unable to Register ! !");
            }
    }catch(SQLException | ClassNotFoundException ex){
    JOptionPane.showMessageDialog(NewGuest.this,ex.getMessage());
}
}

(mvc)I have tried to insert date from jdatechooser to mysql database,but its shows error,please help me to fix this and if can please retype the correct code for me

A: 1 - here to set the date from jDateChooser to string
String dob=""+jDateChooser1.getDate();
2 - to insert the date to database you should set the format first
SimpleDateFormat Date_Format = new SimpleDateFormat("yyyy-MM-dd");
 Date_Format.format(jDateChooser1.getDate())


Q: Design a RESTful API in Laravel 5.2, using a resource that conceptually can contain other resources First of all I am really not very familiar with the REST practice, and I am not very confident about the title of my question.
So I am trying to built a RESTful API using Laravel for a phonebook application. The phonebook may contain telephones of either employees (i.e real persons) or offices. For that reason I have three models

*

*a Directorate with id and name fields,

*an Employee with id and name fields and

*a Telephone with id, tel, employee_id, directorate_id, description and type fields.

Telephones corresponding to a directorate's office have only the id, tel, directorate_id and description fields set, while the telephones corresponding to a person (i.e an employee) have set only the id, tel, employee_id, directorate_id, and type fields. That is how I separate them: a telephone having a description can only be an office's telephone, while a telephone having both the employee_id and the type_id set is an employee's telephone.
The models are related as follows:

*

*an employee may have many telephones

*a directorate, may have many telephones
class Directorate extends Model
{
    public function telephones()
    {
        return $this->hasMany(Telephone::class);
    }

    public function employees()
    {
        return $this->hasMany(Employee::class);
    }
}

class Employee extends Model
{
    public function telephones()
    {
        return $this->hasMany(Telephone::class);
    }

    public function directorate()
    {
        return $this->belongTo(Directorate::class);
    }
}

class Telephone extends Model
{
    public function employee()
    {
        return $this->belongsTo(Employee::class);
    }
}

My question is what should I a consider as my resource.
So far I am thinking of the following approach:
I shall use the concept of contact as resource. A contact may be the joined information of either an employee and a telephone, or a directorate and a telephone. For instance, a "contact" may contain the name of an employee with his related telephone numbers and telephone types, or it can contain the name of a directorate with the description of the telephone and the telephone number.
The "problem" with this approach is that I have ended up with (let's put it this way) two different types of resource: the employee's contacts and the directorate office's contacts, which contain slightly different information and thus, I need also to have different create and edit forms to interact with these two "types" of resources.
In order to implement the REST API, I am thinking of two different scenarios:

*

*Use two different RESTful controllers, one EmployeeContacts and another OfficesContacts for separating conceptually the resource to an employee's and an office's resource, and accessing them through different URIs like:
example.com/phonebook/employees/{id}/edit
example.com/phonebook/offices/{id}/edit
example.com/phonebook/employees/create
etc...

*Use a single RESTful controller, e.g. PhonebookContacts to access the resources through the same URIs as one resource  (i.e. both employee's and office's contact resources now are considered to be just a "contact" resource)
//this refers to a contact resource that can be either an office's or a n employee's contact
example.com/phonebook/contact/{id}/edit
//this should list all resources (both employees and offices contacts)
example.com/phonebook/contact/
and then use conditional statements in the controller's create/store/edit/update methods to deal with them separately (e.g if an http POST request contains a description_id then it is an office contact and do this, or else if has an employee_id then it is an employee's contact so do that...)
I would like to hear your views, what of these two different scenarios do you consider to be better in the context of REST for my phonebook app? Would be better to think of a single "contact" resource and handle it using conditional statements with different return in the controller, or shall I separate the concept of "contact" to "employee's contact" and "office's contact" and use separate controllers and URI's to handle them?
Is there another approach that I could follow instead?

A: The way I would do it is with 2 different controllers for the simple reason of speed and responsiveness. Loading all contacts and filtering isn't as quick as loading the one part only.
However, you can always set in your controller the same return with different data. Such as EmployeeController@index returns view('contacts.index', compact('employeeContacts')), and OfficesController@index returns view('contacts.index', compact('officesContacts'))
EDIT:
Sorry, I have misread it...I thought you wanted to do the filtering in the view. Anyway, my practice is to do it separately, simply because the code is cleaner. If you want to make the whole REST more readable, you can put both resources in a group like so: Route::group(['prefix' => 'contact'], function(){ //routes here// });
So now you will have routes like:
example.com/contact/employees/

example.com/contact/offices/

A: I am not familiar at all with Laravel but since this question is about REST concepts (I have a small background on these) I should give it a try.
Since you are building a RESTful application, you must not consider others as human beings but only as machines. IMO the urls should determine the action that will be performed. Thus, by using different urls for different actions (perform a CRUD on a contact - either an Employee or a Directorate or SomethingElseInTheFuture) sounds good to me and fits the REST nice.
Hope this clarify the things for you!
[EDIT]
I believe jannis is right. It should be the verbs (GET, POST, PUT, PATCH etc) that make the action instead of the URLs. The urls are just respresenting the resources. My mistake. So both of your points of view are correct. It's just how convenient each approach is for your project (for now and for the near future of your project). IMO, I see #1 (two different restful controllers) more approchable.
Cheers and sorry for any misconception!


Q: Datasnap response doesn't convert to json I am returning a string response in my DataSnap server.
function TServerMethods1.GetImagem(PhotoPath: string): string;
var
  ...
begin
  ...
  Result := StrEnv.DataString;
end;

This successfully returns a response with my base64 string
{"result":["Qk02...."]}

I need to get the content of the result, this is my base64 string 'Qk02...'. I was trying to get the response as a TJSONObject and then use TJSONObject.Get('result').Value to get my base64 string.
I tried about three ways and couldn't convert this to TJSONObject, in all the attempts it returns me a blank string.
ShowMessage(RESTResponse1.Content); // This shows the result
lJOImagem := RESTResponse1.JSONValue as TJSONObject;
ShowMessage(lJOImagem.ToString); // This shows a blank message
try
  ShowMessage(lJOImagem.GetValue('result').Value)); // This shows a blank message
finally
  lJOImagem.Free;
end;

How to get the content of the result?

A: The JSONObject was successfully being created. The problem was in the way I was accessing the value.

The image was built by me.
The whole response is a TJSONObject, JSONObject.GetValue('result') is a TJSONArray. If I loop through the array It will loop only once and retrieve a TJSONValue which its value is the string I wanted Qk02...
The code is like that
vJSONObject := RESTResponse1.JSONValue as TJSONObject;
if vJSONObject <> nil then
begin
  vJSONArray := vJSONObject.GetValue('result') as TJSONArray;
  for vJSONValue in vJSONArray do
  begin
    memo.Text := vJSONValue.Value; // This is the string I wanted: Qk02..
  end;
end;

A: You can parse your string into a JsonObject. To do this, you have to convert your string into bytes and then convert it into a JsonObject as following :
var MyObject : TJSONObject;
MyObject := TJSONObject.ParseJSONValue(
TEncoding.ASCII.GetBytes(RESTResponse1.Content), 0) as TJSONObject;

You don't have to use TEncoding.ASCII. You can also use TEncoding.UTF8/Unicode/Etc depending on your encoding.


Q: how to find out which website is requesting my webpage? i have a webpage ... sorto like an api ... basically it prints out some data in form of json .
other website can use this data via php by simply using file_get_contents
or
javascript/jquery  ajax request (jsonp)
anyway i want to be able to black list some unwanted websites , so i have to know where this request are coming from
i've tried
 $url     = $_SERVER['HTTP_REFERER'];
 $domain  = parse_url($url, PHP_URL_HOST);

but i get
Undefined index: HTTP_REFERER

so unless i'm mistaken and this was an wierd exception , HTTP_REFERER doesn't work here .
so how can i get the referee in case of file_get_contents page request ?

A: Note that Ajax request are usually sent through the client's browser, while usually a server would call file_get_contents() or a similar tool, to fetch your page.
So in the case of a server, you can check the REMOTE_ADDR HTTP header (which contains the caller's IP) against a blacklist.
In the case of an Ajax request, probably from a user agent you can't really say from which website the originated from.
Though I am not sure, but the HTTP_REFERER header might contain exactly that, but again I have not checked it.
UPDATE (Ajax Requests):
After looking up a little bit, I turn out that browsers don't send referrer data with XHR requests, so you can only blacklist the IPs of the servers you don't want to be accessed from.

A: If the server request it directly then you can use $_SERVER 'REMOTE_ADDR' and 'REMOTE_HOST'.
If they use javascript then you will only get the clients ip. You can use strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') to disallow jquery requests.

A: Isn't what you're looking for a $_SERVER['REMOTE_ADDR']? AJAX calls probably won't have a Referer header and that's why you are getting that error.

A: The HTTP Referrer gets sent by a browser, probably not by file_get_contents()!
You can use $_SERVER['REMOTE_ADDR']. This will give you the raw IP address from the TCP stack.
In the case of a server-side API call, you get the server's IP (assuming the client does not use any proxies).
However if the client is an AJAX request, you'll get the IP address of the user viewing that page.

A: HTTP_REFERER is not going to be reliable.  You might try $_SERVER['REMOTE_ADDR'] to inspect IP address of remote client.
I would however think that you would have a better time whitelisting approved clients rather then blacklisting, as an attacker could easily proxy a request to get around an IP/host-based blacklist.
There are a number of approaches for whiltelisting:

*

*whitelist known IP's

*HTTP Authentication

*Your own custom API keys

*Third party authentication (i.e. OAuth)

and so forth.


Q: MonoGame develop3d branch not building on OS X I've successfully built been using the stable branch of MonoGame and the MonoDevelop templates for a while, and now I want to upgrade to the develop3d branch to utilize all its features. But when I build it, it gives me the error:
~/MonoGame/MonoGame.Framework/GamerServices/GamerProfile.cs(67,24): warning CS0628: `Microsoft.Xna.Framework.GamerServices.GamerProfile.Dispose(bool)': new protected member declared in sealed class
~/MonoGame/MonoGame.Framework/Graphics/GraphicsCapabilities.cs(47,7): error CS0246: The type or namespace name `OpenTK' could not be found. Are you missing a using directive or an assembly reference?

I'm totally lost on why this is happening. What OpenTK should I reference? Does it not come with it, so I'd have to download it or something?
EDIT: Building this in Terminal with xbuild and building it in MonoDevelop both yield the same result.

A: Found the solution; replace this in the beginning of Graphics/GraphicsCapabilities.cs:
#if OPENGL
#if GLES
using OpenTK.Graphics.ES20;
//...

with:
#if MONOMAC
using MonoMac.OpenGL;
#elsif OPENGL
#if GLES
using OpenTK.Graphics.ES20;
//...


Q: Nested List Item not removing from Flask Session I have a simple Route in Flask where I want to add and remove items to a Session dictionary list value. Adding things to it is fine but it doesn't seem to remove the items.
I've tried adding session.modified = True but that doesn't seem to have helped.
What am I doing wrong?
@app.route('/todo/<profile_id>')
def todo(profile_id):

    kw = request.args.get('kw', None)
    lp = request.args.get('lp', None)

    # remove if it exists
    try:
        session[lp].pop(kw)
        session.modified = True
        return True
    except:
        pass

    # add if it doesn't exist
    if kw and lp:
        try:
            session[lp].append(kw)
        except:
            session[lp] = [kw]

    return '{}'.format(session[lp])

A: Assuming you want to store generic Objects you will need to use remove() instead of pop().
Your problem after that is returning True, which is not a valid return type for a view. Flask view raises TypeError: 'bool' object is not callable
from flask import session as sesh

@app.route('/todo/<profile_id>')
def todo(profile_id):
    kw = request.args.get('kw', None)
    lp = request.args.get('lp', None)
    # remove if it exists
    try:
        print(sesh[lp])
        sesh[lp].remove(kw)
        sesh.modified = True
        print("rem", sesh)
        return '{}'.format(sesh[lp])
    except Exception as e:
        print(e)

    # add if it doesn't exist
    if kw and lp:
        try:
            sesh[lp].append(kw)
        except:
            sesh[lp] = [kw]

    print("add",sesh)
    sesh.modified = True
    return '{}'.format(sesh[lp])


Q: stuck in lxml and xpath in python 3.x I am parsing an arxml file to extract data from it in python 3.x but I am stuck and can't get myself out the following code. I simply can't understand what I am missing.
With xpath I located the child node from where I want to start extracting data of all its sub-element. I tested the xpath expression (dataExpre3) output in an online tester and it gives me the output as the full xml tree under the node. However, same xpath expression outputs only the list address and not the complete tree under the node in a python code.
Any help on how can I parse child element under node ECUC-CONTAINER-VALUE is really appreciated.
from lxml import etree
arxmlFile = "D:/7_scripts/ArXmlParser/input/EcucValues.arxml"
tree = etree.parse(arxmlFile)
dataExpre3 = "//*[local-name() = 'SUB-CONTAINERS']/*[local-name() = 'ECUC-CONTAINER-VALUE'][1]"
subcontainers = tree.xpath(dataExpre3)
print(subcontainers)

The output in python is:
[<Element {http://autosar.org/schema/r4.0}ECUC-CONTAINER-VALUE at 0x28f8f26a1c0>]
The output in xpath tester is complete xml tree of the first child under node ECUC-CONTAINER-VALUE.
Regards,

A: What you're seeing is the list of Element objects that were selected by xpath().
In this case, it's just one Element with the name {http://autosar.org/schema/r4.0}ECUC-CONTAINER-VALUE. That's the full name with the namespace uri in Clark notation.
If you want to print the serialized tree, try (untested):
print(etree.tostring(subcontainers[0]).decode())


Q: How do i select old date from daterangepicker? I'm using daterangepicker , and I can't select old date from second datepicker section. It shows only from this month.

And There is no arrow clickable on second date picker.
I want that i can select any date , year or month on second datepicker section. There is must js code but i can't figure it out.
Here is my js code
$('.datepicker').daterangepicker({
  autoUpdateInput: false,
  opens: 'left',
  alwaysShowCalendars: true,
  showDropdowns: true,
  minDate: '01/01/2010',
  showOtherMonths: true,
  changeMonth: true,
  locale: {
    cancelLabel: 'Cancel'
  }
});

A: Since its a daterange picker you choose a range.
I guess from the moment you choose the starting date, the ending date cannot be older than the starting one.


Q: SQL How can I return 2 different dates in same query I have a query and what I want to do is return the latest date for 2 columns in the same row. If you look at RowID 1 & 2 I would like to merge both rows. They both have the same Event Type however where they differ is in the isProcessed column one contains 1 and the other 0 value. The LastReceived column should return the latest date where isProcessed is 0 and the LastProcessed column should return the last date where IsProcessed is 1. Right now I have that working but it returns in 2 rows. Row 1 shows the last date of where LastReceived is 0 and Row 2 shows the last date where Lastprocessed is 1. Both LastReceived and LastProcessed come from the column CreatedOn. What I somehow need to do is something like this in the select clause
select MAX(select CreatedOn from mytable where IsProcessed=1) as LastProcessed,
MAX(select CreatedOn from mytable where IsProcessed=0) as LastReceived

This is my query below
with cte as (select distinct EventType,SendingOrganizationID,MAX(CreatedOn) as LastReceived,MAX(CreatedOn) as LastProcessed,case
when SendingOrganizationID = '3yst8' then 'Example 1'
else 'Client Not Found'
END AS ClientName,IsProcessed from mytable
where  isprocessed in(0,1)
group by SendingOrganizationID,EventType,IsProcessed
having datediff(hour, MAX(CreatedOn), getdate()) >= 9)

Select ROW_NUMBER() over (ORDER BY SendingOrganizationID) as RowID,* from cte order by SendingOrganizationID,EventType,IsProcessed

Any suggestions would be great

A: You can use case when:
select EventType,SendingOrganizationID,
MAX(case when isProcessed = 0 then CreatedOn end) as LastReceived,
MAX(case when isProcessed = 1 then CreatedOn end) as LastProcessed
from mytable
group by SendingOrganizationID,EventType;


Q: swift 4: Setting button's constrains to safe area while inside a view I have a return button that is inside a view on the top left corner, and that view is anchored to the top of the safe area.
What I'm trying to set is the button's top and leading constraint to the top and the leading of the safe area, but since the button is inside a view I guess the safe area is not visible to it?
So what can I do to set the top constraint of the button to the top of the safe area rather than the superview that the button is inside? fix the button issue without taking the button outside of the view and make it overlap with the view and sitting its z-index above it.
superview constraints
button constraints
the arrow-shaped button on the top-left corner, and the view colored with navy blue.
iPhone 8 simulator
iPhone X simulator

A: From your images it seems like that you don't set the top constraint of the top view to top safeAreaLayoutGuide instead you set it to superView here

, also you can't set the top of the button to safeArea , as it's only appears for direct subviews of thw main vc's view not to nested subviews


Q: python matrix multiplication check if number of rows of 1st matrix is equal to number of columns of 2nd matrix I need to perform a matrix multiplication between 2 matrices by taking user input. The below code works fine for the multiplication part but if the no. of rows of 1st matrix are not equal to the no. of columns of the 2nd matrix then it should print NOT POSSIBLE and exit. But it still goes on to add the elements of the matrices. What could possibly be wrong in this code & what could be the solution for the same. Any help would be greatly appreciated
def p_mat(M,row_n,col_n):
    for i in range(row_n):
        for j in range(col_n):
            print(M[i][j],end=" ")
        print()

def mat_mul(A_rows,A_cols,A,B_rows,B_cols,B):

    if A_cols != B_rows:
        print("NOT POSSIBLE")

    else:
        C = [[0 for i in range(B_cols)] for j in range(A_rows)]

        for i in range(A_rows) :
            for j in range(B_cols) :
                C[i][j] = 0
                for k in range(B_rows) :
                    C[i][j] += A[i][k] * B[k][j]

        p_mat(C, A_rows, B_cols)

if __name__== "__main__":

    A_rows = int(input("Enter number of rows of 1st matrix: "))
    A_cols = int(input("Enter number of columns of 1st matrix: "))
    B_rows = int(input("Enter number of rows of 2nd matrix: "))
    B_cols = int(input("Enter number of columns of 2nd matrix: "))

    ##### Initialization of matrix A and B #####

    A = [[0 for i in range(B_cols)] for j in range(A_rows)]
    B = [[0 for i in range(B_cols)] for j in range(A_rows)]

    print("Enter the elements of the 1st matrix: ")

    for i in range(A_rows):
        for j in range(A_cols):
            A[i][j] = int(input("A[" + str(i) + "][" + str(j) + "]: "))

    print("Enter the elements of the 2nd matrix: ")

    for i in range(B_rows):
        for j in range(B_cols):
            B[i][j] = int(input("B[" + str(i) + "][" + str(j) + "]:"))

    ##### Print the 1st & 2nd matrices #####

    print("First Matrix : ")
    p_mat(A,A_rows,A_cols)

    print("Second Matrix : ")
    p_mat(B,B_rows,B_cols)

    ### Function call to multiply the matrices ###

    mat_mul(A_rows,A_cols,A,B_rows,B_cols,B)

A: For matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix.
If you want to check the no of rows of 1st matrix and the no. of columns of the 2nd matrix then change the if A_cols != B_rows to if A_rows != B_cols
With your current code, it will print NOT POSSIBLE when A_cols != B_rows which is right.
Ex.
Enter number of rows of 1st matrix: 2
Enter number of columns of 1st matrix: 3
Enter number of rows of 2nd matrix: 2
Enter number of columns of 2nd matrix: 3
Enter the elements of the 1st matrix:
A[0][0]: 1
A[0][1]: 2
A[0][2]: 3
A[1][0]: 4
A[1][1]: 5
A[1][2]: 6
Enter the elements of the 2nd matrix:
B[0][0]:1
B[0][1]:2
B[0][2]:3
B[1][0]:4
B[1][1]:5
B[1][2]:6
First Matrix :
1 2 3
4 5 6
Second Matrix :
1 2 3
4 5 6
NOT POSSIBLE

Another mistake in the code is when you are initialize the Matrices.You are doing
A = [[0 for i in range(B_cols)] for j in range(A_rows)]
B = [[0 for i in range(B_cols)] for j in range(A_rows)]

If the B_cols are smaller than the A_cols when you adding elements in A it will raise IndexError
The same if the B_cols are greater than A_cols when you are adding elements to B will raise IndexError.
Change it to
A = [[0 for i in range(A_cols)] for j in range(A_rows)]
B = [[0 for i in range(B_cols)] for j in range(B_rows)]


Q: Path of assets in CSS files in Symfony 2 Problem
I have a CSS file with some paths in it (for images, fonts, etc.. url(..)).
My path structure is like this:
...
+-src/
| +-MyCompany/
|   +-MyBundle/
|     +-Resources/
|       +-assets/
|         +-css/
|           +-stylesheets...
+-web/
| +-images/
|   +-images...
...

I want to reference my images in the stylesheet.
First Solution
I changed all paths in the CSS file to absolute paths. This is no solution, as the application should (and has to!) be working in a subdirectory, too.
Second Solution
Use Assetic with filter="cssrewrite".
So I changed all my paths in my CSS file to
url("../../../../../../web/images/myimage.png")

to represent the actual path from my resources directory to the /web/images directory. This does not work, since cssrewrite produces the following code:
url("../../Resources/assets/")

which is obviously the wrong path.
After assetic:dump this path is created, which is still wrong:
url("../../../web/images/myimage.png")

The twig code of Assetic:
{% stylesheets
    '@MyCompanyMyBundle/Resources/assets/css/*.css'
    filter="cssrewrite"
%}
<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}

Current (Third) Solution
Since all CSS files end up in /web/css/stylexyz.css, I changed all paths in the CSS file to be relative:
url("../images/myimage.png")

This (bad) solution works, except in the dev environment:
The CSS path is /app_dev.php/css/stylexyz.css and therefore the image path resulting from this is /app_dev.php/images/myimage.png, which results in a NotFoundHttpException.
Is there a better and working solution?

A: I'll post what worked for me, thanks to @xavi-montero.
Put your CSS in your bundle's Resource/public/css directory, and your images in say Resource/public/img.
Change assetic paths to the form 'bundles/mybundle/css/*.css', in your layout.
In config.yml, add rule css_rewrite to assetic:
assetic:
    filters:
        cssrewrite:
            apply_to: "\.css$"

Now install assets and compile with assetic:
$ rm -r app/cache/* # just in case
$ php app/console assets:install --symlink
$ php app/console assetic:dump --env=prod

This is good enough for the development box, and --symlink is useful, so you don't have to reinstall your assets (for example, you add a new image) when you enter through app_dev.php.
For the production server, I just removed the '--symlink' option (in my deployment script), and added this command at the end:
$ rm -r web/bundles/*/css web/bundles/*/js # all this is already compiled, we don't need the originals

All is done. With this, you can use paths like this in your .css files: ../img/picture.jpeg

A: I had the same problem and I just tried using the following as a workaround. Seems to work so far. You can even create a dummy template that just contains references to all those static assets.
{% stylesheets
    output='assets/fonts/glyphicons-halflings-regular.ttf'
    'bundles/bootstrap/fonts/glyphicons-halflings-regular.ttf'
%}{% endstylesheets %}

Notice the omission of any output which means nothing shows up on the template. When I run assetic:dump the files are copied over to the desired location and the css includes work as expected.

A: If it can help someone, we have struggled a lot with Assetic, and we are now doing the following in development mode:

*

*Set up like in Dumping Asset Files in the dev Environmen so in config_dev.yml, we have commented:
#assetic:
#    use_controller: true

And in routing_dev.yml
#_assetic:
#    resource: .
#    type:     assetic

*Specify the URL as absolute from the web root. For example, background-image: url("/bundles/core/dynatree/skins/skin/vline.gif"); Note: our vhost web root is pointing on web/.

*No usage of cssrewrite filter

A: I have came across the very-very-same problem.
In short:

*

*Willing to have original CSS in an "internal" dir (Resources/assets/css/a.css)

*Willing to have the images in the "public" dir (Resources/public/images/devil.png)

*Willing that twig takes that CSS, recompiles it into web/css/a.css and make it point the image in /web/bundles/mynicebundle/images/devil.png

I have made a test with ALL possible (sane) combinations of the following:

*

*@notation, relative notation

*Parse with cssrewrite, without it

*CSS image background vs direct  tag src= to the very same image than CSS

*CSS parsed with assetic and also without parsing with assetic direct output

*And all this multiplied by trying a "public dir" (as Resources/public/css) with the CSS and a "private" directory (as Resources/assets/css).

This gave me a total of 14 combinations on the same twig, and this route was launched from

*

*"/app_dev.php/"

*"/app.php/"

*and "/"

thus giving 14 x 3 = 42 tests.
Additionally, all this has been tested working in a subdirectory, so there is no way to fool by giving absolute URLs because they would simply not work.
The tests were two unnamed images and then divs named from 'a' to 'f' for the CSS built FROM the public folder and named 'g to 'l' for the ones built from the internal path.
I observed the following:
Only 3 of the 14 tests were shown adequately on the three URLs. And NONE was from the "internal" folder (Resources/assets). It was a pre-requisite to have the spare CSS PUBLIC and then build with assetic FROM there.
These are the results:

*

*Result launched with /app_dev.php/

*Result launched with /app.php/

*Result launched with /

So... ONLY
 - The second image
 - Div B
 - Div C
are the allowed syntaxes.
Here there is the TWIG code:

            {% stylesheets 'bundles/commondirty/css_original/container.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    {# First Row: ABCDEF #}

            <link href="{{ '../bundles/commondirty/css_original/a.css' }}" rel="stylesheet" type="text/css" />
            <link href="{{ asset( 'bundles/commondirty/css_original/b.css' ) }}" rel="stylesheet" type="text/css" />

            {% stylesheets 'bundles/commondirty/css_original/c.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets 'bundles/commondirty/css_original/d.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/public/css_original/e.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/public/css_original/f.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    {# First Row: GHIJKL #}

            <link href="{{ '../../src/Common/DirtyBundle/Resources/assets/css/g.css' }}" rel="stylesheet" type="text/css" />
            <link href="{{ asset( '../src/Common/DirtyBundle/Resources/assets/css/h.css' ) }}" rel="stylesheet" type="text/css" />

            {% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/i.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/j.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/assets/css/k.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/assets/css/l.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

                    A

                    B

                    C

                    D

                    E

                    F

                    G

                    H

                    I

                    J

                    K

                    L

The container.css:
div.container
{
    border: 1px solid red;
    padding: 0px;
}

div.container img, div.container div
{
    border: 1px solid green;
    padding: 5px;
    margin: 5px;
    width: 64px;
    height: 64px;
    display: inline-block;
    vertical-align: top;
}

And a.css, b.css, c.css, etc: all identical, just changing the color and the CSS selector.
.a
{
    background: red url('../images/devil.png');
}

The "directories" structure is:
Directories

All this came, because I did not want the individual original files exposed to the public, specially if I wanted to play with "less" filter or "sass" or similar... I did not want my "originals" published, only the compiled one.
But there are good news. If you don't want to have the "spare CSS" in the public directories... install them not with --symlink, but really making a copy. Once "assetic" has built the compound CSS, and you can DELETE the original CSS from the filesystem, and leave the images:
Compilation process

Note I do this for the --env=prod environment.
Just a few final thoughts:

*

*This desired behaviour can be achieved by having the images in "public" directory in Git or Mercurial and the "css" in the "assets" directory. That is, instead of having them in "public" as shown in the directories, imagine a, b, c... residing in the "assets" instead of "public", than have your installer/deployer (probably a Bash script) to put the CSS temporarily inside the "public" dir before assets:install is executed, then assets:install, then assetic:dump, and then automating the removal of CSS from the public directory after assetic:dump has been executed. This would achive EXACTLY the behaviour desired in the question.

*Another (unknown if possible) solution would be to explore if "assets:install" can only take "public" as the source or could also take "assets" as a source to publish. That would help when installed with the --symlink option when developing.

*Additionally, if we are going to script the removal from the "public" dir, then, the need of storing them in a separate directory ("assets") disappears. They can live inside "public" in our version-control system as there will be dropped upon deploy to the public. This allows also for the --symlink usage.
BUT ANYWAY, CAUTION NOW: As now the originals are not there anymore (rm -Rf), there are only two solutions, not three. The working div "B" does not work anymore as it was an asset() call assuming there was the original asset. Only "C" (the compiled one) will work.
So... there is ONLY a FINAL WINNER: Div "C" allows EXACTLY what it was asked in the topic: To be compiled, respect the path to the images and do not expose the original source to the public.
The winner is C

A: The cssrewrite filter is not compatible with the @bundle notation for now. So you have two choices:

*

*Reference the CSS files in the web folder (after: console assets:install --symlink web)
{% stylesheets '/bundles/myCompany/css/*." filter="cssrewrite" %}

*Use the cssembed filter to embed images in the CSS like this.
{% stylesheets '@MyCompanyMyBundle/Resources/assets/css/*.css' filter="cssembed" %}

A: I offen manage css/js plugin with composer which install it under vendor.
I symlink those to the web/bundles directory, that's let composer update bundles as needed.
exemple:
1 - symlink once at all (use command fromweb/bundles/
ln -sf vendor/select2/select2/dist/ select2

2 - use asset where needed, in twig template :
{{ asset('bundles/select2/css/fileinput.css) }}

Regards.


Q: Core Data Fetch To Many I am trying to fetch all categories, and their sub categories, and display them all in a table.  I know how to fetch all categories, but I need to fetch all sub categories, and sort them by category using a fetch results controller.  Any ideas of suggestions?

A: You can create a fetched results controller that fetches SubCategory entities and groups them into sections according to the Category:
// Fetch "SubCategory" entities:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SubCategory"];

// First sort descriptor for grouping the cells into sections, sorted by category name:
NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"category.name" ascending:YES];
// Second sort descriptor for sorting the cells within each section:
NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObjects:sort1, sort2, nil];

self.fetchedResultsController = [[NSFetchedResultsController alloc]
                                        initWithFetchRequest:request
                                        managedObjectContext:context
                                          sectionNameKeyPath:@"category.name"
                                                   cacheName:nil];

[self.fetchedResultsController setDelegate:self];
NSError *error;
BOOL success = [self.fetchedResultsController performFetch:&error];

Then you can use the usual table view data source methods as described in the NSFetchedResultsController Class Reference.
This gives you a table view with one table view section for each category.

A: so, you have the categories in the fetchedResultsController.fetchedObjects
since each subCategory is essentially contained in the Category you can access each by calling [Category valueForKey:@"subCategory"
this will give you an NSSet that you can then sort out (to an NSArray) and use as data for your tableView.
It won't be contained in a fetchedResultsController though.

A: If you have the option u can do it in other way also if u like.
Take all The Category objects in arrayOfCategories
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection (NSInteger)section:

{
    Category *cat = [ arrayOfCategories objectAtIndex:indexPath.row]

   if(arrayToHoldObjects.count > 0)

{

[arrayToHoldObjects removeAllObject];
}

for(Subcategory *sub in Category.subcategory)

{
   [arrayToHoldObjects addObject:sub];

}

  return arrayToHoldObjects.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  Category *cat = [ arrayOfCategories objectAtIndex:indexPath.row]

   if(arrayToHoldObjects.count > 0)

{

[arrayToHoldObjects removeAllObject];
}

for(Subcategory *sub in Category.subcategory)

{
   [arrayToHoldObjects addObject:sub];

}

   Subcategory *sub = [arrayToHoldObjects objectAtIndexPath.row]

   for(int k =0 ; k < arrayToHoldObjects .count; k++)
  {

    // do what ever u like with sub

     return cell;

   }

}


Q: Retain submitted data through refreshes I want to retain $orderby and $orderSort (within the query) when I refresh the page or press the links at the bottom of the page to move to next page or previous page.
I have tried attaching orderby and orderSort to sessions but that didn't work due to the query - it always reverts back to Name and ASC from the else statement which seems like an issue with isset($_POST['submit']) but I have tried without it the same problem still occurs.
How do I retain my query (so long as the selections are not changed) as I go to the next page or previous page?
Top PHP portion:
//Next Page
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
 $startrow = 0;
} else {
$startrow = (int)$_GET['startrow'];
}
//when options are selected/submitted
if(isset($_POST['submit']))
    {
        if($_POST['select'] == "EventType")
        {
            $orderby = $_POST['select'];
            if($_POST['otherType'] != "Select an Event") {
            $EventType = 'WHERE `' . $orderby . '`="' . $_POST["otherType"] . '"';
            }
        }
        else
        {
            $orderby = $_POST['select'];
        }
        $orderSort = $_POST['agree'];
    }
else
{
    $orderby = "Name";
    $orderSort = "ASC";
}

if ($stmt = $local->prepare("SELECT * FROM importdata $EventType ORDER BY `$orderby` $orderSort LIMIT     ?,10")) {
$stmt->bind_param('i', $startrow);
$stmt->execute();
$Recordset1 = $stmt->get_result();
$row_Recordset1 = $Recordset1->fetch_assoc();
$stmt->close();
}

Submit Form:
<form id="form1" name="form1" method="post" enctype="multipart/form-data">
  Order By:
  <select name="select" id="selectType">
    <option value="EventType">Event</option>
    <option value=" Name"selected="selected">Race Name</option>
  </select>
      <input type="radio" name="agree" value="ASC" checked>Ascend
    <input type="radio" name="agree" value="DESC">Descend

      <input type="submit" name="submit" value="Submit">
</form>

Bottom PHP for next page/previous page
<?php
    $prev = $startrow - 10;
    if ($prev >= 0)
    echo 'Previous ';
    echo ' Next';
?>

A: You'll have to write the parameters (orderBy and such) into every link, because HTTP is a stateless protocol. This is very tedious, so I suggest to look for a framework that does that for you.
Sessions should work too and for a simple application it might be an easier soultion. How exactly did you store the session variables?

A: I suggest something like this:
// Get our defaults for these variables.
$orderBy = isset($_SESSION['orderBy']) ? $_SESSION['orderBy'] : 'Name';
$orderSort = isset($_SESSION['orderSort']) ? $_SESSION['orderSort'] : 'ASC';

// When options are selected/submitted
if (isset($_POST['submit'])) {
    if ($_POST['select'] == "EventType") {
        $orderby = $_POST['select'];

        if ($_POST['otherType'] != "Select an Event") {
            $EventType = 'WHERE `' . $orderby . '`="' . $_POST["otherType"] . '"';
        }
    } else {
        $orderby = $_POST['select'];
    }

    $orderSort = $_POST['agree'];

    // Set our session variables for next time when we set our defaults.
    $_SESSION['orderBy'] = $orderBy;
    $_SESSION['orderSort'] = $orderSort;
}


Q: Error: undefined index? I get this array from a function (var_dump()):
...{ [0]=> string(7) "user_id" } [1]=> array(1) { [0]=> string(7) "user_id" } [2]...

When I try to separate the values with:
$var2 = $var['user_id']
I get the error "undefined index 'user_id'", even though, as you can see, the name of the value is "user_id", and I've checked my database a hundred times, and that IS the name of the index.
What other possible sources of error are there?
I appreciate any help!
Thank you in advance!
function get_subscribitions($user)
{

$user = mysql_real_escape_string ($user);

  $sql = "SELECT * FROM `subscribe` WHERE subscriber = '$user'";

 $result = mysql_query($sql);

  $rows = array();

  while ($row = mysql_fetch_assoc($result)) {
      $rows[] = $row;
  }

  mysql_free_result($result);

  return $rows;

Can anyone pinpoint where in the above code, I make the mistake leading to this problem?
Thanks.

A: [0] is the index and the data is "user_id"

A: The array key 0 contains a string called 'user_id' but there is no key named 'user_id', hence why you're getting the error.
I suggest you take a look at how you're compiling this data (query results perhaps?).

A: You are mistaken. The structure of the array is like this:
array:
    [0] => array:
        [0] => "user_id"
    [1] => array:
        [0] => "user_id"

You need to access it like this: $var[0][0] and you will get user_id. Most likely you did something wrong when setting up the array.

A: the index is [0]. I don't think you have this structured correctly. The index is the left side of the declaration, the value is the right. You have assigned all values to "user_id" with incremental index.

A: user_id is not an array key (that can be accessed by []), it is an value.
But you can use array_search()
$index = array_search('user_id', $your_array);

var_dump(  $your_array[$index]  );

A: error because the user_id is not an index it's a value having index 0


Q: TITokenField- duplicate records are coming, I am using TITokenField and now i don't want to enter duplicate records.
https://www.cocoacontrols.com/controls/titokenfield
User is able to enter duplicate records.
Can anybody tell me how to handle this.
Thanks


Q: ERROR: #1242 - Subquery returns more than 1 row in the query - MYSQL Below is the MySQL code where a subquery is returned. And I want the subquery to return just one row.
SELECT DISTINCT w.cname
    FROM works w
    WHERE
    (SELECT DISTINCT w.cname, AVG(w.salary)
    FROM works w
    WHERE 1
    GROUP BY w.cname
    )

<

(SELECT DISTINCT w.cname,AVG(w.salary)
FROM works w
WHERE 1
 GROUP BY w.cname
)

MySQL error said:
1242 - Subquery returns more than 1 row

A: First of all, the literal answer: if a subquery you use as an expression returns more than one row, modify it so that it returns at most one row.
I'm going to take a wild guess and say that you want to find workers that earn less than the average salary. The solution would be:
SELECT -- add DISTINCT if needed
  w.cname
FROM
  works w
WHERE
  w.salary < (SELECT AVG(w2.salary) FROM works w2)

Note that the subquery here (SELECT AVG(w2.salary) FROM works w2) will always return a single value, since there is no GROUP BY clause. (Also, since this instance of the works table has nothing to do with the other one, because you're getting something completely unrelated out of it, it's good practice (and required by some DBMS or another) to use a different table alias — hence w2.)
Note that, since you can reference your original table in subqueries, you can use the data in the outer query's FROM clause to filter the subquery. For instance, if you want to return every instance of people earning less than their own average salary:
SELECT DISTINCT
  w.cname, w.salary
FROM
  works w
WHERE
  w.salary < (SELECT AVG(w2.salary) FROM works w2 WHERE w2.cname = w.cname)

Note how the different table aliases (w and w2) matter here. Also, this subquery still returns only one row, because the filter by name is in the WHERE clause — it returns the average of all salary rows matching that particular name, not the average of all salary rows grouped by name. The former is one value (for one particular person), the latter is one value per person (and thus an error).


Q: ArrayAdapter for FragmentList crashes applications This is my code for an android application:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    //Attempting to set the Fragment
    System.err.println("Starting");
    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    System.err.println("Adding the fragment");
    FileBrowser fb = new FileBrowser();
    ft.add(R.id.flFBrowser,fb);
    ft.commit();
    System.err.println("Done");

    fb.test();
}

Where the file browser only has this:
public void test(){
    System.err.println("Entre a test!!!");
    String[] MyList = {"Hello","world","of","the","lists"};
    System.err.println("File Row ID" + Integer.toString(R.layout.file_row));
    ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(), R.layout.file_row, MyList);
    //setListAdapter(aa);
}

The thing is if I comment the ArrayAdapter constructor the program does not crash If I uncomment it, it crashes with the following error:
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): FATAL EXCEPTION: main
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ccr/com.ccr.Main}: java.lang.NullPointerException
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1748)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1764)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at android.app.ActivityThread.access$1500(ActivityThread.java:122)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1002)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at android.os.Looper.loop(Looper.java:132)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at android.app.ActivityThread.main(ActivityThread.java:4025)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at java.lang.reflect.Method.invokeNative(Native Method)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at java.lang.reflect.Method.invoke(Method.java:491)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at dalvik.system.NativeStart.main(Native Method)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): Caused by: java.lang.NullPointerException
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at android.widget.ArrayAdapter.init(ArrayAdapter.java:314)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at com.ccr.FileBrowser.test(FileBrowser.java:13)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at com.ccr.Main.onCreate(Main.java:24)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1712)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804):     ... 11 more

Does any one have any Idea what I could be doing wrong?
Thanks for any help!
UPDATE:
The problem seems to be specifically that getActivity returns null?
Any Idea why this is?


Q: Printing array of specific element C programming:
Was assign to derive values from a text file using File i/o and print array of a specific element instead of everything in the array.
For example:
After accessing the file using File i/o, I use printf(“%s”, readings); and was able to print all the reading in the array. But i want to print a specific element in the array like: printf(“%s”, readings[4]); but nothing is printed when i input this line.


Q: Checking for empty fields on HTML form I am trying to create a form in HTML, and also trying to ensure that any field is not left empty.
Here is the HTML for the form
<form role="form" id="companyDetails" name="companyDetails" method="post" action="saveCompanyDetails.jsp" onsubmit="return false;">

            Company Name
            <input type="text" class="form-control" id="cmpname" name="cmpname">

            Description
            <textarea class="form-control" rows="3" id="desc" name="desc"></textarea>

            Url
            <input type="text" class="form-control" name="url" id="url">

            Email Id
            <input type="text" class="form-control" name="emailid" id="emailid">

            Address
            <textarea class="form-control" rows="3" id="address" name="address"></textarea>

All Links

            Facebook Link
            <input type="text" class="form-control" name="fblink" id="fblink">

            Twitter Link
            <input type="text" class="form-control" name="twlink" id="twlink">

            Linkedin Link
            <input type="text" class="form-control" name="linkinlink" id="linkinlink">

            Download Link
            <input type="text" class="form-control" name="downlink" id="downlink">

            Live Help Link
            <input type="text" class="form-control" name="livehelplink" id="livehelplink">

            Terms & Condition Link
            <input type="text" class="form-control" name="tclink" id="tclink">

            Promotion Link
            <input type="text" class="form-control" name="prolink" id="prolink">

            Sign Up Link
            <input type="text" class="form-control" name="signuplink" id="signuplink">

            Affiliate Link
            <input type="text" class="form-control" name="affiliatelink" id="affiliatelink">

            Game Link
            <input type="text" class="form-control" name="gamelink" id="gamelink">

        <button type="submit" class="btn btn-default" onclick="submitData()">Submit</button>
        <button type="reset" class="btn btn-default">Reset</button>

</form>

Notice that I have a
 tag just below every input field, whose ID value is constructed from the ID of its corresponding input field. For eg. the
 tag below text field cmpname is given ID cmpnameError
Now the JavaScript code for displaying the error message below the text field is given below
function submitData()   {
var elements = document.querySelectorAll('#companyDetails input, #companyDetails textarea');

for (var i = 0; i < elements.length; i++)   {
    if (elements[i].value == "")    {
        var errorElementId = "#" + elements[i].id + "Error";
        // alert("Generated ID is " + errorElementId);
        document.getElementById(errorElementId).style.display = '';
        document.getElementById(errorElementId).innerHTML = "Please enter a value for this field";
        return false;
    }
}
document.forms['companyDetails'].submit();
return true;
}

My problem is that the proper error message is not getting displayed on the form when I click submit.
Can anybody please help me regarding this? Thank you very much in advance.
Here is the JSFiddle link- https://jsfiddle.net/v8ooy2e1/

A: The pound sign is used to select elements with ids using querySelectorAll, but it shouldn't be used with getElementById.
Remove the pound sign here:
var errorElementId = "#" + elements[i].id + "Error";

Should be:
var errorElementId = elements[i].id + "Error";

Working Fiddle

A: You know, assuming IE 10+, you could skip all this javascript fanciness and just use the "required" attribute:
<input type="text" class="form-control" id="cmpname" name="cmpname" required>

That'll invoke the browser supported form validation.

A: Why do you have:
var errorElementId = "#" + elements[i].id + "Error";

Leave out the "#" sign.

A: If you can use jQuery
  var isValid = true;
$("#companyDetails").submit(function(event) {
    $("input").each(function() {
        var element = $(this);
        if (element.val() == "") {
            isValid = false;

        }
    })
    if (!isValid) {
        alert("nopes");

    }
});

FIDDLE