text:
Q: Is time a mathematical entity or there is any demostration of its existence? I an having trouble trying to understand time as a physical entity. We can demonstrate the existence of air, the source of infection, electromagnetism, voltage, amperage, among many other physical entities. We can measure, weigh or see these items but when it gets to time my brain stops.
Does time have a physical manifestation, is it a particle or simply time is a mathematical expression. A constant pushed into formulas?

A: For fundamental questions on time you must refer to proper time, not to coordinate time. That means: Observers are measuring with their respective clocks time periods of worldlines. From such results in the form of coordinate time may always be retrieved the corresponding proper time of the corresponding worldline.
We can distinguish two kinds of worldlines: The spacetime interval of the worldlines of lightlike phenomena such as massless particles and fields is always zero, so they will not help us to understand what (proper) time is. In contrast, mass particles have worldlines with proper time. So when we want to understand what time is, it is sufficient to consider the proper time of mass particles.
The proper time of mass particles is a sort of "pulsebeat" of the particle. The particle has a certain frequency of aging. And this is what (proper) time is. In a second step, we may observe this pulsebeat of the particle, and the respective pulsebeat of all particles. However, the coordinate time we use is the proper time of each particle multiplied by the factors of time dilation - proper time is the time before time dilation, and coordinate time is the time after time dilation.
What we get is our observation, that is a complete coordinate manifold of time measurements of the universe. But each coordinate time measurement can be reduced to the proper time of the corresponding particle.
In one word: There is no common time axis, time is found separately within the different particles, it is their respective duration, their respective aging frequency and their respective proper time.

A: In special relativity, i.e., in physics, spacetime is on a united footing. If you think that space is physical, there is good enough (and unavoidable) reason for you to say that time is physical. The experimental evidence for special relativity being true is tremendous. More strikingly, in general relativity (which makes the GPS work and has been proven incredibly accurate in multiple ways), spacetime is not only physical, it can change, i.e., it is dynamical--in particular, spacetime has $20$ degrees of freedom at each point. So, yes, time is very much physical.


text:
Q: Parsing HTML on Website for Scraping I'm unable to parse the html on this website correctly: https://nwis.waterdata.usgs.gov/usa/nwis/gwlevels/?site_no=332857117043301
I want to extract the line "Latitude  34°02'48.57", Longitude 117°02'09.16". While this shows up in the page source (web developer tools) in line 862, it doesn't show up when I parse via BeautifulSoup. Using the lxml parser does not produce the desired result either.
import requests
import re
from bs4 import BeautifulSoup

page = requests.get('https://nwis.waterdata.usgs.gov/usa/nwis/gwlevels/?site_no=340248117020902')
soup = BeautifulSoup(page.content, 'html.parser')

print (soup.prettify())

My print statement of the page content does not show the latitude/longitude line. How do I adjust my code to scrape this information?

A: import requests
from bs4 import BeautifulSoup

html = requests.get('https://nwis.waterdata.usgs.gov/usa/nwis/gwlevels/?site_no=340248117020902')
soup = BeautifulSoup(html.text, 'lxml')

data = soup.find_all('div', attrs={'align': 'left'})

latitude = ''.join(x.contents[0].split(',')[0] for x in data if 'Latitude' in x.contents[0])
longitude = ''.join(x.contents[0].split(',')[1].strip().replace('\n', '') for x in data if 'Longitude' in x.contents[0])

print(latitude)
print(longitude)

Output:
Latitude  34°02'48.57"
Longitude 117°02'09.16" NAD83

A: How are you searching for that specific content? You can find the data using .findAll('div') and then searching for "Latitude" in the tags' text:
import requests
from bs4 import BeautifulSoup

page = requests.get('https://nwis.waterdata.usgs.gov/usa/nwis/gwlevels/?site_no=340248117020902')
soup = BeautifulSoup(page.content, 'html.parser')

divs = soup.findAll('div')
texts = [div.text for div in divs]

for text in texts:
    if "Latitude" in text:
        data = text

Resulting in a string that just needs a few parsing to get the numbers and assign them to variables:
>>> print(data)
Latitude  34°02'48.57", Longitude 117°02'09.16"
 NAD83

A: That page is pure mess... just use regexp (working example python2):
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
import re

def find(prefix, string):
    return re.search("{} (?:\s+|)(\d+)\&\#176\;(\d+)\'(\d+)\.(\d+)\"".format(prefix), string)

def format_result(result):
    return "{}°{}'{}.{}\"".format(
        result.group(1),
        result.group(2),
        result.group(3),
        result.group(4)
    )

page = requests.get('https://nwis.waterdata.usgs.gov/usa/nwis/gwlevels/?site_no=340248117020902')
found_lat = find('Latitude', page.content)
found_lon = find('Longitude', page.content)
if found_lat and found_lon:
    latitude = format_result(found_lat)
    longitude = format_result(found_lon)
    print('Cords: {} {}'.format(latitude, longitude))

Result:
Cords: 34°02'48.57" 117°02'09.16"

As you can see, you can get each number just like this from found_lat or found_lon:
print(found_lat.group(1)) # 34
print(found_lat.group(2)) # 02
print(found_lat.group(3)) # 48
print(found_lat.group(4)) # 57

Or Latitude or Longitude like this:
print(latitude) # 34°02'48.57"
print(longitude) # 117°02'09.16"

