text:
Q: If $a$ , $b$, $c$ are positive integers satisfying the following $(a^2 +2)(b^2+3)(c^2+4)=2014$ What is the value of $ a+b+c $ If $a$ , $b$, $c$ are positive integers satisfying the following
$(a^2 +2)(b^2+3)(c^2+4)=2014$
What is the value  of $ a+b+c $
I need  details  because  i don't  know  how to solve simlar  problems ?
Thank you for your help.

A: $2014 = 2*19*53$
So each of the $a^2 + 2, b^2+3, c^2 + 4$ are some combination of $2, 19, 53$.
As none of them can equal 1, the must be that one of them equals $2$, another $19$ and the third $53$.  What possible numbers work?  (Note: just by looking only one can be small enough to equal $2$.)

A: Try factoring $2014$. Then you might see how to find $a$, $b$, and $c$.
If you need more help just ask!

A: let us consider following program
    z=input('enter your number : ');
  string='';
    for ii=2:z
       s=0;
       while z/ii==floor(z/ii) % check if  z is divisible by ii
           z=z/ii;
           s=s+1;
       end
       if s>0
                str =[num2str(ii) '^' num2str(s) ];

                   string=strcat(string,str);
                   string= strcat(string,'*');
             % If z = 1, no more divisions are necessary,
            % thus breaks the loop and quits
            if z == 1
                break
            end
        end

    end
    string=string(1:end-1);% remove last sign of multiplicaiton
fprintf('prime factorization is %s\n',string);

we would have
>> integer_factorization
enter your number : 2014
prime factorization is 2^1*19^1*53^1

now
 x=2
y=19
z=53

$a^2+2=2$
$a^2=0$
which means $a=0$
$c^2+4=53$
$c^2=53-4=49$
which  means  that $c=7$  or $c=-7$ depend  we have positive  integers or integers and  also
$b^2+3=19$
we have $ b=4 $ or $b-4$


text:
Q: Invalid use of template-name 'SmartArray' without an argument list So the title states the problem I'm running into with my class constructors/destructor. Here's my code:
    template <class ArrType>
    class SmartArray{
        public:
        ArrType *elements;              // pointer that will point to dynamic array
        int length();                   // function to return array length
        SmartArray<ArrType>();          // default constructor
        SmartArray(int arrSize);        // constructor that initializes array size
        ~SmartArray();                  // destructor
        void resizeArr(int newsize);        // function that resizes array
        SmartArray(const SmartArray& otherObject);  // copy constructor

And here's the default constructor:
    SmartArray::SmartArray(){
        arrSize = 0;
        elements = new ArrType[arrSize];
        cout << "Created array using default constructor." << endl;     // letting user know that object was successfully created
    }

I did try looking the problem up but either those programs were too advanced for me to understand or I was just too stupid. In any case, I'm hoping there's a simple fix for this.

A: You have to use the template keyword to define the constructor, also:
template<class ArrayType>
SmartArray<ArrayType>::SmartArray(){

   // ...

P.S. if you can confirm that you have this constructor definition placed in a separate .cpp file, your question will, unfortunately, also have to be closed as a duplicate of this question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java: Modifying arguments of an anonymous function which is passed as a callable I am creating a generic iterator which is passed a String object and a callable in Java. The callable argument needs to be changed with respect to the iterations. For example, for initial 5 iterations the argument is X and for next 5 iterations the argument should be Y.
I already have separate callable methods. I was trying to pass those methods through lambda expression in place of callable, but I found that the Callable interface doesn't allow modification of arguments from with in the iterator. Can someone suggest about the possible actions possible with Java?
Another option, I have in hand is to create out a Callable object and pass it to the iterator. I believe that'll do the purpose, but I was more interested in passing it as anonymised functions.
Example: I have an iterator similar to
public class CustomIterator<Type> implements Iterable<Type> {

    private int offset;
    private int maxOffset = 1000;
    private Callable<Object> function;

    public CustomIterator(Callable<Object> function) {
        this.offset = 0;
        this.function = function;
    }

    @Override
    public Iterator<Type> iterator() {
        return new Iterator<Type>() {

            @Override
            public boolean hasNext() {
                return (offset < maxOffset);
            }

            @Override
            public Type next() {
                //* Some Logic here

                try {

                    // Pass offset to the Callable function
                    Type t = (Type) function.call();
                // increment offset based on the value of t
                    return t;
                } catch (Exception ex) {
                    return null;
                }
            }
        };
    }
}

By the way, I am using Java 11, so if there is a specific feature related to that version that'll work as well.


text:
Q: How to add Personal Data in the Metadata field of my workout using swift? I'm new in swift.
I have a problem that I don't find the solution.
I would like to add personnal data (the arrows count from my motionManager class) in the metadata field of my workout.
What should I add in my code to do this, please ?
// MARK: Properties
let motionManager = MotionManager()
let healthStore = HKHealthStore()
var builder: HKLiveWorkoutBuilder!
weak var delegate: WorkoutManagerDelegate?
var session: HKWorkoutSession?

// MARK: WorkoutManager
func startWorkout() {
    let typesToShare: Set = [ HKQuantityType.workoutType()  ]
    let typesToRead: Set = [  HKQuantityType.quantityType(forIdentifier: .heartRate)!   ]
    healthStore.requestAuthorization(toShare: typesToShare, read: typesToRead) { (succ, error) in
        if !succ { }
    }
    let workoutConfiguration = HKWorkoutConfiguration()
    workoutConfiguration.activityType = .archery
    workoutConfiguration.locationType = .unknown

    do {
        session = try HKWorkoutSession(healthStore: healthStore, configuration: workoutConfiguration)
        builder = session?.associatedWorkoutBuilder()
    } catch {
    }
    builder.dataSource = HKLiveWorkoutDataSource(healthStore: healthStore, workoutConfiguration: workoutConfiguration)
    session?.startActivity(with: Date())
    builder.beginCollection(withStart: Date()) { (succ, error) in
        if !succ { }
    }
    motionManager.startUpdates()
}

func stopWorkout() {
    if (session == nil) {  return   }
    motionManager.stopUpdates()
    print("****** END ****** ARROWS COU%NT : \(motionManager.arrowsCount)")

    let quantity = HKQuantity.init(unit: HKUnit.count(), doubleValue: Double(motionManager.arrowsCount))

//      WHAT SHOULD I DO TO SAVE QUANTITY IN METADATA OF THE WORKOUT ?

    session?.end()
    builder.endCollection(withEnd: Date()) { (success, error) in
        self.builder.finishWorkout { (workout, error) in
            DispatchQueue.main.async() {
                self.session = nil
                self.builder = nil
            }
        }
    }
    session = nil
}

A: Your builder has an addMetadata function. Call it passing a [String: Any]
builder.addMetadata(["YourKey": quantity])


text:
Q: Not able to show the events against same time one after other in horizontal manager in Blackberry I am trying to get events from Blackberry Calendar. I am trying to show the events occurring at the same time one after other
like
8:00 e1
8:00 e2

as in native Calendar
But the following code shows the output as
8:00 e1 e2

in my code i have 24 hfm added to single vfm.
int size1 = 2;
horizontalFieldManager_left22 = new  HorizontalFieldManager[size1];
for (int y = 0; y < size1; y++) {
horizontalFieldManager_left22[y] = new  HorizontalFieldManager() {
protected boolean navigationClick(int status, int time) {
Field field = getFieldWithFocus();
Vector data = getData(listEvent);
String  currentData = desc22.getText();
String  currentTime = time22.getText();
 if  (currentData != null && currentData != "") {
         UiApplication.getUiApplication().pushScreen(new EventScreen(data,currentData,currentTime));
            }
    return super.navigationClick(status, time);
        }

    protected boolean keyChar  (char key, int status, int time) {
    Field field = getFieldWithFocus();

     return
     super.keyChar(key, status, time);
          }
   };

   int size = eventVector7.size();
   LabelField[] labelField = new
   LabelField[size];
   for (int x = 0; x < eventVector7.size(); x++) {
   labelField[x] = new
   LabelField("", Field.FOCUSABLE);
   String data = (String)
   eventVector7.elementAt(x);
   labelField[x].setText(data);
  horizontalFieldManager_left22[y].add(time22);

  horizontalFieldManager_left22[y].add(min22);

  horizontalFieldManager_left22[y].add(new LabelField(" "));

  horizontalFieldManager_left22[y].add(labelField[x]);

        }

   }
 for (int z = 0; z < size1; z++) {
       vfm.add(horizontalFieldManager_left22 [z]);
       vfm.add(new SeparatorField());
      }

A: import java.util.Hashtable;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

public class ListAllEvents extends MainScreen {

// -----------------------------------------------------------------

VerticalFieldManager mainManager;

VerticalFieldManager listVFM;
HorizontalFieldManager rowHFM[];

int row_height;

LabelField[] eventTimeLabel;
LabelField[] eventNameLabel;

public ListAllEvents() {

    createUI();

    createEventHashtable();

}

// -------------- Create UI --------------------------------

public void createUI() {

    mainManager = new VerticalFieldManager(
            VerticalFieldManager.VERTICAL_SCROLL
                    | VerticalFieldManager.VERTICAL_SCROLLBAR
                    | VerticalFieldManager.USE_ALL_HEIGHT
                    | VerticalFieldManager.FIELD_LEFT | DrawStyle.LEFT) {

        protected void sublayout(int maxWidth, int maxHeight) {
            int displayWidth = Display.getWidth();
            int displayHeight = Display.getHeight();

            super.sublayout(displayWidth, displayHeight);
            setExtent(displayWidth, displayHeight);
        }

        public void paint(Graphics g) {
            g.setBackgroundColor(Color.WHITE);
            g.clear();
            super.paint(g);
        }
    };

    add(mainManager);

}

// ----------------------------Create List
// ----------------------------------------

public void createList(Hashtable eventHashtable) {

    listVFM = new VerticalFieldManager();

    rowHFM = new HorizontalFieldManager[eventHashtable.size()];

    eventTimeLabel = new LabelField[eventHashtable.size()];

    eventNameLabel = new LabelField[eventHashtable.size()];

    row_height = 90;

    int j = 0;
    int row_count = 0;

    if (eventHashtable.size() > 0) {

        EventItem ei = null;

        for (int i = 0; i < eventHashtable.size(); i++) {

            Object obj = eventHashtable.get(new Integer(i));

            final EventItem item = (EventItem) obj;

            if (item != null) {

                String str_event_time = item.event_time;
                String str_event_name = item.event_name;

                rowHFM[row_count] = new HorizontalFieldManager(
                        HorizontalFieldManager.USE_ALL_HEIGHT) {

                    protected void sublayout(int maxWidth, int maxHeight) {

                        int displayWidth = Display.getWidth();
                        int displayHeight = 80;

                        super.sublayout(displayWidth, displayHeight);
                        setExtent(displayWidth, displayHeight);
                    }

                };

                rowHFM[row_count].setPadding(2, 2, 2, 2);

                eventTimeLabel[row_count] = new LabelField(str_event_time) {

                    protected void layout(int maxWidth, int maxHeight) {

                        int displayWidth = (int) (Display.getWidth() / 2);
                        int displayHeight = maxHeight;

                        super.layout(displayWidth, displayHeight);
                        setExtent(displayWidth, displayHeight);
                    }

                };

                eventTimeLabel[row_count].setPadding(5, 0, 0, 2);

                eventNameLabel[row_count] = new LabelField(str_event_name) {

                    protected void layout(int maxWidth, int maxHeight) {

                        int displayWidth = (int) (Display.getWidth() / 2);
                        int displayHeight = maxHeight;

                        super.layout(displayWidth, displayHeight);
                        setExtent(displayWidth, displayHeight);
                    }

                };

                eventNameLabel[row_count].setPadding(5, 0, 0, 2);

                rowHFM[row_count].add(eventTimeLabel[row_count]);

                rowHFM[row_count].add(eventNameLabel[row_count]);

                listVFM.add(rowHFM[row_count]);

            }

        }

    }
    listVFM.setPadding(5, 2, 5, 2);

    mainManager.add(listVFM);

}

public void createEventHashtable() {

    String event_time1 = "8:00";
    String event_time2 = "8:00";

    String event_name1 = "Event 1";
    String event_name2 = "Event 2";

    Hashtable eventHashtable = new Hashtable();

    eventHashtable.put(new Integer(0), new EventItem(event_time1,
            event_name1));
    eventHashtable.put(new Integer(1), new EventItem(event_time2,
            event_name2));

    createList(eventHashtable);
}

 }

public class EventItem {

String event_time;
String event_name;

public EventItem(String event_time, String event_name) {
    this.event_name = event_name;
    this.event_time = event_time;
}

 }


text:
Q: Spring boot app gives error circular references why? I have this Configuration class:-
@Configuration
public class AppConfig {

    @Autowired
    private Environment env;
    private List<Weather> weathers = new ArrayList<>();

    @Bean
    public RestTemplate restTemplate() {
        var factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(3000);
        factory.setReadTimeout(3000);
        return new RestTemplate(factory);
    }

    @PostConstruct
    public void startMonitoring() {
        String url = env.getProperty("openWeatherUrl");
        String apiKey = env.getProperty("openWeatherApiKey");

        try (InputStream resource = app.class.getResourceAsStream("/config.csv")) {
            CSVReader reader = new CSVReader(new InputStreamReader(resource));
            String[] lineInArray;
            while ((lineInArray = reader.readNext()) != null) {
                Weather weather = new Weather();
                if (!lineInArray[0].contains("city")) {
                    weather.setCity(lineInArray[0]);
                } else {
                    continue;
                }

                if (!lineInArray[1].contains("temperaturesLimit")) {
                    weather.setTemperaturesLimit(Float.parseFloat(lineInArray[2]));
                }
                if (!lineInArray[2].contains("temperaturesLimit")) {
                    weather.setFrequency(Integer.parseInt(lineInArray[2]));
                }

                URI uri = new URI(url + "?q=" + weather.getCity() + "&units=metric&APPID=" + apiKey);
                weather.setUri(uri);
                weathers.add(weather);
            }
        } catch (IOException | CsvValidationException | URISyntaxException e) {
            System.out.println(e.getMessage());
        }
        fetchWeatherData();
    }

    void fetchWeatherData(){
        RestTemplate restTemplate = restTemplate();
        weathers.forEach(weather -> {
            var res = restTemplate.getForEntity(weather.getUri(), Weather.class);
        });
    }
}

I got error:-
The dependencies of some of the beans in the application context form a cycle:
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
Why is it circular? How do I fix it?

A: It's quite simple @PostConstruct in AppConfig relies on the RestTemplate bean but this @Bean is part of AppConfig.
This is due to how @Configuration classes work, they are proxied and a call to public RestTemplate restTemplate() would call the proxied method.
A simple fix would be removing the @Bean annotation from your RestTemplate method, if the RestTemplate is not used in other locations.


text:
Q: Postgresql array function doesn't use index I've created a postgresql array column with a GIN index, and I'm trying to do a contains query on that column. With standard postgresql I can get that working correctly like this:
SELECT d.name
FROM deck d
WHERE d.card_names_array @> string_to_array('"Anger#2","Pingle Who Annoys#2"', ',')
LIMIT 20;

Explain analyze:
Limit  (cost=1720.01..1724.02 rows=1 width=31) (actual time=7.787..7.787 rows=0 loops=1)
  ->  Bitmap Heap Scan on deck deck0_  (cost=1720.01..1724.02 rows=1 width=31) (actual time=7.787..7.787 rows=0 loops=1)
        Recheck Cond: (card_names_array @> '{"\"Anger#2\"","\"Pingle Who Annoys#2\""}'::text[])
        ->  Bitmap Index Scan on deck_card_names_array_idx  (cost=0.00..1720.01 rows=1 width=0) (actual time=7.785..7.785 rows=0 loops=1)
              Index Cond: (card_names_array @> '{"\"Anger#2\"","\"Pingle Who Annoys#2\""}'::text[])
Planning time: 0.216 ms
Execution time: 7.810 ms

Unfortunately (in this instance) I'm using QueryDSL with which I read the native array functions like @> are impossible to use. However, this answer says you can use arraycontains instead to do the same thing. I got that working, and it returns the correct results, but it doesn't use my index.
SELECT d.name
FROM deck d
WHERE arraycontains(d.card_names_array, string_to_array('"Anger#2","Pingle Who Annoys#2"', ','))=true
LIMIT 20;

Explain analyze:
Limit  (cost=0.00..18.83 rows=20 width=31) (actual time=1036.151..1036.151 rows=0 loops=1)
  ->  Seq Scan on deck deck0_  (cost=0.00..159065.60 rows=168976 width=31) (actual time=1036.150..1036.150 rows=0 loops=1)
        Filter: arraycontains(card_names_array, '{"\"Anger#2\"","\"Pingle Who Annoys#2\""}'::text[])
        Rows Removed by Filter: 584014
Planning time: 0.204 ms
Execution time: 1036.166 ms

This is my QueryDSL code to create the boolean expression:
predicate.and(Expressions.booleanTemplate(
        "arraycontains({0}, string_to_array({1}, ','))=true",
        deckQ.cardNamesArray,
        filters.cards.joinToString(",") { "${it.cardName}#${it.quantity}" }
))

Is there some way to get it to use my index? Or maybe a different way to do this with QueryDSL to use the native @> function?


text:
Q: Error initializing subclass of float This is what I'm doing:
class D(float):
    def __init__(self, name):
        self._name = name
        print name

But when I try to initialize on object of type D:
d = D('aaa')

I get this error:
Traceback (most recent call last):
  File "/home/user/untitled1.py", line 22, in <module>
    d = D('aaa')
ValueError: could not convert string to float: aaa

Why? I'm not initializing a float, just setting a name. I didn't call the __init__ of float.

A: The reason is that prior to inititalizer, that is __init__ function, a constructor, that is __new__, is called. It is called with the same arguments as __init__. As for your class it is not defined, it's superclass' one, that is float's, is called, and error is raised. You can see it if you wrap constructor:
>>> class D(float):
...     def __new__(cls, *args, **kwargs):
...         print cls, args, kwargs
...         return super(D, cls).__new__(cls, *args, **kwargs)
...     def __init__(self, value):
...         print value
...
>>> D('a')
<class '__main__.D'> ('a',) {}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __new__
ValueError: could not convert string to float: a

If you want add custom attributes, use something like follows:
>>> class D(float):
...     __slots__ = ['name']
...     def __new__(cls, *args, **kwargs):
...         name = kwargs.pop('name')
...         obj = super(D, cls).__new__(cls, *args, **kwargs)
...         obj.name = name
...         return obj
...
>>> d = D(0, name='d')
>>> e = D(1, name='e')
>>> d, d.name
(0.0, 'd')
>>> e, e.name
(1.0, 'e')


text:
Q: Fix some scratches on my Macbook pro please how can I repair these scratches on my Macbook pro they made me so sad.

A: Apple will put a new case around your existing working components for a flat rate repair - probably $350 these days, but I haven't checked.
You would want to file down the aluminum if it protrudes, but that won't look much better than the ragged dings you have shown. Unlike steel, aluminum doesn't repair well and the anodized coating that Apple performs to make the pebbled surface isn't something you can DIY replicate.
If you're just concerned with color, you might be able to get some modeling paint to make it a bit closer to the shade, but on close inspection it won't fool anyone. If that goes badly, you can still file off the paint and use sandpaper which is the last thing I would mention - that really looks bad in my opinion, so I would avoid that unless you are ready to pay for an Apple repair if you don't like what the grit of the sandpaper does to the finish.
Small metal files are much easier to control and limit the area of "rework" so unless you have sharp edges, I would leave it alone if you want to keep the area looking new as opposed to feeling smooth.


text:
Q: AJAX AND SQL Duplicate results I Have problem, I have ajax request and php script, when I click button, results duplicate.
HTML AND JS:

$("#more-news").click(function(e) {
    e.preventDefault();
    $.ajax({    //create an ajax request to load_page.php
        type: "GET",
        url: "/getnews.php",
        dataType: "html",   //expect html to be returned
        data: {
            lang: lng,
            last_id: last_id,
            ids: dataN
        },
        success: function(response){

            var content = document.getElementById("responsecontainer");
            content.innerHTML = content.innerHTML+response;

            //$("#responsecontainer").html(response);
            $('#more-news').attr('data-lim', Number($('#more-news').attr('data-lim')) + 10);
            //alert(response);
        }

    });
});

                <button id="more-news" data-lim="10" style="border:none" class="btn-type-one">
                    <?= $this->trans->t('More'); ?>
                </button>

<?php
$dtTTNews = [];
foreach ($front_page_news as $item) {
$dtTTNews[] = $item['id'];
?>
<? } ?>

PHP:

$ids = $_GET['ids'];

$dtNow = new \DateTime('now');

$db->set_charset("utf8");

$news_id = abs($db->real_escape_string($_GET['last_id']));

$date_now = new \DateTime('now');

$in = join(',', array_fill(0, count($ids), '?'));
//$q = $db->query("select * count(*)

$q = $db->query('SELECT * FROM news WHERE id < "'.$news_id.'" ORDER BY date_show DESC LIMIT 3');

//$q = $db->query('SELECT id, title_ru, title_md, body_ru, body_md, is_video, thumb_ru, thumb_md, date_show,title_ru, title_md
//FROM news GROUP BY id');

$lang = (isset($_GET['lang']) && $_GET['lang'] == 'ru') ? 'ru' : 'md';

$isHidden = false;

if($q->num_rows > 0):
    while($item = $q->fetch_assoc()):
        $dtNews = new \DateTime($item['date_show']);

        if ($dtNews > $dtNow) {
            $isHidden = true;
            break;
        }

        $qs = $db->query("SELECT * FROM news_categories WHERE news_id = " . $item['id']);
        if($qs->num_rows > 0) {
            $dd = $qs->fetch_assoc();

            $qss = $db->query("SELECT * FROM categories WHERE id = " . $dd['categories_id']);
            $dd2 = $qss->fetch_assoc();

            if(in_array('Скрытые новости', $dd2) || in_array('Hidden News', $dd2)) {
                $isHidden = true;
                break;
            }

        }

        $dtShow = $dtNews->format("Y-m-d");
        //$dtShow = \Noitools\Utils::timeFromPost($item['date_show'], $lang);

        if($item['active'] == '1'):
            if($item['body_' . $lang] != ''):
                if(!$isHidden):
?>

        <div class="article-item" data-news="<?= $item['id']; ?>">
            <a href="/<?=$lang?>/news_id/<?=$item['id']?>"
               class="link-img-wrap<?= ($item['is_video']) ? ' video-icon-medium' : ''; ?>">
                <img src="/uploads/newsthumbs/760_500/<?=$item['id']?>.jpg"
                     alt="">

                <?=$dtShow?>

                <a href="news_cat/<?= $dd2['id'] ?>" class="standard-hover-link"><?= $dd2['title_' . $lang] ?>;

<a href="/<?=$lang?>/news_id/<?=$item['id']?>"><?=$dtShow?> <?= $item['title_' . $lang] ?>

                <?= mb_substr(strip_tags($item['body_' . $lang]), 0, 180,
                    'utf-8') ?>

<?php  endif; endif; endif; endwhile; endif; ?>

How I Can Fix this duplicates? I think, because LIMIT 3, when I click button he load 3 same elements ..
I want when I click button more, load 3 more news

A: On first glance it appears that the problem lies with you SQL statement:
$q = $db->query('SELECT * FROM news WHERE id < "'.$news_id.'" ORDER BY date_show DESC LIMIT 3');

Since you are appending the Ajax results each time, you only want to fetch news results that you haven't fetched before. By using less than, you are fetching ALL results less than $news_id, each time.
What you need to do is to window your results. In other words, you need to have a starting id and then fetch several more records. So:
$q = $db->query('SELECT * FROM news WHERE id > "'.$news_id.'" ORDER BY date_show DESC LIMIT 3');

And as long as you keep passing the new id (last_id in your javascript), as the last record fetched, it should work.
The other problem you may have is your ordering. You need to order the same way that you are comparing. If comparing by id, you need:
$q = $db->query('SELECT * FROM news WHERE id > "'.$news_id.'" ORDER BY id ASC LIMIT 3');

If comparing by date then something like:
$q = $db->query('SELECT * FROM news WHERE date_show < "'.$date_show.'" ORDER BY date_show DESC LIMIT 3');

You can't mix both id and date_show. Unless you know that id and date_show are strictly in the same order.


text:
Q: Triple (ring) buffering doesn't increase the FPS I'm creating a drawing app with Metal. Unlike other drawing app, my app stores all strokes as data model rather than just saving the bitmap result after drawing, the goal of this approach is allowing users to use eraser tool and remove a stroke without touching other strokes.
When user erase a stroke, the app have to render remaining strokes on the screen again, so the function to render all strokes on the screen should be as fast as possible, but I'm having problem with it.
When render strokes on the screen, I use this function:
    func renderStroke(strokes: [Stroke]) {
        let commandBuffer = commandQueue?.makeCommandBuffer()
        let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderer.renderPassDescriptor)
        commandEncoder?.setRenderPipelineState(pipelineState)

        var allPoints = [MetalStrokePoint]()

        for stroke in strokes {
            let pointsAlongPath = stroke.cachedPointsAlongPath
            allPoints.append(contentsOf: pointsAlongPath)
        }

        let pointsAlongPathBuffer = sharedDevice?.makeBuffer(bytes: allPoints, length: MemoryLayout<MetalStrokePoint>.stride * allPoints.count, options: .cpuCacheModeWriteCombined)

        if let pointsAlongPathBuffer {
            commandEncoder?.setVertexBuffer(pointsAlongPathBuffer, offset: 0, index: 0)
            commandEncoder?.setVertexBuffer(renderer.uniformBuffer, offset: 0, index: 1)
            commandEncoder?.setVertexBuffer(renderer.transformBuffer, offset: 0, index: 2)

            commandEncoder?.setFragmentTexture(self.stampTexture, index: 0)

            commandEncoder?.drawPrimitives(type: .point, vertexStart: 0, vertexCount: pointsAlongPath.count)
        }

        renderer?.commitCommandBufer()
    }

I tested to render 4000 strokes to the screen by calling this function in a CADisplayLink loop, the length of the buffer is 4'000'000 (Is that too much for Metal to handle?) and the FPS of the app is 12 FPS - That is way too slow and make my app not responsive.
Then some guys here have suggested not to create a new buffer for each draw call:
Poor performance in Metal drawing app when render more than 4000 strokes.
So I implemented ring buffer to reuse buffer for each draw call:
    func renderStroke(strokes: [Stroke]) {
        // Wait for a free ring buffer
        renderer?.ringBufferSemaphore?.wait()

        let commandBuffer = commandQueue?.makeCommandBuffer()
        let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderer.renderPassDescriptor)
        commandEncoder?.setRenderPipelineState(pipelineState)

        var allPoints = [MetalStrokePoint]()

        for stroke in strokes {
            let pointsAlongPath = stroke.cachedPointsAlongPath
            allPoints.append(contentsOf: pointsAlongPath)
        }

        // Reuse ring buffer to avoid creating new buffer
        let ringBuffer = renderer.ringBuffers.getCurrentRingBuffer()

        let ringBufferContents = ringBuffer.contents().bindMemory(to: MetalStrokePoint.self, capacity: allPoints.count)

        for (pointIndex, point) in allPoints.enumerated() {
            ringBufferContents[pointIndex] = point
        }

        commandEncoder?.setVertexBuffer(ringBuffer, offset: 0, index: 0)
        commandEncoder?.setVertexBuffer(renderer.uniformBuffer, offset: 0, index: 1)
        commandEncoder?.setVertexBuffer(renderer.transformBuffer, offset: 0, index: 2)

        commandEncoder?.setFragmentTexture(self.stampTexture, index: 0)

        commandEncoder?.drawPrimitives(type: .point, vertexStart: 0, vertexCount: pointsAlongPath.count)

        // Signal to free current ring buffer
        renderer.commandBuffer?.addCompletedHandler({ commandBuffer in
            renderer.ringBufferSemaphore?.signal()
        })

        renderer?.commitCommandBufer()
    }