A: It is there. If you run the following code, you will get the Latitude, and you can replicate it for Longitude.
divs = soup.find_all('div')
lat_index = str(divs).find("Latitude")
lat = str(divs)[lat_index:lat_index+22 // 'Latitude\xa0 34°02\'48.57"'

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to store variable within javascript to limit number of http calls? I am using a second party file downloader which returns a progress event.  I can capture the event and call a program on the server to perform an update (for security purposes so I can tell the most recent activity).
I get about 30 events per second all at percent downloaded 1%, then 30 more at 2%, then 30 more at 3%, etc.  I would like to limit my http calls to only once per percentage change, 1%, 2%, 3%, etc.  I would put a hidden field on the page and compare that and update it, but I cannot refresh the page since the download is in progress.
Is there a way to use some type of client side storage within javascript or jquery for this?
In other words, I need to be able to tell when the PercentCurrent value changes from 1 to 2, etc.
My javascript function looks like this:
         function onProgress(PercentTotal, PercentCurrent, Index){
            var xmlhttp;

            //The handler will update the file progress
            if (typeof XMLHttpRequest != 'undefined') {
                xmlhttp = new XMLHttpRequest();
            }
            if (!xmlhttp) {
                throw "Browser doesn't support XMLHttpRequest.";
            }
            var data = "";
            xmlhttp.open("POST", "UpdateProgress.aspx?PercentCurrent=" + PercentCurrent, true);
            //Send the proper header information along with the request
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            //xmlhttp.setRequestHeader("Content-length", data.length);
            xmlhttp.setRequestHeader("Connection", "close");
            xmlhttp.send(data);
        }

Thank you,
 Jim

A: Have a look at jQuery's .data(). It allows you to store data and attach it to a particular DOM element like so:
$('body').data('foo', 52);
$('body').data('foo'); // 52

A: I am not sure to understand your problem. Is the page continously reloaded? If it is not all that you need to do is:
var lastPercent = null; // you need to initialize this when it all starts again.
 function onProgress(PercentTotal, PercentCurrent, Index){
            var xmlhttp;

if (lastPercent == PercentCurrent)
return; //Does nothing if no change occurred.

lastPercent = PercentCurrent;

            //The handler will update the file progress
            if (typeof XMLHttpRequest != 'undefined') {
                xmlhttp = new XMLHttpRequest();
            }
            if (!xmlhttp) {
                throw "Browser doesn't support XMLHttpRequest.";
            }
            var data = "";
            xmlhttp.open("POST", "UpdateProgress.aspx?PercentCurrent=" + PercentCurrent, true);
            //Send the proper header information along with the request
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            //xmlhttp.setRequestHeader("Content-length", data.length);
            xmlhttp.setRequestHeader("Connection", "close");
            xmlhttp.send(data);
        }

A: JavaScript does indeed have variables, you just need to store one in a scope that's accessible to your onProgress code. You may just be able to use a var in the same place onProgress is declared, but a simple and JavaScripty way to make that variable "private" is to use a closure:
var onProgress = (function(){
    var lastSend = 0;

    return function(PercentTotal, PercentCurrent, Index){
        if (Math.floor(PercentCurrent) > lastSend) {
            lastSend = PercentCurrent;
            var xmlhttp…
        }
    }
})();

This'll look a little confusing if you haven't worked with JavaScript much. Here's what's going on:

*

*I create a variable called onProgress

*I create and immediately run an anonymous (unnamed) function, like this: (function(){ … })()

*This function defines a local variable, lastSend, and returns the real onProgress function.

Whenever a function is called in JavaScript, it has access to the scope in which it was created. So, whenever onProgress() is called, it'll have access to the lastSend variable, and can check that progress is has moved past the next whole percent.
Of course, this is a bit ugly, and it can only be used once on a page (since there's only one closure with one lastSend variable. Instead of assigning it to a name, you might pass it directly into the function which calls it, anonymously (see below). Then, a new copy of the function, with a new closure, gets created when you hit downloadFile.

Your original question is tagged jquery. If you are indeed using jQuery on the page, you can simplify the posting of data significantly (down to one line) and make it more compatible, with jQuery.post:
$.post("UpdateProgress.aspx", { PercentCurrent: PercentCurrent });

(This would replace all the XMLHTTPRequest-related code in onProgress.)

So, using a closure and jQuery.post might look like this:
// Not sure what your second-party file downloader looks like
fileDownloader.downloadFile((function(){
    var lastSend = 0;
    return function(PercentTotal, PercentCurrent, Index){
        if (Math.floor(PercentCurrent) > lastSend) {
            lastSend = PercentCurrent;
            $.post("UpdateProgress.aspx", { PercentCurrent: PercentCurrent });
        }
    }
})());


text:
Q: Test Apex Class for Lightning Component I am a new developer with minimum experience for developing lightning components.
I have a LEX component to update case values containing the following Apex Class. Can anyone help me to create a test class? I tried various versions, but none of them are going above 75% of code coverage
public class caseStatisChangeCtrl {@AuraEnabled
public static void updateStatus(case obj,String oId){
    system.debug('obj' + obj);
    case cc = obj;
    cc.Id = oId;
    update cc;
}}

A: Honestly, your code is very strange... Why do you want to update the id of the case by a parameter in your aura component?
Nevertheless, it is pretty easy to test your case though.
@isTest
public class SampleUnitTest {
    @isTest
    public static void testSample() {
        Account acc = new Account();
        acc.Name = 'test acc';
        insert acc;

        Case ca = new Case();
        ca.AccountId = acc.Id;
        insert ca;

        ca.Status = 'New';
        caseStatisChangeCtrl.updateStatus(ca, ca.Id);

        ca = [Select Id, Status From Case Where Id = :ca.Id];
        System.assertEquals('New', ca.Status);
    }
}


text:
Q: "If I was you, I'd wanna be me too" "If I was you, I'd wanna be me too"
This is a line from the song "Me Too" by Meghan Trainor. See lyrics here.
I'm wondering, to whom does "me" refer? Because "if I was you," then "me" could refer to me if I'm you (you), or me right now (not you).
So is it a way of saying:

*

*I like the way I look, so you should want to be me, too.

*I like the way you look, so you should want to be you.

Note: in the context of the song, she's looking in a mirror, but I'm asking as if she is not, in order to create a distinction between "me" and "you".

A: It means something like "I know you admire me and would like to be like me. If I were in your position (not being Meghan), I would also like to be Meghan."
I hope it helps.


text:
Q: drupal_add_css not working I need to use drupal_add_css to call stylesheets onto single Drupal 6 pages. I don't want to edit the main theme stylesheet as there will be a set of individual pages which all need completely new styles - the main sheet would be massive if i put it all in there.
My solution was to edit the page in PHP editor mode and do this:
<?php
drupal_add_css("/styles/file1.css", "theme");
?>

stuff here in html

But when I view source, there is nothing there! Not even a broken CSS link or anything, it's just refusing to add the CSS sheet to the CSS package put into the page head.
Variations don't seem to work either:
drupal_add_css($path = '/styles/file1.css', $type = 'module', $media = 'all', $preprocess = TRUE)

My template header looks like this, I've not changed anything from the default other than adding a custom JavaScript.

    <?php print $head ?>
    <title><?php print $head_title ?></title>
    <?php print $styles ?>
    <?php print $scripts ?>

Why is this function not working?

A: It is not quite clear where you are selecting the template that you have in your example. If you are selecting it from a module then you can just use drupal_add_css in the module rather than the template.
If you have your own theme you can use template_preprocess_page and put logic in there to add the relevant CSS (you can also use it to select the template to use).

A: I have noticed something weird and it might fix your problem:
drupal_add_css( drupal_get_path('theme','themname') . '/working.css','module' ,'all' , false );

drupal_add_css( drupal_get_path('theme','themname') . '/path/to/folder/notworking.css','module' ,'all' , false );

The first one will work ebcause the style it in the main them folder
The second line will not work because the style is in a sub folder !
Edit:
i think it did not work because  i did not write the path the the style file properly :S so please disregard my answer
drupal_add_css( drupal_get_path('theme','test') . '/pages/subpage/style.css','theme');

is working

A: This function wont work in templates. The reason is that the variable $styles which will hold all the stylesheet html will already have been generated at this point, so drupal_add_css wont work as it adds to that. if you want to do this in your theme, you would probably have to add the css file manually
<link rel="stylesheet" ... />

The other way would be to use drupal_add_css in a module, but you might have a hard time adding the correct css files on the pages you want.

A: It's possible to use drupal_add_css() inside your template.php file; this page has a good example of how to do just that.

A: Answer was very much to use the CSS Injector module - great little addon!
Here is an excerpt from its project page:

Allows administrators to inject CSS into the page output based on configurable rules. It's useful for adding simple CSS tweaks without modifying a site's official theme. The CSS is added using Drupal's standard drupal_add_css() function and respects page caching, etc. The 2.x brach leverages CTools so CSS can be included with Feature changes (ie. CSS that improves the look of a View can be packaged with the View).

A: Thanks for the link, wyrmmage. That's very useful. I think the rest of the code in the page is unneccessary. You probably just need these since drupal 6 already automatically check for file existence:
drupal_add_css(path_to_theme() . '/css/yourcss.css', 'theme');
// Add the following to regenerate $styles.
// This is needed for template_preprocess_page() since css is already generated at this point.
$variables['styles'] = drupal_get_css();

A: This code inside template.php works for me:
function alagna_preprocess_page(&$vars) {
        drupal_add_css(path_to_theme() . '/header_1.css', 'theme');
        $vars['css'] = drupal_add_css();
        $vars['styles'] = drupal_get_css();
}

explained:

*

*alagna is the theme name

*header_1.css is the css file required.

A: drupal_add_css is expecting a path relative to base path whereas drupal_get_path does not return the path relative to base path.

global $base_path;
drupal_add_css($base_path . drupal_get_path('module / theme','name') . "/styles/file1.css", "module / theme");

You can choose between module and theme accordingly.

A: Try this
common.inc drupal_get_css($css = NULL)
Parameters
$css: (optional) An array of CSS files. If no array is provided, the default stylesheets array is used instead.
    $css    =   $vars['css'];
// unset the system css files
$unset_css = array
    'modules/system/system.css',
    'modules/system/system-menus.css',
);

foreach($unset_css as $css_f) {
    if(isset($css['all']['module'][$css_f])) {
        unset($css['all']['module'][$css_f]);
    }
}

// add css
$css['all']['theme'][drupal_get_path('theme', 'openpublish_theme') . '/css/style.css'] = true;
$vars['styles'] = drupal_get_css($css);


text:
Q: Query that returns results that are at least a week apart I have a google sheets spreadsheet that has lots of user data, timestamped. This data is entered into the google sheet by administration AND end users via a google form, so the data points don't come in at regular intervals.  I want to be able to query against this datapool, but limit the results shown based a defined amount of time between result.
So say I wanted to query for Bob, I would get 3 results. Is it possible to query this data in a way that it would see the 11\11 result, but disregard the 11\12 result becuase it's within a week of the previous result? Really I'd like to be able to do this for any timeframe.

A: Well it's easy enough to do as an ordinary formula that you can pull down like this, but I don't see a way of doing it as a query or array formula:
=iferror(if(istext(F1),index(A$2:A,match(true,(B$2:B=$F$1),0)),index(A$2:A,match(1,(B$2:B=$F$1)*((A$2:A-F1)>=7),0))))

where the person's name is in F1.

This is a fairly rough outline of an answer, I haven't taken account of any time part of the timestamps. The last two dates are only separated by 6 days, but the formula includes the third to last and the last one as mentioned in my comment because they are separated by 7 days.


text:
Q: RecyclerView row onClick and child button onClick I am using the method from RecyclerView onClick to perform on item click method in recyclerview. But the problem is how to handle child button in the recyclerview? I have perform onclick method in the adapter but still not work, It always perform recyclerview onitemclicklistener first then only perform onclick method from adapter. How to handle it properly?
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
  private OnItemClickListener mListener;

  public interface OnItemClickListener {
    public void onItemClick(View view, int position);

    public void onLongItemClick(View view, int position);
  }

  GestureDetector mGestureDetector;

  public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
    mListener = listener;
    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
            if (child != null && mListener != null) {
                mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
            }
        }
    });
}

  @Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
    View childView = view.findChildViewUnder(e.getX(), e.getY());
    if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
      mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
      return true;
    }
    return false;
  }

  @Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }

  @Override
  public void onRequestDisallowInterceptTouchEvent (boolean disallowIntercept){}
}

A: I have implement OnClick in the Adapter Section... Refer to the below code of my Adapter Class
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
    private Context context;
    List<Video_Details> video;

    public DataAdapter(List<Video_Details> video, Context context) {
        super();
        this.context = context;
        this.video = video;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_row, parent, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final Video_Details videoDetails =  video.get(position);
        String url;
        final String VideoID;

        holder.title.setText(video.get(position).getTitle());

        VideoID= video.get(position).getV_id();
        url = video.get(position).getThumb();

         Glide.with(context)
                 .load(url)
                 .override(150,70)
                 .into(holder.thumb);
       //viewHolder.thumb.setText(android.get(i).getVer());
      //  viewHolder.tv_api_level.setText(android.get(i).getApi());

        holder.vm.setOnClickListener(new View.OnClickListener() {
                                         @Override
                                         public void onClick(View v) {
                                             Toast.makeText(v.getContext(), "You Clicked"+video.get(position).getV_id(), Toast.LENGTH_SHORT).show();
                                             Intent intent = new Intent(v.getContext(),Play_Video.class);
                                             intent.putExtra("VideoId",(video.get(position).getV_id()));
                                             intent.putExtra("Title",(video.get(position).getTitle()));
                                             v.getContext().startActivity(intent);

                                         }
                                     }

        );
    }

    @Override
    public int getItemCount() {
        return video.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        public TextView title;
        public ImageView thumb;
        public String videoid;
        public View vm;
        public ViewHolder(View view) {
            super(view);
            vm = view;
            title = (TextView)view.findViewById(R.id.title);
            thumb = (ImageView) view.findViewById(R.id.thumb);

            //tv_version = (TextView)view.findViewById(R.id.tv_version);
            //tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);

        }
    }

}


text:
Q: Printing an NSString What's the correct way to print an NSString in Objective-C? A lot of examples use NSLog(), but according to the documentation:

NSLog is a FoundationKit function for printing debug statements to the console.
  ...
  NSLog works basically like:
    fprintf(stderr, format_string, args ...);

Which to me is a bit like the _TRACE macro in Win32/C++. I don't want to print to stderr, I want to print to stdout.  There are people who suggest using printf() as follows:
printf("%s", [str cStringUsingEncoding:NSUTF8StringEncoding]);

But this seems like an extra level on indirection to get the NSString printed, and it doesn't "feel" like the solution.

A: C string (UTF8String) is a pointer to a structure inside the string object.
NSString *str = @"Hello, World.";
printf("%s\n", [str UTF8String]);

A: I think you'll find these adequate for your needs:
// print to stdout
static void NSPrint(NSString *format, ...) {
    va_list args;
    va_start(args, format);

    NSString *string = [[NSString alloc] initWithFormat:format arguments:args];

    va_end(args);

    fprintf(stdout, "%s\n", [string UTF8String]);

#if !__has_feature(objc_arc)
    [string release];
#endif
}

// print to stderr
static void NSPrintErr(NSString *format, ...) {
    va_list args;
    va_start(args, format);

    NSString *string = [[NSString alloc] initWithFormat:format arguments:args];

    va_end(args);

    fprintf(stderr, "%s\n", [string UTF8String]);

#if !__has_feature(objc_arc)
    [string release];
#endif
}