Result: CPU usage recuced by 5% but the FPS do not change. Am I doing anything wrong here or just ring buffers do not help in this case?


text:
Q: Syncing Google Calendar with iPhone Alarms Does anyone know if there is a way to make google calendar alerts more intrusive on an iPhone? Currently, you just get a weak push notificiation, which is very easy to be ignored by accident.
One way would be to automatically sync calendar events with phone alarms (which are very intrusive, as they have to be manually disabled by users).
Is something like this possible with a jailbroken iPhone?

A: All you have to do is to choose a long and loud ringtone as your calendar alert sound. Try it, it works, and doesn't require any technical manipulation. You can change the alert from the preferences (and not within calendar itself).
You will probably have to make a ringtone yourself if the regular ones seem too harmless... A ringtone can be as long as 30 seconds. Here is how to make one: http://www.digitaltrends.com/mobile/how-to-make-ringtones-for-iphone/
You can also set a second alarm in calendar for an event. It will be hard to miss two consecutive alerts of 30 seconds!

A: This worked for me!

*

*Synchronize Apple Calendar and Google Calendar by going to Settings -> Calendar -> Accounts -> Gmail(sign in to your account) -> turn on sync Calendars. As long as the notification is set up on Google Calendar, it will also notify you on Apple calendar.

*Then you can go to Settings -> Calendar Alerts. There you can set up a ringtone of your choosing that is long.
Voila! Your notifications should now behave just like an alarm.

Note:

*

*Adding events to Apple Calendar will not add them to Google Calendar, but the other way around works! Add events to Google Calendar as usual.


text:
Q: Meta-analysis of rates in R I am currently doing a meta-analysis using a standardized metric i.e., defined daily dose (DDD) per 1000 inhabitant days. I initially thought that metarate function in R is appropriate, but as I performed the analysis I noticed that I require the raw DDD and inhabitant-days value, which were not reported in the included studies. Basically, DDD/1000 inhabitant-days are like incidence/person-years. However, the 'DDD' parameter is not the same as events, which complicates the analysis. I already have the desired effect sizes i.e., DDD/1000 inhabitant-days, but I'd like to weight the effect sizes according to the sample sizes
UPDATE: I am now sure that a meta-analysis of rates is the appropriate method to combine these data. However, from each study, I only have the rate i.e., DDD/1000 inhabitant-days and the sample size (which could be used as the denominator; please refer to Bitterman et al. for further reference); I don't have the events and person-time data, which are required in the metarate function in the meta package. Is there a function in R where I can input the rate and weigh them according to the sample sizes, using random-effects model?
Here is the sample dataset (NOT for the purpose of replicating the analysis, but only as an illustration of the state of the data I currently have)

Thank you very much in advance


text:
Q: Procedure to get employees average salary and increase it if it is below average I'm trying to create package and procedure where i find all employes that are working in a job that starts with MA or SA and if their salary is below average salary, then increase their salary by 33%.
I can't find the problem and make it work.
Here is the code, can't get it to work:
create or replace package body name2 as
procedure one(
alga emp.sal%type,
new_sal emp.sal%type)
cursor kursors1 is
select ename, sal from emp where job LIKE 'MA%' OR e.job LIKE 'SA%' for update sal;
begin
select round(avg(sal),2) videja_alga into alga from emp
for darb in kursors1
loop
if darb.sal < alga then
new_sal:=darb.sal+(darb.sal*0.33);
dbms_output.put_line('New sal: ' || darb.sal);
update emp set sal = new_sal where current of kursors1;
end if;
end loop;
end;
end name2;
/

A: Please put proper next time. Its really hard to interpret otherwise.
CREATE OR REPLACE PACKAGE BODY name2
AS
   PROCEDURE one (alga emp.sal%TYPE, new_sal emp.sal%TYPE)
   AS
      CURSOR kursors1
      IS
         SELECT ename, sal
           FROM emp
          WHERE job LIKE 'MA%' OR e.job LIKE 'SA%';
   BEGIN
      SELECT ROUND (AVG (sal), 2) videja_alga
        INTO alga
        FROM emp;

      FOR darb IN kursors1
      LOOP
         IF darb.sal < alga
         THEN
            new_sal := darb.sal + (darb.sal * 0.33);
            DBMS_OUTPUT.put_line ('New sal: ' || darb.sal);

            UPDATE emp
               SET sal = new_sal
             WHERE CURRENT OF kursors1;
         END IF;
      END LOOP;
   END;
END name2;

Changes done:

*

*Removed  for update sal from cursor. I am not sure what it does as your simply looping through it.

*';' was missing in avg calculation select statement

*Added 'as' before cursor declaration as it is part of standard procedure creation.

This whole code can be done in much less, try using partition by that will give you avg value in the cursor itself and you can do the calculation in the cursor itself with just an update below which will loop through the cursor.


text:
Q: Convert Specific BitmapImage Colour to Transparent I'm currently recreating my Image Explorer application, formerly written in Windows Forms to the Windows Presentation Framework.
My WinForms application was using the WindowsThumbnailProvider from @DanielPeñalba (See this link for the original version of the code)
WinForms Version - Successfully converting 0 alpha, 0 red, 0 green and 0 blue to Transparent

WPF Version - Almost working

WPF Code - Slightly modified version of the original WindowsThumbnailProvider to support System.Windows.Media.Imaging.BitmapImage instead of System.Drawing.Bitmap
MainWindow.xaml - For all the testing
<Window x:Class="WpfFileFolderThumbnails.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfFileFolderThumbnails"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="600">
    <Grid>
        <Image x:Name="ThumbnailImage1" HorizontalAlignment="Left" Height="256" Margin="10,20,0,0" VerticalAlignment="Top" Width="256"/>
        <Image x:Name="ThumbnailImage2" HorizontalAlignment="Left" Height="256" Margin="326,20,0,0" VerticalAlignment="Top" Width="256"/>
    </Grid>
</Window>

MainWindow.xaml.cs - Test code to call the GetThumbnail and CreateAlphaBitmapImage methods
using System.Windows;

namespace WpfFileFolderThumbnails
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();

            var thumbnail = WindowsThumbnailProviderWpf.GetThumbnail(@"D:\Pictures\Art\Anime", 256, 256,
                ThumbnailOptions.ThumbnailOnly);

            var alphaThumbnail = WindowsThumbnailProviderWpf.CreateAlphaBitmapImage(thumbnail);

            this.ThumbnailImage1.Source = thumbnail;
            this.ThumbnailImage2.Source = alphaThumbnail;
        }
    }
}

WindowsThumbnailProviderWpf.cs - Class to get Folder Thumbnail and make it Transparent
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Path = System.IO.Path;

namespace WpfFileFolderThumbnails
{
    [Flags]
    public enum ThumbnailOptions
    {
        None = 0x00,
        BiggerSizeOk = 0x01,
        InMemoryOnly = 0x02,
        IconOnly = 0x04,
        ThumbnailOnly = 0x08,
        InCacheOnly = 0x10,
    }

    public static class WindowsThumbnailProviderWpf
    {
        private const string IShellItem2Guid = "7E9FB0D3-919F-4307-AB2E-9B1860310C93";