A: You should use the custom file handler or write a macro yourself.
Tip: when NSLog prints out an object it uses object's debugDescription method. You could override this method for your custom NSObject subclasses to print custom debugInfo to stdout.

A: Spewing stuff to stdout is actually a pretty rare thing to do in Cocoa, given that almost all projects are GUI in nature.   There are relatively few projects that are built as command line tools or otherwise need to deal with stdout.
However, the Foundation does provide the means to write to stdout. Specifically, NSFileHandle has fileHandleWithStandardOutput which gives you a file handle that can write to stdout.
From there, it is a matter of converting the NSString to an NSData and writing it.
Quite a few steps, but easily wrapped up in a reusable function:
void MyLog(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *formattedString = [[NSString alloc] initWithFormat: format
                                                  arguments: args];
    va_end(args);
    [[NSFileHandle fileHandleWithStandardOutput]
        writeData: [formattedString dataUsingEncoding: NSNEXTSTEPStringEncoding]];
    [formattedString release];
}

A: Well this is the solution.
Since printf is a pure C function, it won't recognize the Objective-C objects. (NSLog's formatter is distinct from printf's one.) Therefore, you have to convert it into a C string before formatting.
BTW you can use [str UTF8String] instead of [str cStringUsingEncoding:NSUTF8StringEncoding].

A: I just do:
define NSPrintf(...)   printf( "%s", [[NSString stringWithFormat: __VA_ARGS__] UTF8String] )

Then i can use it as:
NSPrintf( @"Sorry %@, I can't do that\n", name );


text:
Q: Is it possible to represent a type similar to ArrayList> as as OData Entity? I'm creating an OData REST Service to provide read-only access to some values in a database, the values are Strings, however there can be an arbitrary amount of Rows and Columns of them. Here is my current schema:
<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
<edmx:DataServices>
<Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="olingo.server">
<EntityType Name="Form">
<Key>
<PropertyRef Name="FormId"/>
</Key>
<Property Name="FormId" Type="Edm.Int32"/>
<Property Name="Name" Type="Edm.String"/>
<Property Name="Description" Type="Edm.String"/>
<Property Name="UUID" Type="Edm.Guid"/>
<Property Name="Rows" Type="Collection(olingo.server.Cell)"/>
</EntityType>
<ComplexType Name="Cell">
<Property Name="Cell" Type="Collection(Edm.String)"/>
</ComplexType>
<EntityContainer Name="Container">
<EntitySet Name="Forms" EntityType="olingo.server.Form"/>
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>

This looks correct to me, Rows are defined as a Collection of Cell types, and Cell is defined as a Collection of Strings. So we have Collection(Collection(String)) if I'm understanding this correctly.
So now I'm trying to use some dummy data for testing, but no matter what I do, Rows comes back null, like so
<d:Rows m:null="true"/>

Here's the functions related to generating the dummy data
private EntityCollection createForms() {
    EntityCollection entitySet = new EntityCollection();
    Entity el = new Entity()
        .addProperty(createPrimitive("FormId", 1))
        .addProperty(createPrimitive("Name", "New Test"))
        .addProperty(createPrimitive("Description", "Test"))
        .addProperty(createPrimitive("UUID", UUID.fromString("ef35f489-339a-4b41-a5d2-cb2426ed6a77")))
        .addProperty(createRow(Arrays.asList("1","1","1","Test 2","blue","rabbit","blah","06/12/2020")));
    el.setId(createId(JPEdmProvider.ES_FORMS_NAME, 1));
    entitySet.getEntities().add(el);

    el = new Entity()
        .addProperty(createPrimitive("FormId", 2))
        .addProperty(createPrimitive("Name", "Space Shuttle"))
        .addProperty(createPrimitive("Description", "Lego Space Shuttle"))
        .addProperty(createPrimitive("UUID", UUID.fromString("f44173d8-c319-482e-b078-03b18ce7827f")))
        .addProperty(createRow(Arrays.asList("1","1","1","Test 2","blue","rabbit","blah","06/12/2020")));
    el.setId(createId(JPEdmProvider.ES_FORMS_NAME, 2));
    entitySet.getEntities().add(el);

    for (Entity entity:entitySet.getEntities()) {
      entity.setType(JPEdmProvider.ET_FORM.getFullQualifiedNameAsString());
    }
    return entitySet;
  }

  private Property createRow(final List<String> data) {
    ComplexValue complexValue=new ComplexValue();
    List<Property> addressProperties = complexValue.getValue();

    data.forEach((str) -> {
        addressProperties.add(createPrimitive("Data", str));
      });
    return new Property(null, "Cell", ValueType.COMPLEX, complexValue);
  }

  private Property createPrimitive(final String name, final Object value) {
    return new Property(null, name, ValueType.PRIMITIVE, value);
  }

Any help would be appreciated, thanks!


text:
Q: Count and list all posts user has posted in all categories I have just discovered this awesome wordpress function
<?php echo 'Number of posts published by user: ' . count_user_posts( ); ?>

Im busy making a graph which displays on a pie chart how many posts the user has done per category. (chars.js)
Is there any way to make a loop almost where i could get the values for each category the user has posted in.
Id like to future proof it so if more categories are added i dont have to go and write something like this
<?php echo 'Number of posts published by user: ' . count_user_posts( 5 ); ?>
<?php echo 'Number of posts published by user: ' . count_user_posts( 7 ); ?>
<?php echo 'Number of posts published by user: ' . count_user_posts( 8 ); ?>

Is there a way where i can just get a category breakdown of how many posts a user has posted in all categories
Thanks for any help

A: Try this code:
Just set which type of user's do you want at array:
<?php $args = array(
    'blog_id'      => $GLOBALS['blog_id'],
    'role'         => 'subscriber',//"Super Admin" or "Administrator" or "Editor" or "Author" or "Contributor"
    'meta_key'     => '',
    'meta_value'   => '',
    'meta_compare' => '',
    'meta_query'   => array(),
    'include'      => array(),
    'exclude'      => array(),
    'orderby'      => 'login',
    'order'        => 'ASC',
    'offset'       => '',
    'search'       => '',
    'number'       => '',
    'count_total'  => false,
    'fields'       => 'all',
    'who'          => ''
 );

php get_users( $args );

foreach ($blogusers as $user) { ?>
        <li>
            <?php $user_id = $user->ID ?>
            <?php echo 'Number of posts published by user: ' . count_user_posts( $user_id ); ?>
        </li>
<?php } ?>

Thanks.

A: I think you are misunderstanding the count_user_posts function. It's argument is for user id and not for category id.
Anyways, once you have the desired user id (if i understood well, you want to display the post count for every category where the user was the post author) you can do something like this:
$user_id = 124;

/* Get all categories */

$categories = get_terms("category");

/* Loop for each category to count the posts of the user */
foreach($categories as $category)
{
   $cat_name = $category->name;
   $cat_id = $category->term_id;
   $post_count = count(get_posts("cat=$cat_id&post_author=$user_id"));

   echo "The user $user_id has $post_count posts in the $cat_name category";
}

A: Here is the completed code, thanks for the help everyone
<script type="text/javascript">
var pieData = [
                            <?php
                                $user_id = get_query_var('author');

                                $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');

                                //get all posts from author
                                $args = array(
                                    'post_type' => 'post',
                                    'author'=> $queried_object->ID
                                );

                                $the_query = new WP_Query( $args );

                                if ( $the_query->have_posts() ) :

                                    while ( $the_query->have_posts() ) : $the_query->the_post();

                                        //put categories in array
                                        $cat = get_the_category( get_the_ID() );
                                        $terms[] = $cat[0]->term_id;

                                    endwhile;

                                    wp_reset_query();
                                endif;

                                //count matching categories (array vals)
                                $countVal = array_count_values($terms);
                                foreach($countVal as $count){

                                    $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];

                                    echo "  {
                                            value: ".$count.",
                                            color:'".$color."'
                                            },";
                                }

                            ?>
                            ]
                            var myPie = new Chart(document.getElementById("piec").getContext("2d")).Pie(pieData);
                        </script>


text:
Q: Хлебные крошки битрикс выводят неправильные ссылки У меня есть структура инфоблоков, выглядит вот так.

По идеи если я нахожусь на сайте в разделе Линии , то навигационная цепочка должна выглядить вот так
Категории / Красота / Линии

Если например в разделе Здоровье , то вот так
Категории / Здоровье

Но  у меня на всех сраницах выводится вот такое.

То есть берутся все инфоблоки вообще , все возможные пути , и выводятся на экран. Как будто я одновременно нахожусь на 4-х страницах.
Почему так происходит? И как это исправить?
Вызов компонента
  <?$APPLICATION->IncludeComponent(
            "bitrix:breadcrumb",
            "breadcrumb2019",
            array(
                "START_FROM" => "0",
                "PATH" => "",
                "SITE_ID" => "-",
                "COMPONENT_TEMPLATE" => "breadcrumb2019"
            ),
            false
        );?>

Шаблон
<?php
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();

/**
 * @global CMain $APPLICATION
 */

global $APPLICATION;
//echo '
';
//var_dump($arResult);
//exit();
//delayed function must return a string
if(empty($arResult))
    return "";

$strReturn = '';

//we can't use $APPLICATION->SetAdditionalCSS() here because we are inside the buffered function GetNavChain()
$css = $APPLICATION->GetCSSArray();

if(!is_array($css) || !in_array("/bitrix/css/main/font-awesome.css", $css))
{
    $strReturn .= '<link href="'.CUtil::GetAdditionalFileURL("/bitrix/css/main/font-awesome.css").'" type="text/css" rel="stylesheet" />'."\n";
}

$strReturn .= '';

$itemSize = count($arResult);
for($index = 0; $index < $itemSize; $index++)
{
    $title = htmlspecialcharsex($arResult[$index]["TITLE"]);
    $arrow = ($index > 0? '' : '');

    if($arResult[$index]["LINK"] <> "" && $index != $itemSize-1)
    {
        $strReturn .= '

                '.
                    $title.
                '';

    }
    else
    {
        $strReturn .= '

                '.$title.'';

    }
}

$strReturn .= '';

return $strReturn;


text:
Q: Jenkins: Seting up mail notifications I have deployed Jenkins in OpenShift and I want to receive mail notification when my project fails. I have this config:

And when I send test mail I get this error:

javax.mail.AuthenticationFailedException: 534-5.7.14
   Please log in via your web
  browser and 534-5.7.14 then try again. 534-5.7.14  Learn more at 534
  5.7.14  https://support.google.com/mail/answer/78754 32sm10514455qkp.11 - gsmtp