        [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern int SHCreateItemFromParsingName(
            [MarshalAs(UnmanagedType.LPWStr)] string path,
            // The following parameter is not used - binding context.
            IntPtr pbc,
            ref Guid riid,
            [MarshalAs(UnmanagedType.Interface)] out IShellItem shellItem);

        [DllImport("gdi32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool DeleteObject(IntPtr hObject);

        [ComImport]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        [Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
        internal interface IShellItem
        {
            void BindToHandler(IntPtr pbc,
                [MarshalAs(UnmanagedType.LPStruct)]Guid bhid,
                [MarshalAs(UnmanagedType.LPStruct)]Guid riid,
                out IntPtr ppv);

            void GetParent(out IShellItem ppsi);
            void GetDisplayName(SIGDN sigdnName, out IntPtr ppszName);
            void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
            void Compare(IShellItem psi, uint hint, out int piOrder);
        };

        internal enum SIGDN : uint
        {
            NORMALDISPLAY = 0,
            PARENTRELATIVEPARSING = 0x80018001,
            PARENTRELATIVEFORADDRESSBAR = 0x8001c001,
            DESKTOPABSOLUTEPARSING = 0x80028000,
            PARENTRELATIVEEDITING = 0x80031001,
            DESKTOPABSOLUTEEDITING = 0x8004c000,
            FILESYSPATH = 0x80058000,
            URL = 0x80068000
        }

        internal enum HResult
        {
            Ok = 0x0000,
            False = 0x0001,
            InvalidArguments = unchecked((int)0x80070057),
            OutOfMemory = unchecked((int)0x8007000E),
            NoInterface = unchecked((int)0x80004002),
            Fail = unchecked((int)0x80004005),
            ElementNotFound = unchecked((int)0x80070490),
            TypeElementNotFound = unchecked((int)0x8002802B),
            NoObject = unchecked((int)0x800401E5),
            Win32ErrorCanceled = 1223,
            Canceled = unchecked((int)0x800704C7),
            ResourceInUse = unchecked((int)0x800700AA),
            AccessDenied = unchecked((int)0x80030005)
        }

        [ComImport()]
        [Guid("bcc18b79-ba16-442f-80c4-8a59c30c463b")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        internal interface IShellItemImageFactory
        {
            [PreserveSig]
            HResult GetImage(
            [In, MarshalAs(UnmanagedType.Struct)] NativeSize size,
            [In] ThumbnailOptions flags,
            [Out] out IntPtr phbm);
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct NativeSize
        {
            private int width;
            private int height;

            public int Width { set { this.width = value; } }
            public int Height { set { this.height = value; } }
        };

        [StructLayout(LayoutKind.Sequential)]
        public struct RGBQUAD
        {
            public byte rgbBlue;
            public byte rgbGreen;
            public byte rgbRed;
            public byte rgbReserved;
        }

        public static BitmapImage GetThumbnail(string fileName, int width, int height, ThumbnailOptions options)
        {
            IntPtr hBitmap = GetHBitmap(Path.GetFullPath(fileName), width, height, options);

            try
            {
                // return a System.Drawing.Bitmap from the hBitmap
                return GetBitmapImageFromHBitmap(hBitmap);
            }
            finally
            {
                // delete HBitmap to avoid memory leaks
                DeleteObject(hBitmap);
            }
        }

        public static BitmapImage GetBitmapImageFromHBitmap(IntPtr nativeHBitmap)
        {
            var bmpSource =  Imaging.CreateBitmapSourceFromHBitmap(nativeHBitmap,
                                                                    IntPtr.Zero,
                                                                    Int32Rect.Empty,
                                                                    BitmapSizeOptions.FromEmptyOptions());

            var bmpImage = BitmapSourceToBitmapImage(bmpSource);

            return bmpImage;
        }

        // Conversion code
        public static BitmapImage BitmapSourceToBitmapImage(BitmapSource bitmapSource)
        {
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            MemoryStream memorystream = new MemoryStream();
            BitmapImage tmpImage = new BitmapImage();
            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            encoder.Save(memorystream);

            tmpImage.BeginInit();
            tmpImage.StreamSource = new MemoryStream(memorystream.ToArray());
            tmpImage.EndInit();

            memorystream.Close();
            return tmpImage;
        }

        public static BitmapImage CreateAlphaBitmapImage(BitmapImage sourceBitmapImage)
        {
            var bmp = sourceBitmapImage.Clone();
            var pixels = new int[(int)bmp.Width * (int)bmp.Height];
            var stride = (bmp.PixelWidth * bmp.Format.BitsPerPixel + 7) / 8;

            bmp.CopyPixels(pixels, stride, 0);
            var oldColor = pixels[0];
            var red = 255;
            var green = 255;
            var blue = 255;
            var alpha = 0;
            var color = (alpha << 24) + (red << 16) + (green << 8) + blue;

            for (var i = 0; i < (int)bmp.Width * (int)bmp.Height; i++)
            {
                if (pixels[i] == oldColor)
                {
                    pixels[i] = color;
                }
            }

            //remake the bitmap source with these pixels
            var source = BitmapSource.Create(bmp.PixelWidth, bmp.PixelHeight, bmp.DpiX, bmp.DpiY, PixelFormats.Bgra32, bmp.Palette, pixels, stride);

            //return sourceBitmapImage;
            return BitmapSourceToBitmapImage(source);
        }

        private static IntPtr GetHBitmap(string fileName, int width, int height, ThumbnailOptions options)
        {
            IShellItem nativeShellItem;
            Guid shellItem2Guid = new Guid(IShellItem2Guid);
            int retCode = SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out nativeShellItem);

            if (retCode != 0)
                throw Marshal.GetExceptionForHR(retCode);

            NativeSize nativeSize = new NativeSize();
            nativeSize.Width = width;
            nativeSize.Height = height;

            IntPtr hBitmap;
            HResult hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out hBitmap);

            Marshal.ReleaseComObject(nativeShellItem);

            if (hr == HResult.Ok) return hBitmap;

            throw Marshal.GetExceptionForHR((int)hr);
        }
    }
}

While i understand i could just simply reference System.Drawing and use the already working solution, i'd like to know if it's possible to do the same thing in WPF.
Question - Is there a simple way to loop through each pixel of a BitmapImage (similar to a Bitmap), change a specific pixel combination and create a copy of the BitmapImage with transparency?

A: You may call CopyPixels on a BitmapSource to get the raw pixel buffer, then modify the buffer as you like, and create a new BitmapSource from the modified buffer.
The method below shows how this could work for a BitmapSource with a 32-bit BGRA format.
private static BitmapSource CreateTransparency(BitmapSource source)
{
    if (source.Format != PixelFormats.Bgra32)
    {
        return source;
    }

    var bytesPerPixel = (source.Format.BitsPerPixel + 7) / 8;
    var stride = bytesPerPixel * source.PixelWidth;
    var buffer = new byte[stride * source.PixelHeight];

    source.CopyPixels(buffer, stride, 0);

    for (int y = 0; y < source.PixelHeight; y++)
    {
        for (int x = 0; x < source.PixelWidth; x++)
        {
            var i = stride * y + bytesPerPixel * x;
            var b = buffer[i];
            var g = buffer[i + 1];
            var r = buffer[i + 2];
            var a = buffer[i + 3];

            if (...)
            {
                buffer[i + 3] = 0d; // set transparent
            }
        }
    }

    return BitmapSource.Create(
        source.PixelWidth, source.PixelHeight,
        source.DpiX, source.DpiY,
        source.Format, null, buffer, stride);
}


text:
Q: How to save variables after quitting application in Kotlin I'm trying to create a flashcards app in Kotlin but I'm not sure how to make the flashcards I create save after exiting.
val flashCards = FlashCardList(50)
flashCards.addCard(inputTerm.text.toString(),inputDefinition.text.toString(),false)

This above code creates a list of Flashcards (size 50) with term and definition and then adds to it. How would I make this save even after exiting? My understanding from searching is to use sharedpreferences
but even after reading some explanations I don't really understand how I would use that here. If someone could turn my above code into one that uses sharedpreferences (or any form of saving variables) I could try to understand what's going on from that.
(This is another post on this forum that I read but couldn't understand in case someone else tries to link it: save variables after quitting application?)

A: As we need to store custom modals in shared preference, we need to make objects serialisable. Gson is google's library which can do this. Use Gson library first and then :
Storing in shared preference :
val flashCards = FlashCardList(50)
flashCards.addCard(inputTerm.text.toString(),
   inputDefinition.text.toString(),false)
var gson = Gson()

// Convert our object in json string
var jsonFlashCards = gson.toJson(flashCards);
Log.d("TAG","jsonFlashCards = " + jsonFlashCards);

// store json in shared preference
var appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());
var prefsEditor = appSharedPrefs.edit();
prefsEditor.putString("MyObject", jsonFlashCards)
prefsEditor.commit()

Reading from shared preference :
// Get json from shared preference
var appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());
var gson = Gson();
var jsonFlashCards = appSharedPrefs.getString("MyObject", "");

// Convert json string to array list
Type type = new TypeToken<List<FlashCardList>>(){}.getType();
List<FlashCardList> carsList = gson.fromJson(jsonFlashCards, type);

To add Gson in your project : Gson library in Android Studio
Reference :

*

*https://stackoverflow.com/a/22019470/1994950

*https://stackoverflow.com/a/15011927/1994950

A: You can also use Serialization in position of GSON (just extent you'r class with Serializable), after that you can save & retrieve it, from shared Pref.
fun <T : Serializable?> saveSerializable(
context: Context,
objectToSave: T,
fileName: String?
) {
try {
    val fileOutputStream: FileOutputStream =
        context.openFileOutput(fileName, Context.MODE_PRIVATE)
    val objectOutputStream = ObjectOutputStream(fileOutputStream)
    objectOutputStream.writeObject(objectToSave)
    objectOutputStream.close()
    fileOutputStream.close()
} catch (e: IOException) {
    e.printStackTrace()
}
}

fun <T : Serializable?> readSerializable(
context: Context,
fileName: String?
): T? {
var objectToReturn: T? = null
try {
    val fileInputStream = context.openFileInput(fileName)
    val objectInputStream = ObjectInputStream(fileInputStream)
    objectToReturn = objectInputStream.readObject() as T
    objectInputStream.close()
    fileInputStream.close()
} catch (e: IOException) {
    e.printStackTrace()
} catch (e: ClassNotFoundException) {
    e.printStackTrace()
  }
  return objectToReturn
  }

A: Using shared preferences, you can save the variables that have only primitive types like an integer, string, float, and so on. In your case I would create a class with name for example "FlashCardData" that was store all the data for your FlashCard and create the two methods inside it, the first one will return all it's data as a json string which then you can store in the app's SharedPreferences and the second method (or you can instead create a secondary constructor for the class) that will take a json string with the data for the FlashCard and return an instance of FleshCardData class filled with data from json string. And finally i would pass a FlashCardData class to the FlashCard constructor where then the FlashCard will take all the needed data from it, and also i would create a method inside a FlashCard that will return an istance of FlashCardData that was pass to the FlashCard constructor.


text:
Q: How can I allow pages on CakePHP? I am trying to allow some pages in my project from Cake function beforeFilter, but it's not working at all. The only allowed page is the 'login' page. I am using this function on the controller 'PagesController':
public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow(array('login', 'definition'));
    }

Please, help me! I've started to learn CakePHP recently, so I'm having some problems with it. :\

A: Give the fuction name of pages controller in $this->Auth->allow();
public function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow(array(
        'login',
        'definition',
        'give here your pages controller function name'
        )
   );
}


text:
Q: Take a toll on X versus take a toil on X
"Your majesty, the princess is just tired from using too much
strength... also, the silver she came in contact with took a toil on
her!"

I see both, but just realized they don't mean the same thing. Or am I wrong? However, they're used to mean the same thing, but toil doesn't make sense, does it?

A: Toll is correct.  I think toil must just be a typographical error.  She might have got tired from excessive toil, but the assertion is that the silver took a toll.


text:
Q: Java error : R cannot be resolved to a variable , Parsing Data for android-21 failed I have searched for a solution to my problem on stack overflow . Before marking this question as duplicate, please understand that I have tried all the possible solutions that were posted, but I still have the above errors. I am running the default Hello World android program, so haven't made any changes in the code . The Minimum supported sdk version=8,Target build = sdk android API 21, Compiler sdk= android API 21 and Environment: Eclipse Juno.
Things that I tried :
    -

*

*I have deleted appcompat v4.jar from the appcompat workspace folder, which leaves me with just appcompat v7.jar

*I have added appcompat_support_v7.jar as external jar.

*I have tried refreshing, restarting eclipse and cleaning but errors still persist.
Error being: "R cannot be resolved to a variable Type: Java Error".

*For android 5,  JRE 1.8 is needed so I have installed that and set the windows environment variable to the path  where jdk1.8 is saved.
i.e. JAVA_HOME=C:\Program Files\Java\jdk1.8.0_31

*Using cmd when i do echo %JAVA_HOME% it prints the above path. Though I am still unable to run java programs from cmd using 'javac'.

*I have then set the path for jdk1.8 by going to Eclipse, window>preference>java>installed jres , the path being : C:\Program Files\Java\jre1.8.0_31

*I have also then gone to Eclipse, window>preference>java>installed jres>execution environment and checked the compatiability of SE 8.

*Even after restarting Eclipse, the first error I get is :
"Parsing Data for android-21 failed
Unsupported major.minor version 51.0".
and at the bottom in the problems tab ,the error I get is :
"R cannot be resolved to a variable -  Java Error"

*My Android Support library is up to date and  I have installed all the necessary packages using SDK manager for Android API 17 and 21 .

Please note that I have JRE 6 ,7 and 8 installed on my computer because I am using those versions in another eclipse for J2EE, but in eclipse (Juno) for android I have set the path for jdk 1.8.
I think it has got something to do with Java installation, but I don't understand what exactly I have done wrong. It would be great if you could help me out. Thanks in advance.

A: As you did not mention this in your checklist I was wondering: did you make sure that you do not have any uppercase letter in your resources file names? For example if you have a drawable named myIcon.png, you should rename it my_icon.png
I spent hours with a completely broken project just because of that, I wish this could be as simple in your case!?

A: 1) Check that appcompat_support_v7.jar really is pointing to the right location by going under project -> properties.
2) Clean (even though you've done it already)


text:
Q: sort of arrays and their position I have a sort problem.
I have two array
int a[] ={index1,index2,index3...indexI};
int b[] ={num1,num2,num3.......numI};

Array b[] is having numbers in random order but their position corresponds to position in a[].
For example num1 is the value of index1, num2 is the value of index2.
The problem is:
I need to sort the b[] elements in descending order, at the same time I need to move the a[] elements position according to the sorted order of b[].
I can sort b[] in descending order using one of the sort algorithm but I am not able handle the simultaneous move of the a[] elements according to the b[] position change.
My final output  I am expecting is a[] indexes arranged in descending order of their values in b[].
Please help.
Thanks

A: int a[] ={index1,index2,index3...indexI};
int b[] ={num1,num2,num3.......numI};
int c[] = {{num1, index1}, {num2, index2}...{indexI, numI}}
sort(c);
for i = 0 to c.len
  print c[i][1]

In c++ I would use a vector of pairs. In other languages you can use a structure.

A: If I get it correcty yu want to have something like this a = [0 1 2]; b = [5 2 8] and after sorting a = [1 0 2]; b = [2 5 8].
Which ever sorting algorithm you must just remember to change index arrays when changing number's position:
eg. swapping two positions (pseudocode)
swap(i, j): // i, j - indexes
   (b[i], b[j]) = (b[j], b[i]) // swap values
   (a[i], a[j]) = (a[j], a[i]) // swap the indexes

A: After you've sorted b, you can sort a by a comparison function that looks up values in b.
// assuming b is visible at the module level, you can pass this to qsort
int compare_by_indexing_into_b(void const *a, void const *b)
{
    int i = *(int const *)a;
    int j = *(int const *)b;

    return b[i] - b[j];
}

A: You can do it in two paths: first, sort a using your favorite sorting algorithm, but instead  of comparing a[i] to a[j] directly, compare b[a[i]] to b[a[j]]. Now re-arrange b according to the indexes in a - and you are done.
The second step may look like this (in pseudocode):
var c = new int[b.length]
for (int i = 0 ; i != a.length ; i++)
    c[i] = b[a[i]]
b = c

A: This shows one of the downfalls of using parallel arrays instead of an array of struct. The simple solution would be to convert your code to use
 struct {int index, num;} a[] = {{index1, num1},{index2, num2}, ...};

If your codebase already makes heavy use of parallel arrays, you can write a sort which is aware of such difficulties. You could pass it an array of arrays, rather than a single one, and write the sort to perform its swaps across every array, while only performing comparisons on the first. In other words:
void sort_pa(void **arrays/*NULL-terminated*/, int len,int size, int(*cmp)(...)))