at
  com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:809)
    at
  com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:752)
    at
  com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:669)
    at javax.mail.Service.connect(Service.java:317)     at
  javax.mail.Service.connect(Service.java:176)  at
  javax.mail.Service.connect(Service.java:125)  at
  javax.mail.Transport.send0(Transport.java:194)    at
  javax.mail.Transport.send(Transport.java:124)     at
  hudson.tasks.Mailer$DescriptorImpl.doSendTestMail(Mailer.java:522)    at
  sun.reflect.GeneratedMethodAccessor592.invoke(Unknown Source)     at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)     at
  org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:298)
    at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:161)    at
  org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:96)
    at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:121)   at
  org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:53)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)  at
  org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)  at
  org.kohsuke.stapler.MetaClass$6.doDispatch(MetaClass.java:249)    at
  org.kohsuke.stapler.NameB

I write the right password, so it is not the error.


text:
Q: How to select words of equal max length from a text document I am trying to write a program to read a text document and output the longest word in the document. If there are multiple longest words (i.e., all of equal length) then I need to output them all in the same order in which they occur. For example, if the longest words were dog and cat your code should produce:
dog cat
I am having trouble finding out how to select numerous words of equal max length and print them. This is as far as I've gotten, I am just struggling to think of how to select all words with equal max length:
open the file for reading
fh = open('poem.txt', 'r')

longestlist = []
longestword = ''

for line in fh:
    words = (line.strip().split(' '))
    for word in words:
        word = ''.join(c for c in word if c.isalpha())
        if len(word) > (longestword):
            longest.append(word)

for i in longestlist:
    print i

A: Ok, first off, you should probably use a with as statement, it just simplifies things and makes sure you don't mess up. So
fh = open('poem.txt', 'r')
becomes
with open('poem.txt','r') as file:
and since you're just concerned with words, you might as well use a built-in from the start:
    words = file.read().split()

Then you just set a counter of the max word length (initialized to 0), and an empty list.  If the word has broken the max length, set a new maxlength and rewrite the list to include only that word.  If it's equal to the maxlength, include it in the list.  Then just print out the list members.  If you want to include some checks like .isalpha() feel free to put it in the relevant portions of the code.
maxlength = 0
longestlist = []
for word in words:
    if len(word) > maxlength:
        maxlength = len(word)
        longestlist = [word]
    elif len(word) == maxlength:
        longestlist.append(word)
for item in longestlist:
    print item

-MLP

A: What you need to do is to keep a list of all the longest words you've seen so far and keep the longest length. So for example, if the longest word so far has the length 5, you will have a list of all words with 5 characters in it. As soon as you see a word with 6 or more characters, you will clear that list and only put that one word in it and also update the longest length. If you visited words with same length as the longest you should add them to the list.
P.S. I did not put the code so you can do it yourself.

A: TLDR
Showing the results for a file named poem.txt whose contents are:
a dog is by a cat to go hi
>>> with open('poem.txt', 'r') as file:
...   words = file.read().split()
...
>>> [this_word for this_word in words if len(this_word) == len(max(words,key=len))]
['dog', 'cat']

Explanation
You can also make this faster by using the fact that <file-handle>.read.split() returns a list object and the fact that Python's max function can take a function (as the keyword argument key.) After that, you can use list comprehension to find multiple longest words.
Let's clarify that. I'll start by making a file with the example properties you mentioned,

For example, if the longest words were dog and cat your code should produce:
dog cat

{If on Windows - here I specifically use cmd}
>echo a dog is by a cat to go hi > poem.txt

{If on a *NIX system - here I specifically use bash}
$ echo "a dog is by a cat to go hi" > poem.txt

Let's look at the result of the <file-handle>.read.split() call. Let's follow the advice of @MLP and use the with open ... as statement.
{Windows}
>python

or possibly (with conda, for example)
>py

{*NIX}
$ python3

From here, it's the same.
>>> with open('poem.txt', 'r') as file:
...   words = file.read().split()
...
>>> type(words)
<class 'list'>

From the Python documentation for max

max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])
Return the largest item in an iterable or the largest of two or more arguments.
If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.
There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.
If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc).
New in version 3.4: The default keyword-only argument.
Changed in version 3.8: The key can be None.

Let's use a quick, not-so-robust way to see if we meet the iterable requirement (this SO Q&A gives a variety of other ways).
>>> hasattr(words, '__iter__')
True

Armed with this knowledge, and remembering the caveat, "If multiple items are maximal, the function returns the first one encountered.", we can go about solving the problem. We'll use the len function (use >>> help(len) if you want to know more).
>>> max(words, key=len)
'dog'

Not quite there. We just have the word. Now, it's time to use list comprehension to find all words with that length. First getting that length
>>> max_word_length = len(max(words, key=len))
>>> max_word_length
3

Now for the kicker.
>>> [this_word for this_word in words if len(this_word) == len(max(words,key=len))]
['dog', 'cat']

or, using the commands from before, and making things a bit more readable
>>> [this_word for this_word in words if len(this_word) == max_word_length]
['dog', 'cat']

You can use a variety of methods  you'd like if you don't want the list format, i.e. if you actually want
dog cat
but I need to go, so I'll leave it where it is.


text:
Q: vertical arrow in chemistry mechanism I have decided to mark down the mechanism that I have learnt. However, I have got some problem.
I would like to use a vertical arrow on the second step but I do not know any command that can form a vertical arrow. Also, I would like to ask why part of my command does not count as command in the question part?
\documentclass[12pt,a4paper]{report}

\usepackage{chemfig}

\usepackage[version=4]{mhchem}

\begin{document}

\title{mechanism}

\maketitle

\newpage

\section*{addition of hydrogen halide to alkene}

\begin{center}

\schemestart
    \chemfig{-[:-60]C(-[:240])=_[@{a1}]C(-[:60])(-[:-60])}
    \arrow{0}[,0]\+
    \chemfig{@{a2}H-[@{a3}]@{b1}X@{z}}
    \arrow(.mid east--.mid west)
    \chemfig{-C(-[:90]H)(-[:-90])-@{b2}\chemabove{C}{\oplus}(-[:-90])(-)}
    \arrow{0}[,0]\+
    \chemfig{@{b3}\charge{180=\:}{X}\chemright{X}{\ominus}}
    \schemestop
    \chemmove{
        \draw(a1)..controls +(100:5mm) and +(145:5mm)..(a2);
        \draw(a3)..controls +(100:5mm) and +(145:5mm).. (b1);
        \draw(b3)..controls +(100:5mm) and +(45:5mm).. (b2);
    }

\end{center}

\end{document}

A: As mentioned in the comment vertical arrows are drawn with A\arrow[90]B.
In order to arrange the arrow to the plus sign see example below:
\documentclass[border=1cm]{standalone}

\usepackage{chemfig}

\begin{document}

    \schemestart
    A\subscheme{\+}BCDEF \arrow G
    \arrow(@c2--)[-90]H
    \schemestop

\end{document}

Taken together in your code:
\documentclass[12pt,a4paper]{report}

\usepackage{chemfig}

\usepackage[version=4]{mhchem}

\begin{document}

    \title{mechanism}

    \maketitle

    \newpage

    \section*{addition of hydrogen halide to alkene}

    \begin{center}

        \schemestart
        \chemfig{-[:-60]C(-[:240])=_[@{a1}]C(-[:60])(-[:-60])}
        \arrow{0}[,0]\+
        \chemfig{@{a2}H-[@{a3}]@{b1}X@{z}}
        \arrow
        \chemfig{-C(-[:90]H)(-[:-90])-@{b2}\chemabove{C}{\oplus}(-[:-90])(-)}
        \arrow{0}[,0]\subscheme{\+}
        \chemfig{@{b3}\charge{180=\:}{X}\chemright{X}{\ominus}}
        \arrow(@c5--)[-90]
        \chemfig{-C(-[:90]H)(-[:-90])-C(-[:90]Y)(-[:-90])-}
        \schemestop
        \chemmove{
            \draw(a1)..controls +(100:5mm) and +(145:5mm)..(a2);
            \draw(a3)..controls +(100:5mm) and +(145:5mm).. (b1);
            \draw(b3)..controls +(100:5mm) and +(45:5mm).. (b2);
        }

    \end{center}

\end{document}

A: Do you want something like this? Using \subscheme helps position the arrow in the center of each reaction step.
\begin{center}

        \schemestart
%
        \subscheme{
        \chemfig{-[:-60]C(-[:240])=_[@{a1}]C(-[:60])(-[:-60])}
        \arrow{0}[,0]\+
        \chemfig{@{a2}H-[@{a3}]@{b1}X@{z}}
        }
%
        \arrow{->}[270,1]
%
        \subscheme{
        \chemfig{-C(-[:90]H)(-[:-90])-@{b2}\chemabove{C}{\oplus}(-[:-90])(-)}
        \arrow{0}[,0]\+
        \chemfig{@{b3}\charge{90:1pt=\:,45:3pt=$\ominus$}{X}}
        }
%
\arrow{->}[270,1]
%
        \chemfig{C(-[2]H)(-[4])(-[6])-C(-[2]X)(-[0])(-[6])}
        \schemestop
        \chemmove{
            \draw[red,shorten <=1pt,shorten >=1pt](a1)..controls +(100:5mm) and +(145:5mm)..(a2);
            \draw[red,shorten <=1pt,shorten >=1pt](a3)..controls +(100:5mm) and +(145:5mm).. (b1);
            \draw[red,shorten <=3pt,shorten >=1pt](b3)..controls +(90:8mm) and +(45:8mm).. (b2);
        }

    \end{center}


text:
Q: Failed to load JavaHL Library when opening Eclipse What does mean this when I open Eclipse?
Failed to load JavaHL Library.
These are the errors that were encountered:
no libsvnjavahl-1 in java.library.path
no svnjavahl-1 in java.library.path
no svnjavahl in java.library.path
java.library.path = /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib

I can't even commit my work in SVN. I get:
org.apache.subversion.javahl.ClientException: svn: E160013: Commit failed (details follow):
svn: E160013: '/svn/XXX/src' path not found: 404 Not Found (https://...)
org.apache.subversion.javahl.ClientException: svn: E160013: Commit failed (details follow):
svn: E160013: '/svn/XXX/src' path not found: 404 Not Found (https://...)

A: the easiest way to solve the problem is to re-install subclipse! seems there is some issue in your JavaHL libraries which is required by subclipse to work with SVN.
Update site for subclipse:
http://subclipse.tigris.org/update_1.8.x/

A: basically what I did was:
copy the class content to text file
remove this class from project
commit changes to SVN
then create "new" class and commit.


text:
Q: NHibernate IDataBaseSchema.GetTableMetadata method take a datarow. How can I use this method? I'm trying to verify a table gets created. I'm using SQLite and NHibernate.
new SchemaExport(_configuration)
            .Execute(true, true, false, _session.Connection, Console.Out);

IDataBaseSchema dbMeta = new SQLiteDataBaseMetaData((DbConnection) _session.Connection);
ITableMetadata tbMeta = dbMeta.GetTableMetadata(//where do I get the datarow this method needs?, and what are the extras args?);

How can I use this method correctly?

A: I would suggest you verify that your mappings and your DB schema are in synch (See SchemaValidator); that should do the trick.


text:
Q: How to convert wav to mp3 using pure java? How can i use an api java for converting wav files to mp3 files without installing anything ? I tried JMF but it need to install JMStudio, and the broblem is that i need to not install anything. Who can give me an advice about something pure java !

A: You can't, without writing your own MP3 encoder. The MP3 format is patent encumbered, so the JRE cannot ship with a codec for it.


text:
Q: Adding a comment under the image I'm trying to add a comment below the image, but for some reason the text is all over the place.
Can anyone from the forum help me, please?
Images have margin-bottom: 4em; and I want to put a comment exactly there.

A: You can use figure tag

The  tag specifies self-contained content, like illustrations,
diagrams, photos, code listings, etc.
While the content of the  element is related to the main flow,
its position is independent of the main flow, and if removed it should
not affect the flow of the document.

read more here

<!DOCTYPE html>

Fig.1 - Trulli, Puglia, Italy.


text:
Q: how do I push a view controller from a ViewCell in a UICollectionView I'm trying to use a UICollectionView and it's viewCell.  I have that going fine.  But on the viewcell form I have a button that I intend to have go to a settings view.  I'm trying to "push it onto the stack".  Xcode complains of "no visible interface for the selector".  Some code and the error message are below.
// TryColViewCell.h
#import <UIKit/UIKit.h>
#import "TryColViewContViewController.h"

@interface TryColViewCell : UICollectionViewCell

@property (weak, nonatomic) IBOutlet UILabel *outletNameLBL;

@property (weak, nonatomic) IBOutlet UILabel *outletCellLabel;
@property (readwrite) NSInteger intTest;
@property (readwrite) TryColViewContViewController *theHost;

- (IBAction)actionPlus1:(id)sender;

- (IBAction)actionMinus1:(id)sender;

- (IBAction)actionNameEdit:(id)sender;

//  TryColViewCell.m
#import "TryColViewCell.h"
#import "SettingsViewController.h"

@implementation TryColViewCell {
@public    int intCellNumber;  //TODO: get this to track the row/cell #
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (IBAction)actionPlus1:(id)sender {

}

- (IBAction)actionMinus1:(id)sender {

}

- (IBAction)actionNameEdit:(id)sender {
    NSLog(@"Name Edit");

    SettingsViewController *viewControllerB =
        [[SettingsViewController alloc] initWithNibName:@"SettingsViewController" bundle:nil];

    viewControllerB.propName = _outletNameLBL.text;
    [self pushViewController:viewControllerB animated:YES];
    [self.theHost  pushViewController:viewControllerB animated:YES];

}
@end

// Error message on PushVIewController line
TryColViewCell.m:83:11: No visible @interface for 'TryColViewCell'
declares the selector 'pushViewController:animated:'

A: Push the new view controller from the view controller that contains the collection view, not the cell. Only a subclass of UIViewController has the method pushViewController:animated. to override.
In your table view controller, do something like this, assuming you are using storyboard:
-(UITableViewCell*)tableView:(UITableView*)tableView
  cellForRowAtIndexPath:(NSIndexPath*)indexPath {

  static NSString* identifier = @"Cell";
  CellSubClass *cell =
       (CellSubClass*) [tableView dequeueReusableCellWithIdentifier:identifier];

  [cell.upButton addTarget:self selector:@selector(actionPlus1:)
       forControlEvent:UIControlEventTouchUpInside];
  [cell.downButton addTarget:self selector:@selector(actionMinus1:)
       forControlEvent:UIControlEventTouchUpInside];

  ...
}


text:
Q: Fabric js: overriding toSVG method to add custom attribute into svg output I am trying to add attribute into my SVG output using fabric.js library.
Here is my code:

objectGlobal = new fabric.Rect({
        // here are some Rect attributes such as height width etc
        room_id: counter
    });
    objectGlobal.toSVG = (function(toSVG) {
        return function() {
            console.log("overriden to svg");
            return fabric.util.object.extend(toSVG.call(this), {
                room_id: this.room_id
            });
        };
    })(objectGlobal.toSVG);

    canvas.add(objectGlobal);

I got "overriden to svg" in my console, but my SVG output does not contain room_id attribute.
Here is the SVG output:

<rect x="-93.5" y="-49.5" rx="0" ry="0" width="187" height="99" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(229,229,229); fill-rule: nonzero; opacity: 1;" transform="translate(318 160)"/>


text:
Q: DD and Free Space I have a partition (/dev/sda1) of 10 GB. Also have "dd" file of another 7 GB partition ( /dev/sdb1).
When I execute the command as:

dd if=sdb1.dd of=/dev/sda1

then everything goes fine but I can not use remaining 3 GB space of /dev/sda1
Is there any way to tell DD to utilize remaining free space ( 3 GB in this case ) ?

A: dd does not care about free space (as in the filesystem concept) whatsoever, it just copies block by block.
If sdb1.dd is a filesystem image, you may be able to grow it using resize2fs or other tools (depending on the filesystem type) after you copied it.
resize2fs /dev/sda1

A:
Is there any way to tell DD to utilize remaining free space ( 3 GB in this case ) ?

No.
More to the point, assuming the target partition is the proper size (as you say), what you are doing is effectively writing a file system which only knows about the first portion of the partition. dd does not care about the meaning of the data written either at the source or the destination.
Depending on the file system in use, you might be able to expand the file system to use the entire partition, but that's far beyond the responsibilities of dd and the specifics will depend heavily on which exact file system is inside that image file.

A: dd doesn't copy files, if copies bytes.  That includes the structure of the filesystem, which is a 7 gigabyte filesystem.  When you are done copying, the filesystem data indicates it is a 7 gigabyte filesystem.
If you are just trying to duplicate all the files, using dd to make a copy isn't what you want.  Use tar, or dump/restore onto a freshly created filesystem.


text:
Q: Sideways Button On Edge of Screen I'm trying to add a button to the edge of the screen like this:

I tried using something like the code below but since the rotation is around the center there is space on the right side of the button about half the length of the button.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:rotation="270"
        android:text="Button" />

</RelativeLayout>

A: Use a RelativeLayout to access the attribute layout_alignParentEnd for your Button. If your root layout is a RelativeLayout then use that, if not you can wrap your Button in a RelativeLayout and use that layout. If you choose the latter option, you will need to position that layout.
<RelativeLayout
    android:id="@id+/wrapper_or_root"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_gravity="center_vertical|right"
        android:rotation="270"/>
</RelativeLayout>


text:
Q: Json after json_encode showing wrong value after insert in database I am trying to save multidimensional array in database using json_encode. if i echo json string its showing right output but in database string is changed after insert.
here is my code:
$email=$_POST['email'];
$watchlist=$_POST['watchlist'];
$watchshow=$_POST['watchshow'];
$yearshow=$_POST['yearshow'];

$quer = "SELECT email FROM users WHERE email = '$email'";
$q = mysqli_query($conn, $quer);
$count=0;
while($row = mysqli_fetch_array($q)){
$email = $row['email'];
$count++;
}

if($count==1) //if user already exist change greeting text to "Welcome Back"
{
$quer = "SELECT watchlist FROM users WHERE email = '$email'";
$q = mysqli_query($conn, $quer);
while($row = mysqli_fetch_array($q)){
$watch = $row['watchlist'];
}
$data = json_decode($watch, TRUE);
array_push($data,$watchlist);
$add=array();
array_push($add,$watchshow);
array_push($add,$yearshow);

$data[] = $add;

$t = json_encode($data , JSON_FORCE_OBJECT);

$sql = "update users set watchlist='$t' WHERE email='$email'";

if ($conn->query($sql) === TRUE) {
echo'updated';
} else {
echo'error';
}
}
else            {
$new=array();
array_push($new,$watchlist);
$add=array();
array_push($add,$watchshow);
array_push($add,$yearshow);
$new[] = $add;
$name = json_encode($new);

$sql1 = "INSERT INTO users (email,watchlist)
VALUES ('$email','$name')";
if ($conn->query($sql1) === TRUE) {
echo 'success';
} else {
echo "Error: " . $sql1 . "<br>" . $conn->error;
}
}

if i echo $name output is
{"0":{"0":"Stranger Things","1":2017}}

but after insert it's showing this in database
{"0":"Stranger Things","1":{"0":"Stranger Things","1":"2017"}}

what i am doing wrong here?

A: {"0":"Stranger Things","1":{"0":"Stranger Things","1":"2017"}}

This is happening most probably due to  $new[] = $add; when you are using Loop and passing some value inside $new[i].
In first Loop its proper {"0":"Stranger Things","1":2017}
Now in second loop when i will be 1.
So, in position of 1 , {"0":"Stranger Things","1":2017} this is getting inserted again and making final array as {"0":"Stranger Things","1":{"0":"Stranger Things","1":"2017"}}

Show the complete code as it is, to identify the error.

As per the code you have provided, output must be correct.
$email= "abc@gmail.com";
$watchshow="Stranger Things";
$yearshow= 2017;
$new=array();
$add=array();
array_push($add,$watchshow);
array_push($add,$yearshow);

$new[] = $add;

$add=array();
array_push($add,$watchshow);
array_push($add,$yearshow);
$new[] = $add;

echo $name = json_encode($new, true);

A: You placed echo to unnecessary variable somewhere in your code thats why it prints name 2 times.. check it properly and remove it.


text:
Q: AngularJS: Get template attribute value in controller I am a newbie of angularjs using version 1.6.4. I am using this module leon/angular-upload for upload functionality, minify version. On successful upload request, server return json object of uploaded file information on onSuccess(response) function as you can see in my user-registration.template.html file. Now i need to take this json object to my controller so that i can save this information in my database. Below is the few lines of my code.
user-registration.template.html:
<form role="form">

                    Name
                    <input type="text" placeholder="Name" class="form-control" ng-model="model.user.name">

Upload

                    <button type="button" class="btn btn-default" ng-click="model.save(model.user)">Save</button>

            </form>

My component "user-registration.component.js":
(function(){
    "use strict";

    var module = angular.module(__appName);
function saveUser(user, $http){
        var url = user.id > 0 ? __apiRoot + "/users/" + user.id : __apiRoot + "/users";
        var dataObj = {
            payload: JSON.stringify(user),
            _method: "PUT"
        }
        return $http.post(url, dataObj);
    }

    function controller($http){
        var model = this;
        model.user = null;

        model.save = function(user){
            console.log(JSON.stringify(user));
            saveUser(user, $http).then(function(response){
                alert(response.data.msg);
            });
        }
    }

    module.component("userRegistration", {
        templateUrl: "components/user-registration/user-registration.template.html",
        bindings: {
            value: "<"
        },
        controllerAs: "model",
        controller: ["$http", controller]
    });

}());

A: Try to put your server response data to  rootScope model for Exempel :
$rootScope.serveResponse = response ;
and with this rootScope you can share your variable data between  controller


text:
Q: How to access object outside the promised function in angularjs I am new in angularjs and as starter i have a problem with accessing object outside then function. I have created a factory:
    var injectParams = ['$http'];
    var address = function ($http) {
    var factory = {};

    factory.get = function () {
        return $http({
            method: "POST",
            url: '/address',
            headers: {
                'Content-Type': 'application/json'
            },
            data: {
                service: 'address'
            }
        });
    };
  return factory;
 }

And a controller method:
   function getAddresses() {
        address_factory.get().then(function success(response) {
            $scope.billing = response.data.billing;
            $scope.shipping = response.data.shipping;
            console.log(response.data);

        }, function error(x) {
            console.log(x);
        });
    }
   getAddresses();

The question is how can i access $scope.billing object outside getAddresses function? I have read promises in angularjs but i don't understand how to use...

A: $scope variables are available outse the promise once everywhere in the controller...
Hence $scope.billing will be accessible in html and controller js both...

A: $scope.billing is accessible everywhere in the controller and the template bound to that controller. But the value of $scope.billing is dynamic, it is undefined until the factory-get Promise is resolved. To reflect a dynamic nature of $scope.billing in the template you may try following approach:
 function getAddresses() {
    $scope.loading = true;
    address_factory.get().then(function success(response) {
      $scope.billing = response.data.billing;
      $scope.loading = false;
      $scope.error = null;
    }, function error() {
      $scope.loading = false;
      $scope.error = true;
    });
  }
 getAddresses();

and then in the template:

  Loading...

  Got an error!

  Billing: {{billing}}

Also, you may use $scope.$watch in the controller to watch for $scope.billing changes:
// ...
getAddresses();

$scope.$watch('billing', function() {
  // $scope.billing has been changed
  console.log($scope.billing);
});

But I would recommend to do all necessary logic right in the success-callback of the Promise.then call.

A: $scope means the current scope that is the current area where some-controller.js & the some-view.html is accessible.
If you set any variable to $scope it will be accessible anywhere in the some-controller.js & some-view.html.
Suppose you set ng-controller to any div as
.....
. So any thing with $scope like $scope.something is set in controller will be accessible in the controller and withing this div too, because the scope of the controller is this.


text:
Q: I just upgraded to PHP5 - Everything is deprecated, Apache is blank I have no idea of what version of PHP I was using before, but I'm guessing it was an older version because it was working just fine before I switched from Nginx to Apache. I think I was using an older version of PHP on Nginx. Anyhow this is an example of code that is said to be deprecated. I am now on PHP 5.5.9.
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "username", "password");
// Selecting Database
$db = mysql_select_db("database", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select name from table where name='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['name'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>

All of my pages use PHP code similar to this so I'm just going to post one of them. This is my error log.
[Mon Jan 12 03:03:40.456254 2015] [mpm_event:notice] [pid 2415:tid 3074542208] AH00489: Apache/2.4.7 (Ubuntu) configured -- resuming normal operations
[Mon Jan 12 03:03:40.456344 2015] [core:notice] [pid 2415:tid 3074542208] AH00094: Command line: '/usr/sbin/apache2'
[Mon Jan 12 03:04:42.038619 2015] [mpm_event:notice] [pid 2415:tid 3074542208] AH00491: caught SIGTERM, shutting down
[Mon Jan 12 03:04:43.100702 2015] [mpm_prefork:notice] [pid 3617] AH00163: Apache/2.4.7 (Ubuntu) configured -- resuming normal operations
[Mon Jan 12 03:04:43.100786 2015] [core:notice] [pid 3617] AH00094: Command line: '/usr/sbin/apache2'
[Mon Jan 12 03:04:44.344041 2015] [mpm_prefork:notice] [pid 3617] AH00169: caught SIGTERM, shutting down
[Mon Jan 12 03:04:45.489917 2015] [mpm_prefork:notice] [pid 3708] AH00163: Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.5 configured -- resuming normal operations
[Mon Jan 12 03:04:45.489959 2015] [core:notice] [pid 3708] AH00094: Command line: '/usr/sbin/apache2'
[Mon Jan 12 03:06:19.837552 2015] [mpm_prefork:notice] [pid 3708] AH00169: caught SIGTERM, shutting down
[Mon Jan 12 03:06:20.873964 2015] [mpm_prefork:notice] [pid 3925] AH00163: Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.5 configured -- resuming normal operations
[Mon Jan 12 03:06:20.874005 2015] [core:notice] [pid 3925] AH00094: Command line: '/usr/sbin/apache2'
[Mon Jan 12 03:07:37.795009 2015] [:error] [pid 3932] [client 108.162.238.215:57356] script '/var/www/html/info.php' not found or unable to stat
[Mon Jan 12 03:09:01.713565 2015] [:error] [pid 3928] [client 108.162.238.215:28781] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 4
[Mon Jan 12 03:09:06.002298 2015] [:error] [pid 3928] [client 108.162.238.215:28781] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 4
[Mon Jan 12 03:09:17.906216 2015] [:error] [pid 3946] [client 108.162.238.215:64299] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 4
[Mon Jan 12 03:09:23.456198 2015] [:error] [pid 3931] [client 108.162.238.215:36456] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 4, referer: https://epicmc.us/404.php
[Mon Jan 12 03:09:26.631794 2015] [:error] [pid 3931] [client 108.162.238.215:36456] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 4, referer: https://epicmc.us/404.php
[Mon Jan 12 03:09:55.207111 2015] [mpm_prefork:notice] [pid 3925] AH00169: caught SIGTERM, shutting down
[Mon Jan 12 03:09:55.300465 2015] [mpm_prefork:notice] [pid 3996] AH00163: Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.5 configured -- resuming normal operations
[Mon Jan 12 03:09:55.300511 2015] [core:notice] [pid 3996] AH00094: Command line: '/usr/sbin/apache2'
[Mon Jan 12 03:09:59.717164 2015] [:error] [pid 4001] [client 108.162.238.215:16174] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 4, referer: https://epicmc.us/404.php
[Mon Jan 12 03:10:25.281382 2015] [:error] [pid 4002] [client 108.162.238.215:18754] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 4
[Mon Jan 12 03:11:03.812550 2015] [:error] [pid 3999] [client 108.162.238.215:47026] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 4
[Mon Jan 12 03:11:39.560256 2015] [:error] [pid 4016] [client 108.162.238.215:28585] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 4
[Mon Jan 12 03:14:36.371451 2015] [:error] [pid 4001] [client 108.162.238.215:29588] PHP Notice:  Undefined index: player in /var/www/html/stats.php on line 7
[Mon Jan 12 03:14:36.387589 2015] [:error] [pid 4017] [client 63.142.248.45:58023] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/api.php on line 9
[Mon Jan 12 03:14:36.387889 2015] [:error] [pid 4001] [client 108.162.238.215:29588] PHP Warning:  file_get_contents(http://epicmc.us/api.php?task=stats&player=): failed to open stream: HTTP request failed! HTTP/1.0 500 Internal Server Error\r\n in /var/www/html/stats.php on line 7
[Mon Jan 12 03:14:36.387942 2015] [:error] [pid 4001] [client 108.162.238.215:29588] PHP Notice:  Undefined index: player in /var/www/html/stats.php on line 10
[Mon Jan 12 03:14:36.387956 2015] [:error] [pid 4001] [client 108.162.238.215:29588] PHP Notice:  Undefined index: player in /var/www/html/stats.php on line 20
[Mon Jan 12 03:14:36.388029 2015] [:error] [pid 4001] [client 108.162.238.215:29588] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 4
[Mon Jan 12 03:14:40.516471 2015] [:error] [pid 4001] [client 108.162.238.215:29588] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/api.php on line 9
[Mon Jan 12 03:16:26.882760 2015] [:error] [pid 4003] [client 108.162.214.137:51884] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 4, referer: https://epicmc.us
[Mon Jan 12 03:18:35.605165 2015] [mpm_prefork:notice] [pid 3996] AH00169: caught SIGTERM, shutting down
[Mon Jan 12 03:18:36.649524 2015] [mpm_prefork:notice] [pid 4105] AH00163: Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.5 configured -- resuming normal operations
[Mon Jan 12 03:18:36.649586 2015] [core:notice] [pid 4105] AH00094: Command line: '/usr/sbin/apache2'
[Mon Jan 12 03:18:40.845243 2015] [:error] [pid 4111] [client 108.162.238.215:26322] PHP Notice:  Undefined index: player in /var/www/html/stats.php on line 7
[Mon Jan 12 03:18:40.849347 2015] [:error] [pid 4112] [client 63.142.248.45:34942] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/api.php on line 9
[Mon Jan 12 03:18:40.849619 2015] [:error] [pid 4111] [client 108.162.238.215:26322] PHP Warning:  file_get_contents(http://epicmc.us/api.php?task=stats&player=): failed to open stream: HTTP request failed! HTTP/1.0 500 Internal Server Error\r\n in /var/www/html/stats.php on line 7
[Mon Jan 12 03:18:40.849660 2015] [:error] [pid 4111] [client 108.162.238.215:26322] PHP Notice:  Undefined index: player in /var/www/html/stats.php on line 10
[Mon Jan 12 03:18:40.849671 2015] [:error] [pid 4111] [client 108.162.238.215:26322] PHP Notice:  Undefined index: player in /var/www/html/stats.php on line 20
[Mon Jan 12 03:18:40.850012 2015] [:error] [pid 4111] [client 108.162.238.215:26322] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 4
[Mon Jan 12 03:22:59.264503 2015] [:error] [pid 4110] [client 108.162.238.215:39205] PHP Fatal error:  Call to undefined function mysqli_connect() in /var/www/html/session.php on line 3
[Mon Jan 12 03:25:15.361204 2015] [:error] [pid 4109] [client 108.162.238.215:31116] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 3
[Mon Jan 12 03:26:55.673865 2015] [:error] [pid 4108] [client 108.162.238.215:44137] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 3
[Mon Jan 12 03:26:59.193970 2015] [:error] [pid 4112] [client 108.162.238.215:43815] PHP Notice:  Undefined index: player in /var/www/html/stats.php on line 7
[Mon Jan 12 03:26:59.197756 2015] [:error] [pid 4125] [client 63.142.248.45:44475] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/api.php on line 9
[Mon Jan 12 03:26:59.197950 2015] [:error] [pid 4112] [client 108.162.238.215:43815] PHP Warning:  file_get_contents(http://epicmc.us/api.php?task=stats&player=): failed to open stream: HTTP request failed! HTTP/1.0 500 Internal Server Error\r\n in /var/www/html/stats.php on line 7
[Mon Jan 12 03:26:59.197982 2015] [:error] [pid 4112] [client 108.162.238.215:43815] PHP Notice:  Undefined index: player in /var/www/html/stats.php on line 10
[Mon Jan 12 03:26:59.197992 2015] [:error] [pid 4112] [client 108.162.238.215:43815] PHP Notice:  Undefined index: player in /var/www/html/stats.php on line 20
[Mon Jan 12 03:26:59.198047 2015] [:error] [pid 4112] [client 108.162.238.215:43815] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/session.php on line 3
[Mon Jan 12 03:27:03.942299 2015] [:error] [pid 4111] [client 108.162.238.215:51061] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/api.php on line 9
[Mon Jan 12 03:27:16.010513 2015] [:error] [pid 4110] [client 108.162.238.215:42175] PHP Fatal error:  Call to undefined function mysql_connect() in /var/www/html/api.php on line 9

If somebody out there could re-write the entire PHP code I posted above in PHP 5 format so that I know where to start that would be awesome. Currently Apache2 is just a blank site with only a couple HTML elements working here and there. Sorry if this sounds like a noob question I'd just really like a reference.
There is two php.ini files. One is in /etc/php5/apache2
PHP INI ATTACHED EXTERNALLY BECAUSE I DON'T HAVE ENOUGH ROOM TO POST IT HERE
http://pastebin.com/UpwuC2Hj

A: you appear to be missing the mysql modules for php.  installing them should get your site back up again,  then you can start on upgrading your code.
read the comments in the section Dynamic Extensions of the ini file and uncomment the correct line.


text:
Q: android- How to make slideshow something like this I'm new to android. I saw this slideshow and I like it ,
I don't know how can I make something like this.

it has two arrows ,it changes the image every x second.
I couldn't find library like this.
Could you help me to find a library or a way to make something like this ?
thanks you

A:               ViewPagerAdapter adapter = new ViewPagerAdapter(MainActivity.this,SIZE);
           myPager = (ViewPager) findViewById(R.id.yourViewPager);
              myPager.setAdapter(adapter);
              myPager.setCurrentItem(0);

              // Timer for automatic sliding
              timer  = new Timer();
              timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(count<= SIZE){
                              myPager.setCurrentItem(count);
                              count++;
                              }else{
                                     count = 0;
                                     myPager.setCurrentItem(count);
                              }
                    }
                });
            }
        }, 100, 1000);
       }