Which you would then use:
int a[] ={index1,index2,index3...indexI};
int b[] ={num1,num2,num3.......numI};
int *c[] = {b, a, NULL};

sort_pa(c, I, sizeof **c, cmp);

A: Using qsort, you will sort the array a using the following comparison expression:
b[*(int*)elem1] - b[*(int*)elem2]

where elem1 and elem2 are the two pointer arguments to the comparator function (let b be visible by the function).
This will leave the array b untouched, and b[a[i]] will give the b elements in decreasing order.


text:
Q: Why does my javascript button dissapear onlick(in-line method) I know some javascript but never quite understood why this code makes the buttons disappear.
<input type="button" name="clickable" value="Click me!" onclick="clicked();">

OR
<button onclick="clicked();">Clickity</button>

Here is my function
function clicked() {
    document.write("Thank you");
}

As you can see it is not telling the element to hide or anything like that. Can someone explain this? A solution would be nice.
JSBin

A: Because you write your document to "Thank you"
Try to use alert or console.log

A: document.write overwrites the existing HTML on the page.  You could try something like this:
Script:
function clicked() {
    document.getElementById('myOutput').innerHTML="Thank you";
}

HTML:
<input type="button" name="clickable" value="Click me!" onclick="clicked();">

A: You executed document.write() after the DOM was loaded and ready, which writes over the HTML of the entire page. This SO Answer will help elaborate.


text:
Q: Unable to find file 'path/NA' when knitting to word_document2 using tbl_summary but works for PDF, HTML etc before you click "next", this is not a path file error.
I am building on a blogpost: https://labrtorian.com/2019/08/26/rmarkdown-template-that-manages-academic-affiliations/
It works well for scientific papers.
My problem is:
In Rmarkdown when calling a data frame I am returned with the error about not being able to find file 'path/NA'

    ---

    output:
     bookdown::word_document2:
        pandoc_args:
          - --reference-doc=Extras/Reference_Document.docx
        keep_tex: TRUE

    ---

    ```{r MRE}

    library(gtsummary)
    a <- c(10,20,30,40)
    b <- c('book', 'pen', 'textbook', 'pencil_case')
    c <- c(TRUE,FALSE,TRUE,FALSE)
    d <- c(2.5, 8, 10, 7)
    df <- data.frame(a,b,c,d)

    tbl_summary(df)
    tbl_summary

which returns:

Error: could not find file '/Users/brianbrummer/Documents/Rstudio/Affilitations_template/NA'
Execution halted

So what gives? I would usually know how to fix a "path not found" error, but not a file...and the file is NA?
files referenced in YAML can be found:
https://github.com/bridaybrummer/author_affiliations_extras.git
Thanks in advance

A: I did some digging and found the issue and a solution. First, if you update your yaml to call the reference document like this, you won't get the error any longer.
---
output:
  word_document:
    reference_doc: Reference_Document.docx
---

The issue was with the flextable package. If you're looking for community service points, you can post this reprex to their github page to alert them to the issue.
---
output:
  word_document:
    pandoc_args:
      - --reference-doc=Reference_Document.docx
---

```{r MRE}
mtcars |>
  flextable::flextable()