For more details
http://saurabhsharma123k.blogspot.in/2014/03/viewpager-for-horizental-screen-slides.html


text:
Q: How to update properties with functions within a foreach loop? I would like to change some properties of an object in a foreach loop:
foreach ($object->array as $element) {
    $element['foo'] = $new_foo;
    $element['bar'] = $new_bar;
}

How should I do this with a function? Or else how could I do this with object-oriented approach? My code doesn't work, as it only changes the value of the $handle variable within the function:
function change_attribute(&$handle, $new_value) {
    $handle = $new_value;
}

foreach ($object->array as $element) {
    change_attribute($element['foo'], $new_foo);
    change_attribute($element['bar'], $new_bar);
}

The actual code
foreach ($xml->database[0]->table as $table) {
    $table->column[1]['name'] = 'new value';
}

It succesfully updates the $xml object without referencing the array element (that would cause a fatal error). Why can't I do the same with this function?
function change_attribute(&$handle, $old, $new) {
    if ($handle == $old) {
        $handle = $new;
    }
}

foreach ($xml->database[0]->table as $table) {
    change_attribute($table->column[1]['name'], 'old value', 'new value');
}

The $xml object
php > var_dump($xml->database[0]->table);
object(SimpleXMLElement)#2 (2) {
  ["@attributes"]=>
  array(1) {
    ["name"]=>
    string(7) "objects"
  }
  ["column"]=>
  array(5) {
    [0]=>
    string(4)
    [1]=>
    string(1)
    [2]=>
    string(17)
    [3]=>
    string(17)
    [4]=>
    string(1949)
  }
}

This is identical to var_dump($xml->database[0]->table[0]) except the later is object(SimpleXMLElement)#4 (2).
object(SimpleXMLElement)#2 (2) {
  ["@attributes"]=>
  array(1) {
    ["name"]=>
    string(9) "old value"
  }
  [0]=>
  string(1) "2"
}

A: You need to make $element a reference using &, i.e.
foreach ($object->array as &$element) {...}

Without it, you're manipulating a copy of $object->array rather than the array itself. Have a look at the PHP docs on references.

A: I have to pass the object to the function and not the class property. Unfortunately the later must be hard-coded in the function:
function change_column_name(&$table, $index, $old, $new) {
    if ($table->column[$index]['name'] == $old) {
        $table->column[$index]['name'] = $new;
    }
}

foreach ($xml->database[0]->table as $table) {
    change_column_name($table, 1, 'old value', 'new value');
}

George Brighton's answer is right concerning arrays, but SimpleXMLElement objects cannot be used the same way, likely because they are objects embed in objects as class properties.


text:
Q: Go url.Parse(string) fails with certain user names or passwords Using a URL that has worked in the past, I know receive a parsing error from net/url. What's wrong with it?
parse postgres://user:abc{DEf1=ghi@example.com:5432/db?sslmode=require: net/url: invalid userinfo

Sample application
See https://play.golang.com/p/mQZaN5JN3_q to run.
package main

import (
    "fmt"
    "net/url"
)

func main() {
    dsn := "postgres://user:abc{DEf1=ghi@example.com:5432/db?sslmode=require"

    u, err := url.Parse(dsn)
    fmt.Println(u, err)
}

A: Well, you can just
url.QueryEscape("your#$%^&*(proper$#$%%^(password")

and use this one to parse your url.

A: It turns out up until Go v1.9.3 net/url didn't validate the user info when parsing a url. This may break existing applications when compiled using v1.9.4 if the username or password contain special characters.
It now expects the user info to be percent encoded string in order to handle special characters. The new behaviour got introduced in ba1018b.
Fixed sample application
package main

import (
    "fmt"
    "net/url"
)

func main() {
    dsn1 := "postgres://user:abc{DEf1=ghi@example.com:5432/db?sslmode=require" // this works up until 1.9.3 but no longer in 1.9.4
    dsn2 := "postgres://user:abc%7BDEf1=ghi@example.com:5432/db?sslmode=require" // this works everywhere, note { is now %7B

    u, err := url.Parse(dsn1)
    fmt.Println("1st url:\t", u, err)

    u, err = url.Parse(dsn2)
    fmt.Println("2nd url:\t", u, err)
}

Run the code on https://play.golang.com/p/jGIQgbiKZwz.

A: Use url.UserPassword func :
package main

import (
    "fmt"
    "net/url"
)

func main() {
    dsn := "postgres://example.com:5432/db?sslmode=require"

    u, err := url.Parse(dsn)
    if err != nil {
         fmt.Printf("ERROR: %v\n", err)
         return
    }
    u.User = url.UserPassword("user", "abc{DEf1=ghi")
    fmt.Println("url:\t", u)

}


text:
Q: rails link_to category that has_many I have Pages that belongs_to Category
for the Pages I have controller and model
for the Category I only have model and I made a relations between them
on my PagesContoller I have:
@categories = Category.all

and this is how I show it on my page:
<% @categories.each do |cat| %>
  <%= cat.name %>
  <%= link_to "category", ????? %>
<% end %>

Now I'm trying to create a link that will go to each Category, any ideas?

A:  <% @categories.each do |cat| %>
      <%= cat.name %>
      <%= link_to "category", category_path(cat) %>
    <% end %>

UPDATE
First of all you should have categories controller I don't find any reason why you wont do it. Secondly if you wanna handle every thing in pages controller then add a route and action in pages controller. like in your route file
get 'pages/categories/:id' => "pages#category" , :as=>:category

then In pages_controller add an action named category
def category
@category=Category.find(params[:id])
end


text:
Q: How do I tell if a site is using CloudFlare reverse proxy services? I'm investigating the impact of the leak of CloudFlare payload data due to a parser bug on services that we use.
It's relatively easy to tell if a service is directing traffic to CloudFlare via DNS:
$ nslookup www.authy.com
Server:  google-public-dns-a.google.com
Address:  8.8.8.8

Non-authoritative answer:
Name:    www.authy.com
Addresses:  104.16.0.17
          104.16.1.17

$ whois -h whois.arin.net n 104.16.0.17 | egrep 'Organization'
Organization:   Cloudflare, Inc. (CLOUD14)

Does CloudFlare terminate all traffic directed to them this way, or if not, is there a way to independently tell whether a CloudFlare customer is using CloudFlare's reverse proxy service?

A: Method 1 (Most Accurate)
Visit the IP you receive upon DNS lookup:
$ ping authy.com
PING authy.com (104.16.0.17) 56(84) bytes of data.

So, going to 104.16.0.17 in my browser gives me this: Direct IP access not allowed
If you would want to automate this, I'm sure you could use curl or a similar tool, but on an individual site-by-site basis, this is the easiest way I can think of doing this.
NOTE: Someone could "spoof" the page into looking like a Cloudflare page, when it isn't, so this method isn't foolproof or guaranteed to work.
Method 2 (Less  Accurate)
Take a look at the whois data for any website suspected of using Cloudflare:
$ whois authy.net|grep "Name Server"
Name Server: LEE.NS.CLOUDFLARE.COM
Name Server: MARY.NS.CLOUDFLARE.COM