```


text:
Q: Android Service upding UI with timer crashing So I'm trying to update an overlay with a timer however it always crashes. I read something about UI thread but I'm kinda lost on what that even means.
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

    WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    overlayView.getBackground().setAlpha(50);
    windowManager.addView(overlayView, params);

    new Thread(new Runnable() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //crashing here//
                overlayView.getBackground().setAlpha(150);
                //testing if updating
                counter = counter + 1;
                notification.setContentText("number" + counter);
                startForeground(1, notification.build());
            }

        }
    }).start();

    return START_NOT_STICKY;
}

It always returns this error:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the
original thread that created a view hierarchy can touch its views.

A: Android do not allow updating UI from any thread except UI/Main thread. I see you have created a new Thread so your updating UI stuff is on a worker thread which is not allowed in Android.
A simple solution is to create a handler of main thread and post a runnable to it.
new Handler(Looper.getMainLooper()).post(new Runnable() {
       public void run() {
            // modify UI here
            // overlayView.getBackground().setAlpha(150);
       }
});


text:
Q: Only allow write access on property to Entity Framework Is there any way to only allow Entity Framework classes to write/read the EmailJson property ? The code works without this but it would be much cleaner if this property could not be altered by any code since having invalid json in it would throw an exception.
I cannot use a backing property because of the generic requirement.
public class EmailEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    public string EmailJson { get; set; }

    public T GetEmail<T>() where T : BaseEmailModel
    {
        return JsonConvert.DeserializeObject<T>(EmailJson);
    }

    public void  GetEmail<T>(T emailModel) where T : BaseEmailModel
    {
        EmailJson = JsonConvert.SerializeObject(emailModel);
    }
}

A: I suggest using a seperate data access tier (for example a class 'EmailEntityService') that is responsible for all access to EmailEntity. All code throughout your solution should only use this service then. If you move EmailEntity to a seperate project you can ensure that access to it is only possible via EmailEntityService (if you keep that service in a project holding a reference to the 'entity project').
So at the end you have (at least) three projects:
1: Entity project
2: Entity services project (with a reference to 1, this project ensures entities cannot be altered directly)
3: Business logic project (with a reference to 2 but not to 1 to prevent direct access to entities)
Since entity classes are just POCOs I don't see any other possibilities to do this on a more technical/basic way.


text:
Q: VBA Pivot deselect values to select a single value Im trying to create a VBA to eventually loop through a given list filtering out one value at a time from a Pivot table. The issue is with deselecting all options and choosing 1 value. How do you perform this?
The solution below (which i got to work is too slow):
What im trying below is to select the 1st value, then loop through the rest to deselect them and finally choosing the value i want. Is there a faster way to do this?
With ActiveSheet.PivotTables("PivotTable2")
.PivotFields("Name").PivotItems(1).Visible = True
For i = 2 To .PivotItems.Count 'Error here
.PivotItems(i).Visible = False
Next
With ActiveSheet.PivotTables("PivotTable2").PivotFields("Name")
    .PivotItems(SelectedPerson).Visible = True
End With
End With

A: Converting all my relevant comments to an answer.
.PivotItems in your code is referring to With ActiveSheet.PivotTables("PivotTable2"). It should refer to a PivotTable field. For example
ActiveSheet.PivotTables("PivotTable2").PivotFields(1).PivotItems.Count
'~~> OR something like
ActiveSheet.PivotTables("PivotTable2").PivotFields("Name").PivotItems.Count

You can read more about it in PivotItems object (Excel)

Even with this solution it is too slow, it would take me hours to wait for the entire data to loop through. Is there a way to "deselect" everything?

For a faster method, you can remove all filter in one go (without looping) and then simply add the relevant filter as shown below
Dim ws As Worksheet

'~~> Change this to the relevant sheet
Set ws = Sheet1

With ws.PivotTables("PivotTable2").PivotFields("Name")
    .ClearAllFilters

    .PivotFilters.Add Type:=xlCaptionEquals, _
                      Value1:="SOME VALUE"
                      '~~> OR something like
                      '~~> Value1:= ws.Range("A1").Value
End With

Tried both referencing a cell and direct text in VBA. Is it possible that the value is somehow formattet wrongly in the pivot data? As in text in my cell im refering to but something else in the Pivot? – Carlsberg789 24 mins ago

Screenshot in action


text:
Q: JQuery table sorter displays the entire results first and then does the pagination I get tens of thousands of records from the server for the jquery tablesorter plug-in (http://mottie.github.io/tablesorter/docs/index.html) to perform sorting and pagination. I noticed that tablesorter first dislplays all the data on the UI and then perform the pagination. This results the user see the full results for few seconds and then suddenly the pagination starts. Is this the behavior which any one else also noticed or do you think that this could be due to some issues in the way I have configured the tablesorter ?

A: If you have thousands of rows to show, then it would be best to set up your server to send smaller chunks of the table using ajax and use the pager to access the server. With that many records, I'm sure some browsers are choking while sorting the information.
If that was just an exaggeration, then alternatively you can try hiding the tbody until after the pager has initialized. Once revealing the tbody, make sure to trigger an applyWidgets on the table so that any zebra striping can be applied.
$(function(){

  $("table")

    // initialize the sorter
    .tablesorter()

    // bind to pager initialized event BEFORE calling the addon
    .bind('pagerInitialized', function(event, options){
        $(this)
            .find('tbody').show()
            .trigger('applyWidgets');
    })

    // initialize the pager plugin
    .tablesorterPager({
      container: $("#pager")
    });

});


text:
Q: Edit on Google Docs without converting I'm integrating my system with Google Drive. Everything is working so far, but one thing. I cannot edit the uploaded Word documents without converting them to Google Docs first.
I've read here it's possible using a Chrome plugin:
https://support.google.com/docs/answer/6055139?hl=en
But that's not my goal. I'm storing the file's information on my database and then I just request the proper URL for editing and previewing. Previewing is working fine, but when I try the edit URL it says the file does not exist. If I convert the file (using Google Drive's interface) and pass the new ID it works. I don't want to convert the user's documents to Google Drive because they still use Word as their main editing software.
Is there a way to accomplish this?
This is how I'm doing right now:
public static File UploadFile(FileInfo fileInfo, Stream stream, string googleAccount)
{
    var mimetype = GetValidMimetype(fileInfo.MimeType);
    var parentFolder = GetParentFolder(fileInfo);
    var file = new File { Title = fileInfo.Title, MimeType = mimetype, Parents = parentFolder };
    var uploadRequest = _service.Files.Insert(file, stream, mimetype);

    uploadRequest.Upload();
    file = uploadRequest.ResponseBody;

    ShareFileWith(file.Id, googleAccount);

    return file;
}

This is the URL for editing (where {0} is the file ID):
https://docs.google.com/document/d/{0}/edit?usp=drivesdk
I know that in order to convert the file I just need to:
uploadRequest.Convert = true;
But again, that's not what I want. Is it possible?
Thanks!
EDIT
Just an update. Convert = true should've worked but it's not. I've raised an issue for that here https://github.com/google/google-api-dotnet-client/issues/712
Bottomline, it only works if I open the file on Google Docs and then use its Id...


text:
Q: How to verify SHA of Azure certificate used for ftps? I am trying to connect to my Azure web app through FileZilla, with FTP/S settings listed on my app inside the Azure portal (picture below), how can I ensure this certificate is actually from Microsoft?

In the next picture, how to ensure this is truly from Microsoft? I'm expecting a simple lookup table somewhere.

A: This is more an issue with Filezilla as it doesn't trust certs that your local machine trusts (see feature request).  Most Azure certs are signed by Baltimore Cyber Trust.  Here is a blog post announcing our change to Baltimore Cyber Trust.


text:
Q: Performance with Entity Framework I have another question about performance with EF.
There's one method to get an object from context:
tDocumentTyp DocumentTypObject = Context.tDocumentTyps.Where(s => s.DocumentTypID == iTypID).FirstOrDefault();

This method takes ~2979 ms.
Then I wrote a method to get the DBSet via reflection and is executed this way:
tDocumentTyp DocumentTypObject = Context.GetEntries<tDocumentTyp>().Where(s => s.DocumentTypID == iTypID).FirstOrDefault();

My method needs ~222 ms to execute.
So my question now is, why is my method much faster than the original one? Or is there anything wrong with my method?
To make this a bit easier, here is my method for getting DBSet via reflection:
public static IEnumerable<T> GetEntries<T>(this AppContext DataContext,
    string PropertyName = null, IEnumerable<string> includes = null) where T : IEntity
{
    Type ContextType = typeof(AppContext);
    PropertyInfo Entity = null;
    if (null == PropertyName)
        Entity = ContextType.GetProperty(typeof(T).Name)
                    ?? ContextType.GetProperty(typeof(T).Name + "s");
    else
        Entity = ContextType.GetProperty(PropertyName);

    if (null == Entity)
        throw new Exception("Could not find the property. If the property is not equal to the tablesname, you have to parametrize it.");
    DbQuery<T> set = ((DbSet<T>)Entity.GetValue(DataContext, null));
    if (includes != null)
        includes.ForEach(f => set = set.Include(f));
    return set;
}

A: The second example is getting the entire table and applying the Where in memory. You are applying the extension method System.Linq.Enumerable.Where which operates on IEnumerable<T>. Note that this is an in-memory implementation. In the first example you using the extension method System.Linq.Queryable.Where which operates on IQueryable<T>. This is a different method, though they share the same name.
If you inspect closely you will also find that in the first example the method parameter is of type Expression<Func<T, bool>> whilst in the second example it is simply Func<T, bool>. This is a very important difference: the expression can be processed to produce a SQL-query.
So why is the second one faster? Well, that is hard to answer without more information about your data source. But as others have noted in the comments, if the database is not indexed then it may well be quicker to select the entire table and execute the filter in memory than to have the SQL server apply the filtering.


text:
Q: Unable to add the item in array on scan in Angular 2 I am developing an application using Angular 2.. In my application I am using barcode scanner to scan in the text field and storing those items in the array.
When I scan the item get added to array, but when I scan another item the old item it replace the old value in array.
Below is the piece of code which I am using. Please help me if you see any fix for the weird issue.
    import { Component,ViewChild,Input, Output,OnInit,ChangeDetectorRef   } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HeaderComponent } from '../common/header.component';
//import { SaleCart } from '../model/SaleCart';
//import * as $ from "jquery";
declare var jQuery: any
@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./posapp.component.css']

})
export class TestComponent implements OnInit{
  title = 'Treewalker POS';

  public cartItems = [];
  public query;
  public filteredList = [];
  public products = [{"id":"3","name":"Pears Soap Original 75gm","sku":"89675432189","price":"32.00","special_price":"32.00","qty":null,"barcode":"89675432189","tax":"5","discount":"0"},{"id":"1","name":"Rin","sku":"1111111111111","price":"11.00","special_price":"11.00","qty":"10.000","barcode":"1111111111111","tax":"5","discount":"0"},{"id":"2","name":"Test 1","sku":"23456","price":"10.00","special_price":"10.00","qty":"10.000","barcode":"23456","tax":"5","discount":"0"}];
  constructor() {

  }

    ngOnInit() {

  }

  add(item) {

    /* check the items in the json data */
    let flag = false;
    var foodItem = {};
    for (let product of this.products) {
       if(product.barcode == item) {
          flag = true;
          foodItem['ctr'] = 1;
          foodItem['item'] = product;
          break;
        }
    }

    let localCart = [];
    if(sessionStorage.getItem("cart")){
      localCart =  JSON.parse(sessionStorage.getItem("cart"));
      //console.log(JSON.stringify(localCart));
    }
    //console.log("food "+JSON.stringify(this.cart));
    if(flag && localCart.length) {

      let exist = 0;

      for(let i=0; i < localCart.length; i++) {

        if(localCart[i].item.barcode == item) {

          localCart[i].ctr = parseInt(localCart[i].ctr) + 1;
          //console.log("@@@@ "+this.cart[i].ctr+" --- "+item);
          exist = 1;

        }
      }
      if(!exist){
        localCart.push(foodItem);
      }
      sessionStorage.setItem("cart",JSON.stringify(localCart));

      //this.barcode = "";
    }else if(flag){

      localCart.push(foodItem);

      sessionStorage.setItem("cart",JSON.stringify(localCart));
    }
    //this.cart = JSON.parse(sessionStorage.getItem("cart"));

    //this.itemsCnt = localCart.length;
    //console.log("--- "+this.itemsCnt);
    console.log(JSON.parse(sessionStorage.getItem('cart')));
    //this.onScanProduct.emit(localCart);

}

  filter(e) {
    //e.preventDefault();
    if (this.query !== ""){

        this.filteredList = this.products.filter(function(el){
            if(el.barcode.toLowerCase() == this.query.toLowerCase()) {

                return el.barcode.toLowerCase() == this.query.toLowerCase();
            }else{
               return el.barcode.toLowerCase().indexOf(this.query.toLowerCase()) > -1;
            }

        }.bind(this));

        /* scanned item will be added to the cart */
        console.log(this.filteredList.length);
        if(this.filteredList.length > 0 && e.which == 13){

            //console.log(JSON.stringify(this.filteredList));
            for (let product of this.filteredList) {
                //console.log(filter.barcode+"=="+this.query);
                if(product.barcode == this.query) {
                    this.add(product.barcode);
                    jQuery('#barcode').val("");jQuery('#barcode').focus();
                    this.filteredList = [];
                }
            }

        }

    }else{
        this.filteredList = [];
    }
}

}

Below is the html template

       <form>

                              <input id="barcode" type="text" class="form-control validate filter-input" name="query" [(ngModel)]="query" (keyup)="filter($event)" placeholder="Enter item code or scan the barcode" autocomplete="off" [ngModelOptions]="{standalone: true}">

 0">

                                      {{item.barcode}} {{item.name}}

                              <button type="button" class="btn btn-primary" (click)="createnewproduct(newproduct)">New Product</button>

           </form>

Below is the input field which is being used to scan the barcode
<input id="barcode" type="text" class="form-control validate filter-input" [(ngModel)]="query" (keyup)="filter()" placeholder="Enter item code or scan the barcode" autocomplete="off">

A: I am assuming you are using only the function add. I tried to implement in a javascript like in the following code but I am pretty sure you are referencing that object somewhere else and you are changing it. That's my conclusion but I might be wrong.
var factoryP = (function(){

    function P() {
        this.cart = [];
        this.products = [{'barcode': 1, 'name': 'a'}, {'barcode': 1, 'name': 'b'}]

    }

    function add(item) {

          /* check the items in the json data */
          //console.log("cart length "+JSON.stringify(this.cart));
      let flag = false;
      var foodItem = {};
      for (let product of this.products) {

        if(product.barcode == item) {
                //console.log("check "+item);
          flag = true;
          foodItem['ctr'] = 1;
          foodItem['item'] = product;
          break;
        }
      }

      if(flag && this.cart.length) {

        let exist = 0;

        for(let i=0; i < this.cart.length; i++) {

          if(this.cart[i].item.barcode == item) {
                //console.log("Same product");
            this.cart[i].ctr = parseInt(this.cart[i].ctr) + 1;
            exist = 1;

          }
        }
        if(!exist){

          console.log(foodItem);
          this.cart.push(foodItem);
        }

      }else if(flag){
        console.log("step 4 "+item);
        this.cart.push(foodItem);

      }

    }

    P.prototype.add = add;
    return  new P();
  });

instanceP = factoryP();
instanceP.add(1);
instanceP.add(1);
instanceP.add(1);
instanceP.add(2);

console.log(instanceP.cart[0].ctr)
//output 3
instanceP.cart[1].ctr
//output 1

A: Check your code here. Every time you are initializing the foodItem array with empty array. So whenever code will call add method, it will first empty your foodItem array.
Please check my comment in your code below:
add(item) {

       let flag = false;

//Akshay: You need to make your changes here. Initialize your foodItem array out of this scope
       var foodItem = {};
       for (let product of this.products) {
         if(product.barcode == item) {
           //console.log("check "+item);
           flag = true;
           foodItem['ctr'] = 1;
           foodItem['item'] = product;
           break;
         }
       }


text:
Q: Customizing Selection Handles of GEF figures Whenever a figure is selected in the GEF Editor, by default, we see a black,filled rectangle resize handles and a black border outlining the figure. I am implementing a feature where i am explicitly(through code) applying handles to a figure.
Following are some issues i am facing :
1) The handles are not placed close to the figure. They are placed leaving some space between handle and figure
2) I want to change the color filled from black to red
I am new to this kind of development so any examples of customizing these handles will be really use full.
Thanking in advance.

A: The handles are created by the SelectionHandlesEditPolicy (this is an abstract class, the implementation is done in ResizableEditPolicy). This policy is added by GEF to a child figure when it is added to a parent that has a ConstrainedLayoutEditPolicy (i.e. XYLayoutEditPolicy).
What you can do is inherit from your container's edit policy (i.e. XYLayoutEditPolicy) and override the createChildEditPolicy method to return a SelectionHandlesEditPolicy that you implement that creates the handles the way you want them to look.


text:
Q: how to run all feature files multiple times with different values for one of the parameter So far we have a configuration.properties where we set value for all required parameters, but I need to loop through multiple values for one of the parameters (probably comma delimited) and run all feature files for each.

A: I do not think there is a feature in cucumber to send multiple parameters to only one of the parameters. But what we can do is in the Scenario Outline,

*

*We can send the parameters comma separated

*The parameters to an array.

*Run the steps multiple times for that array

Feature file
Scenario Outline : Create User
 Given I enter names as <names>
 And I enter class as <class>
 When I click Save
 Then the success message is displayed

     Examples:
     |names      |class|
     |Ann,Malissa|5G   |

Step definition file
@Given("I enter names as (.*)")
public void GivenIenterName(String names){
        String[] nameList = names.split("\\,");
         for(String x : nameList){
              /*block of code
              to execute*/
         }
        }


text:
Q: Angular NgRoute "/" works but the rest don't? I have an app running on the MEAN stack, and I can't seem to get any angular route other than "/" to work. I have tried this with both ng-Route and ui-router, and both keep sending anything other than "/" (like /contacts or /portfolio_item/4)  back to "/".
Here is app.js:
// using the express library in variable express
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// specify that app is a new express application
var app = express();
app.use('/javascripts', express.static(__dirname + '/public/javascripts'));
app.use('/images', express.static(__dirname + '/public/images'));
app.use('/stylesheets', express.static(__dirname + '/public/stylesheets'));
app.use('/pages', express.static(__dirname + '/public/pages'));
app.use('/partials', express.static(__dirname + '/views/partials'));
app.use('/portfolio.json', express.static(__dirname + 'portfolio.json'));

app.get('*', function (req, res) {
    res.sendFile(__dirname + '/public/index.html');
});

And here is angularapp.js:
var myApp = angular.module('myportfolio', ['ngRoute'])

myApp.config(function($routeProvider){
        $routeProvider
        .when('/', {
          templateUrl: '/pages/home.html',
          controller: 'mainController'
        })
        .when('/portfolio_item/:item_number', {
          templateUrl: '/pages/item.html',
          controller: 'portfolioController'
        })
        .when('/contacts', {
          templateUrl: '/pages/contact.html',
          controller: 'contactController'
        })
        .otherwise({ redirectTo: '/' });

Regardless of what I do, both /portfolio_item/5 and /contacts keep showing me /pages/home.html... it's odd to me that only the index would work. When I removed the ".when('/', {" portion, it would just show me the layout with no view at all from any URL.
I am working on a C9 environment and running a Node server if that makes a difference?

A: If you check your browser console, you should find an error of this form:

Uncaught SyntaxError: Unexpected token <

The error occurs because the server is not serving the static files. express.static is being used as a middleware for routes on the server.
To correct this, you need to include the line:
app.use(express.static(__dirname + '/public'));

This serves all the static files in the public folder.


text:
Q: How to do this Jenkins conditional build? We are a .net shop so use Jenkins MSBuild plugin to do the build. For each project we have a development and release build, but I notice their only differences are:

*

*/p:Configuration=Debug or /p:Configuration=Release in MSBuild

*Release build has an extra copy step at the end

So I am thinking if I can merge them together into one build, and change the above configurations in the build based on the git branch names. I can get the git branch name like this %GIT_BRANCH%= origin/development, but I can't figure out:

*

*How to construct a conditional step to use the above %GIT_BRANCH%.

*How to use the above %GIT_BRANCH% to change the /p:Configuration=?

Can anyone shed me some lights?

A: I assume that, in merging these into a single job, you're expecting to parameterize the build (e.g., defining a Choice parameter named "Type" with values of "Development" and "Release"). If so, you could check "Prepare an environment for the run", then add something like the following to the "Evaluated Groovy script" field:
if ("Release".equals(Type)) {
    def map = [Configuration: "Release"]
    return map
}

if ("Development".equals(Type)) {
    def map = [Configuration: "Debug"]
    return map
}

This will define a Configuration environment variable with the specified value, which can then be passed to MSBuild as a ${Configuration} or %Configuration% environment variable (e.g., "/p:Configuration=${Configuration}" as the Command Line Argument).
If you have an additional build step that should only execute conditionally (if the Type is "Release"), you can use the Conditional BuildStep Plugin, in which case you can use a Regular Expression Match, with the Expression "^Release$" and the Label ${ENV,var="Type"} to access the value of the "Type" environment variable and compare it to the "^Release$" regex pattern. You would then do your copy step as the step to execute if the condition is met.
Alternatively, and more simply, you can use IF logic in a Windows batch file, such as this:
IF "%Type%" EQU "Release"
(
    rem Copy your files wherever
)


text:
Q: leaflet pattern . trying to add a path pattern not working based on the documentation here leaflet.pattern
i can create my custom patterns ,here is an example
I have done the same steps  as mentioned in the example for our custom pattern . i have only changed the d element (related to svg path) .
but things did not went as i expected .
any help would be thankful .
Here is the code :
   var mapCenter = new L.LatLng(50.68, -120.34);

    var baseLayer = new L.TileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: '© OpenStreetMap contributors'
    });

    var _map = new L.Map("map", {
        center: mapCenter,
        zoom: 14,
        layers: [baseLayer]
    });

    var shape = new L.PatternPath({
        d: 'M10 0 L7 20 L25 20 Z',
        fill: true
    });

    var pattern = new L.Pattern({width:50, height:50});
    pattern.addShape(shape);
    pattern.addTo(_map);

    var circle = new L.Circle(mapCenter, 400.0, {
        fillPattern: pattern,
        fillOpacity: 1.0});
    circle.addTo(_map);

I have only changed ( d: 'M10 0 L7 20 L25 20 Z')
to ('m206.38471,149.50017a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828')
any help would be thankfull

A: You can fix it by making x and y position of your svg path same as the sample's x and y positions.
I've put two paths in same svg file and opened it with an online editor.
As you can see in this screenshot, sample path is located top-left corner, but your path is located in the middle.

After setting its position same as sample's values: 6px, -1px pattern displayed like this:

used path: m8.278722,2.394142a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828
If you scale down your path, it is displayed like this:

used path: m7.27872,1.318623a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245


text:
Q: Better ways of saying "is able to" I'm trying to complete my English coursework and cannot find a way around using 'is able to' in this context "Throughout the novel McEwan 'is able to' convey..." and I need to find another way of saying this.

A: Maybe you should try 'succeeds in conveying'.
So the sentence will look like "Throughout the novel McEwan succeeds in conveying.......".
Hope this helps.

A: Have you considered using "is capable of"? in your sentence it would be used as: "... McEwan is capable of conveying..." and should read identically after your passage.