Anything that ends in NS.CLOUDFLARE.COM is Cloudflare, however, the site owner may not be using the reverse-proxy server (aka the server is gray-clouded), so they are just using Cloudflare's DNS servers.
Another way Method 2 may not work is if the server's DNS is CNAME, which it will look like a private/non-Cloudflare DNS server, but when queried, it will return Cloudflare.
Conclusion:
You shoud use Methods 1 and 2 to be fairly certain they are using Cloudflare's reverse-proxy server.

A: Try https://cloudflare.hellafast.digital/
It checks nameservers automatically and gives you the answer

A: If talking about http/https reverse proxy only - you can make a request to the hostname and see if there is a
CF-RAY

and or
Server: cloudflare

available.


text:
Q: Amazon S3 check existence of bucket using libS3 I am using LibS3, a C library that talks to my amazon S3 server and I have noticed that for checking the existence of a bucket libs3 sends a GET request with a query in the URL "?location", and the amazon S3 server responds with an appropriate HTTP response if the bucket exists or not. The problem is that in the documentation of the Amazon S3 server for checking the existence of a bucket it's said that you must make a HTTP HEAD request, http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html, so I'm confused on what method it's used in the server... If the both of them are supported and how is list objects different from check existence using GET.

A: You can send both GET and HEAD requests to check existence of a bucket. Amazon will return 404 HTTP code if it doesn't exist. The main difference is that HEAD does not contain request body (thus takes less bandwidth).


text:
Q: How to set gradient dynamically in a appwidget imageView background? I have set up the gradient in my drawable\skycolor.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item>
    <shape>
        <gradient
            android:angle="90"
            android:endColor="#ff5bdddd"
            android:startColor="#ff4688bf"
            android:type="linear" />
    </shape>
</item>

I want to set this gradient as the background of my homescreen widget. I already have an imageview placed in the widget.
<ImageView
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:id="@+id/iv_background"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:focusableInTouchMode="true" />

How do I set the gradient as the background color in the updateAppWidget method? Initially I planned to do it this way, but it did not work.
ImageView iv_skyColor = (ImageView)findViewById(R.id.iv_background);
    iv_skyColor.setBackground(@drawable/skycolor);

findViewbyID does not work inside updateAppWidget method,
updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId)

also the code can not resolve @drawable/skycolor. How can I resolve this?

A: Nevermind, I managed to make it work using,
views.setImageViewResource(R.id.iv_background, R.drawable.skycolor);


text:
Q: Adding a placeholder in  is causing triggering of onchange event on it in IE browser Adding a placeholder in lightning-textarea is causing the triggering of onchange event on it in the IE browser.
Below is the snippet where I have added placeholder = "Enter value". While loading the component in LWC, it is causing triggering of the onchange = {handleChange} event. I need to stop this as further validations are there on the change event.
<lightning-textarea value={TestValue}
                      class="requiredField"
                      placeholder="Enter value"
                      onchange={handleChange}
                      message-when-value-missing="Please Enter the value"
                      variant="label-hidden"
                      max-length=50
                      required>
              </lightning-textarea>

A: You can try following workaround in Your handler:
handleChange(event) {
    if(event.target.value !== 'Enter value') {
    //Your logic here
    }
}


text:
Q: Do single use plants count as losing a plant? One of the conditions for a star on a level is to lose no more than 1 plant.  Do single use plants like the iceberg lettuce count as losing a plant?

A: I should have just tried to pick one for the level.  If you try to take a single use plant on a mission with that restriction, a big warning pops up telling you that it does count as losing a plant.


text:
Q: To search for strings with in a string (search for all hrefs in HTML source) I have a string variable that contains the entire HTML of a web page.
The web page would contain links to other websites. I would like to create a list of all hrefs (webcrawler like ).
What is the best possible way to do it ?
Will using any extension function help ? what about using Regex ?
Thanks in Advance

A: Use a DOM parser such as the HTML Agility Pack to parse your document and find all links.
There's a good question on SO about how to use HTML Agility Pack available here. Here's a simple example to get you started:
string html = "your HTML here";

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();

doc.LoadHtml(html);

var links = doc.DocumentNodes.DescendantNodes()
   .Where(n => n.Name == "a" && n.Attributes.Contains("href")
   .Select(n => n.Attributes["href"].Value);

A: I think you'll find this answers your question to a T
http://msdn.microsoft.com/en-us/library/t9e807fx.aspx
:)

A: I would go with Regex.
        Regex exp = new Regex(
            @"{href=}*{>}",
            RegexOptions.IgnoreCase);
        string InputText; //supply with HTTP
        MatchCollection MatchList = exp.Matches(InputText);

A: Try this Regex (should work):
var matches = Regex.Matches (html, @"href=""(.+?)""");

You can go through the matches and extract the captured URL.

A: Have you looked into using HTMLAGILITYPACK? http://htmlagilitypack.codeplex.com/
With this you can simply us XPATH to get all of the links on the page and put them into a list.
private List<string> ExtractAllAHrefTags(HtmlDocument htmlSnippet)
{
    List<string> hrefTags = new List<string>();

    foreach (HtmlNode link in htmlSnippet.DocumentNode.SelectNodes("//a[@href]"))
    {
        HtmlAttribute att = link.Attributes["href"];
        hrefTags.Add(att.Value);
    }

    return hrefTags;
}

Taken from another post here - Get all links on html page?


text:
Q: MySQL - Return multiple users based on team membership I am looking to return all users that are members of teams that the requested user (simulated by hard coding the uid value of user1) is part of. I am trying to achieve this by using a joining table teams_members but can only end up with queries than return more than what I am looking for.
DB Fiddle Link
In the query output (Query #3) I am expecting to not see user3 as they are not part of team1 or team2, the only teams that user1 is part of.
Setup:
CREATE TABLE users (
  uid INT,
  name TEXT
);
INSERT INTO users (uid, name) VALUES (1, "user1");
INSERT INTO users (uid, name) VALUES (2, "user2");
INSERT INTO users (uid, name) VALUES (3, "user3");

CREATE TABLE teams (
  tuid INT,
  name TEXT
);
INSERT INTO teams (tuid, name) VALUES (1, 'team1');
INSERT INTO teams (tuid, name) VALUES (2, 'team2');
INSERT INTO teams (tuid, name) VALUES (3, 'team3');

CREATE TABLE teams_members (
  uid INT,
  tuid INT,
  role TEXT
);
INSERT INTO teams_members (uid, tuid, role) VALUES (1, 1, 'owner');
INSERT INTO teams_members (uid, tuid, role) VALUES (1, 2, 'owner');
INSERT INTO teams_members (uid, tuid, role) VALUES (2, 1, 'owner');
INSERT INTO teams_members (uid, tuid, role) VALUES (3, 3, 'owner');

Queries (others added for context):
# Get user
SELECT * FROM users WHERE uid = 1;

# Get teams the user is part of
SELECT t.tuid, t.name FROM teams t
LEFT JOIN teams_members tm ON t.tuid = tm.tuid
WHERE uid = 1;

# Get team members present for all teams <<<<<<< Query in question
SELECT u.uid, u.name FROM users u
LEFT JOIN teams_members tm ON u.uid = tm.uid
LEFT JOIN teams t ON tm.tuid = t.tuid
WHERE tm.uid = u.uid;

How do I return only users that are present in teams that user1 is part of?

A: Your second query is all you need. Use it to get the data from table users:
select *
from users where uid in(SELECT t.tuid
                        FROM teams t
                        LEFT JOIN teams_members tm ON t.tuid = tm.tuid
                        WHERE uid = 1);

Here is the demo:

DEMO

A:
How do I return only users that are present in teams that user1 is part of?

One method uses exists:
select u.*
from users u
where exists (select 1
              from teams_members tm1 join
                   teams_members tm2
                   on tm1.tuid = tm2.tuid  -- same team
              where tm1.uid = 1 and        -- team has user 1
                    tm2.uid = u.uid        -- team has user in outer query
             );


text:
Q: Re-manning drones Anyone remember the story about the re-discovery of manual arithmetic enabling unmanned robot planes to be re-manned?  I believe it was a short story published in Astounding.

A: This is most likely "The Feeling of Power" By Isaac Asimov, as suggested in [this eye-opening answer] by Valorum.
The idea that humanity struggles with simple arithmetic is clear

"Aub! How much is nine times seven?" Aub hesitated a moment. His pale eyes glimmered with a feeble anxiety. "Sixty-three," he said. Congressman Brant lifted his eyebrows. "Is that right?" "Check it for yourself, Congressman."
Valorum's answer to: Story about a mathematics discovery that would allow people to replace computers in missiles

and the "drones" which are actually missiles which are currently on auto-pilot are replace by human pilots.

The general drove on. "At the present time our chief bottleneck is the fact that missiles are limited in intelligence. The computer controlling them can only be so large, and for that reason they can meet the changing nature of anti-missile defenses in an unsatisfactory way. Few missiles, if any, accomplish their goal, and missile warfare is coming to a dead end, for the enemy, fortunately, as well as for ourselves.
"On the other hand, a missile with a man or two within, controlling flight by graphitics, would be lighter, more mobile, more intelligent. It would give us a lead that might well mean the margin of victory.
ibid.

This story was published in If (as User14111 says) and can be read online here.


text:
Q: Angular2: Property binding permission not used by any directive on an embedded template I have create one directives in angular2. but, not working and return error template parse.
my directives :
import { Directive, Input } from '@angular/core';
import { TemplateRef, ViewContainerRef } from '@angular/core';
import {CookieService} from 'angular2-cookie/core';

@Directive({ selector: '[permission]' })
export class PermissionDirective {
  constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef,
        private _cookie:CookieService,
    ) {}
  @Input() set permission(_user_type: any) {
    this.viewContainer.clear();

    // let _type = this._cookie.get("_type");
    // if (_user_type == _type) {
    //   this.viewContainer.createEmbeddedView(this.templateRef);
    // } else {
    //   this.viewContainer.clear();
    // }
  }
}

Html code:

      Users

Console error log:
error_handler.js:45 EXCEPTION: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'permission' since it isn't a known property of 'a'. ("

                ][permission]="'2'" routerLink="/users/list"> Users
            "): LeftMenuComponent@38:19

A: Are you adding the Directive to the app module as a declaration?
import { PermissionDirective } from './permissions.directive';

@NgModule({
    declarations: [PermissionDirective],
    exports: [PermissionDirective]
})

export class PermissionsModule {}