text:
Q: Calling web services from Jasmine Test I am attempting to write some black box tests to some web services. In an attempt to do this, I'm using Jasmine. I would like to know how to call a web service from Jasmine. I currently have the following setup:
describe('Web Service', function () {
  describe('-> endpoint', function() {
    describe('-> create', function() {
      var response = null;
      beforeEach(function(done) {
        // execute a call to the web service here
        if (done) {
          done();
        }
      });

      it('should run correctly', function(done) {
        if (done) {
          done();
        }
      });
    });
  });
});

How do I call a web service from Jasmine?
Thank you!

A: You should use something like nock to mock a response and assert that your code has called the service and received the correct response and then did its job correctly, or, if you really want nock can even allow your code to perform the actual call to the web service.
Otherwise if you just want to call the webservice from within your test you most likely have an API client somewhere where you can just perform the call yourself.
describe('My Test', function (done) {
    beforeEach(function () {
        var myApiClient = new MyApiClient();
        //unless you're using promises
        this.response = myApiClient.synchronousGet('http://someURL.com');
    });
});

Jasmine itself isn't, and shouldn't be, responsible for calling your web services, that should come from within your unit under test.

A: You shouldn't send ajax requests from your tests because you'll be dependant of the services to run your tests... And a bad response from your webservices doesn't absolutely mean that your code is not running correctly.
A good way to do it is to mock the ajax request (as limelights said), but Jasmine has an ajax module ready to help you with this. See http://jasmine.github.io/edge/ajax.html
This Jasmine plugin will allow you to catch the calls to a service and replace it with your fresh configured response that will be always the same (because you should know the exact response to test correctly your service.
Anyway, if you absolutely want to call your service, I think you'll have to code it in JS in your tests (not recommanded to write such code in your tests. Better write function that will be tested too). As I know, Jasmine doesn't provide you this kind of helper, it's just for tests purposes.


text:
Q: Map every second element of a list I've loaded a CSV:
Colors = Import[
  "d:\\bitbucket\\diversity\\data\\nlcd\\nlcd-colors.csv", "CSV"]
{{0., " 0.00000000000 0.00000000000 0.00000000000"}, {11.,
  " 0.27843137255 0.41960784314 0.62745098039"}, {12.,
  " 0.81960784314 0.86666666667 0.97647058824"}, {21.,
  " 0.86666666667 0.78823529412 0.78823529412"}, {22.,
  " 0.84705882353 0.57647058824 0.50980392157"}}

And I would like this:
{{0., RGBColor[0.00000000000,0.00000000000,0.00000000000]}, {11.,
  RGBColor[0.27843137255,0.41960784314,0.62745098039]}, {12.,
  RGBColor[0.81960784314,0.86666666667,0.97647058824]}, {21.,
  RGBColor[0.86666666667,0.78823529412,0.78823529412]}, {22.,
  RGBColor[0.84705882353,0.57647058824,0.50980392157]}}

A: Here is your list:
lst = {{0., " 0.00000000000 0.00000000000 0.00000000000"}, {11.,
   " 0.27843137255 0.41960784314 0.62745098039"}, {12.,
   " 0.81960784314 0.86666666667 0.97647058824"}, {21.,
   " 0.86666666667 0.78823529412 0.78823529412"}, {22.,
   " 0.84705882353 0.57647058824 0.50980392157"}};

Try this:
{#[[1]], RGBColor[Map[ToExpression, StringSplit[#[[2]]]]]} & /@ lst

(*  {{0., RGBColor[{0., 0., 0.}]}, {11.,
  RGBColor[{0.27843137255, 0.41960784314, 0.62745098039}]}, {12.,
  RGBColor[{0.81960784314, 0.86666666667, 0.97647058824}]}, {21.,
  RGBColor[{0.86666666667, 0.78823529412, 0.78823529412}]}, {22.,
  RGBColor[{0.84705882353, 0.57647058824, 0.50980392157}]}}   *)

Have fun!

A: You could also try
 MapAt[
   Apply[RGBColor,First@ImportString[#, "Table"]] &, Colors, {All, 2}]

which outputs

 {
   {0., RGBColor[0., 0., 0.]},
   {11.,RGBColor[0.27843137255, 0.41960784314, 0.62745098039]},
   {12., RGBColor[0.81960784314, 0.86666666667, 0.97647058824]},
   {21., RGBColor[0.86666666667, 0.78823529412, 0.78823529412]},
   {22., RGBColor[0.84705882353, 0.57647058824, 0.50980392157]}
  }

or, equivalently

Effectively, MapAt
applies an appropriate data extracting function on the second item for every entry in the list Colors.
The function that it uses to extract the data (in this case, the RGB values in the strings) is Apply[RGBColor,First@ImportString[#, "Table"]] &.
Every string sequence of RGB values is first parsed, using ImportString; this produces a list of values (not a string, anymore).
Each list of values is then, in turn, transformed to an RGBColor by replacing their head of List with the appropriate RGBColor head (this is what the Apply[RGBColor,<>] portion of the code does).

A: This way is quite simple:
{#1, RGBColor[ToExpression /@ StringSplit[#2]]} & @@@ Colors

It is almost the same as k_v's comment except I use #1 and #2 instead of #[[1]] and #[[2]], and I use @@@ instead of @@.
a @@@ b is shorthand for Apply[a, b, {1}], e.g. f @@@ {{a, b}, {c, d}} gives {f[a, b], f[c, d]}.

A: Edit
Ok, so an incorrect answer producing arrays like:
{{"0.", RGBColor["0.00000000000", "0.00000000000", "0.00000000000"]}}

received +12 and an accept. Let's correct it though:
Activate @ ReadList[
  file
, {Number, RGBColor[Inactive[ToExpression][Word], Number, Number]}
, WordSeparators -> {"\t", " ", ","}
]

{{0., RGBColor[0., 0., 0.]}, ...}

Original answer
Let's try to get those numbers directly from the file:
ReadList[
  file
, {Word, RGBColor[Word, Word, Word]}
, WordSeparators -> {"\t", " ", ","}
]

To learn what is going on please read:
Can Read[] apply a custom function automatically to the read values?

A: If we define:
rgb[s_] := RGBColor @@ StringReplace[s, Whitespace~~n:NumberString :> ToExpression[n]]

then we can write any of the following expressions:
MapAt[rgb, Colors, {All, 2}]

Colors // Query[All, {2 -> rgb}]

ReplacePart[Colors, {i_, 2} :> rgb[Colors[[i, 2]]]]

to obtain:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding the focused child element within a parent element in Android In Android, how do I find the focused child element within a parent element?

A: A focused UI component is the one that is receiving user events. It is usually highlighted in some way e.g. a coloured border. If your reading this answer on a browser window, your browser window has some indication (e.g. colours/shadows) to indicate that this browser window is the UI component that is accepting events.

*

*When a button is clicked, it is focused.

*But if a button is focused, it does not mean that the button has been clicked.

A: As you can easily test by yourself, a button gains focus when you click it.
In the source code of View.onTouchEvent() you can see that the view gains focus on the first touch event, and on the second one Android calls your onClick listener :
// take focus if we don't have it already and we should in
// touch mode.
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
    focusTaken = requestFocus();
}

if (!mHasPerformedLongPress) {
    // This is a tap, so remove the longpress check
    removeLongPressCallback();

    // Only perform take click actions if we were in the pressed state
    if (!focusTaken) {
        // Perform click
    }
}


text:
Q: My App sometimes causes WindowServer high CPU on Mac 10.12 I am developing an UI application on Mac. After running about 1 hour, the application seems to become stuck. At the same time, the WindowServer process is costing very high CPU, from 50%~100%.
I googled a lot, it seems very few questions and answers related self developed application with WindowServer.
Does anyone know how to find what's causing the WindowServer cost high CPU? Any instruments in Xcode can help?

A: I fixed this issues in my MacBook(Monterey 12.6) by changing "Scaled" to "Default" in Displays Setting.
Figure: Change "Scaled" setting
How to change the resolution of your display:
https://support.apple.com/en-us/HT202471
Related Discussion:
https://discussions.apple.com/thread/8087967?page=3


text:
Q: jQuery table filter not quite sorting correctly I have been trying to use the following I found on fiddle (modified it a bit for this example). Not even sure if i'm posting this code correctly ... would be best to just look at the fiddle I guess.
{
    filters[col] = text;

    $(table).find('tr').each(function(i){
        $(this).data('passed', true);
    });

    for(index in filters)
    {
        if(filters[index] !== 'any')
        {
            $(table).find('tr td:nth-child('+index+')').each(function(i){
                if($(this).text().indexOf(filters[index]) > -1 && $(this).parent().data('passed'))
                {
                    $(this).parent().data('passed', true);
                }
                else
                {
                    $(this).parent().data('passed', false);
                }
            });
        }
    }

    $(table).find('tr').each(function(i){
        if(!$(this).data('passed'))
        {
            $(this).hide();
        }
        else
        {
            $(this).show();
        }
    });
}

Basically I will have a table with, lets say, 100 rows, and each row will have a column with a timer value in it, e.g. 10 min or 15 min. When a user clicks the appropriate "custom filter" like 10 min, the table will be filtered to only show all entries with 10min. So far it works 100%.
But, when a user might filter anything with one digit, like 5 min or 1 min it throws out, well everything for example user filters by 5 min, now it throws out 5 min, 15 min, 45 min etc.
In the example the 10, 15, 45 and 59 min filters does their job correctly. The 5 and 9 min buttons filters wrong, you will see what i mean in the example.
Are there any way to remedy that situation, so that when 5 min filter is clicked it only loads table columns with the value 5 min? I have seen something similar in another fiddle (which i can't find right now) think it was called a regular expression and not a indexOf ... this was for a search function within a table but it worked.
Please let me know if you need more information or a better description.

A: Here's a much simpler approach that uses filter() and eq() and only loops the rows once
function apply_filter(table, col, text) {
  var $rows = $(table).find('tr');
  if (text === 'any') {
    $rows.show();
  } else {
    // hide all rows then filter the ones to show
    $rows.hide().filter(function() {
      return $(this).children().eq(col - 1).text().trim() === text;
    }).show();
  }
}

DEMO


text:
Q: Filtering arrays in a document or sub document in MongoDB Java My Java Code:
MongoCollection<Document> coll = mongoClient.getDatabase(dbs.get(0)).getCollection(dbc.get(2));
    Bson Myfilter=Filters.and(Filters.eq("id", "144-12"), Filters.gte("lastTimestamp",StartPeriod ),
                Filters.lte("lastTimestamp", FinishTime));
    FindIterable<Document>  doc=coll.find(Myfilter).limit(5);
    for (Document Document : doc) {
        System.out.println(Document);
    }

for more help the corresponding Mongo Compass screenshot to  show the data structure:

and another screenshot from Mongo Compass and i have copied the JSON Document inside the red rectangle:

{"_id":"5db06ab680bd68ca32a84c6e","disconnected":false,"id":"144-12","lastTimestamp":"1571842738588","manufacturer":"gmb","modelName":"GMB_Mod1","signals":[{"event":"changed","signal":"InjectionUnitCycleParametersType.DosingTime","stability":"unstable","timestamp":"1571842736566","type":"INTEGER","value":"0","writable":"read","written":false},{"event":"changed","signal":"InterfaceType.Jobs.ActiveJobValues.LastCycleTime","stability":"unstable","timestamp":"1571842736584","type":"INTEGER","value":"0","writable":"read","written":false}],"tC":10}

I want to try to combine the filters with array fields and scalar fields. for instance int the photo I would like to combine filters based on "manufacturer" field and "written" field of the array

A: Your requirement is to check for a field signals is an array and is not empty. Then, print a field (value) value from the array sub-document element, for all array elements.
The following is an example of how it can be achieved. I am using sample documents and print the fldA values. The following Java code has the array checks:
{ _id: 1, arr: [ { fldA: 11, fldB: "str123"}, { fldA: 29, fldB: "strxyz"} ] },
{ _id: 2, arr: [ ] }

The Java Code:
MongoClient mongoClient = MongoClients.create("mongodb://localhost/");
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document>collection = database.getCollection("arrays");

Bson filterType = type("arr", "array");
Bson filterXpr = expr(Document.parse("{ $gt: [ { $size: '$arr' }, 0 ] }"));
List<Document> list = new ArrayList<>();

collection.find(and(filterType, filterXpr))
               .limit(2)
               .iterator()
               .forEachRemaining(list::add);

for ( Document doc: list) {
    List<Document> arr = (List<Document>) doc.get("arr");
    arr.forEach(e -> System.out.println(e.get("fldA")));
}

The output:
11
29

NOTES:
You can combine the filters I had defined (to check if the field is an array and the array has elements) with the filters MyFilter from your code using Filters.and.
// MongoDB Java driver imports
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.client.*;
import static com.mongodb.client.model.Filters.*;


text:
Q: Who is growing faster? I am trying to prove that $\lim_{n\to \infty} { 2^{n^2} \over n!} = \infty$. I can't use l'Hôpital's rule (or I dnon't know how) and I don't recall any other method which could help me. It also isn't obvious to me that exponential is growing faster than factorial. How do I prove that?

A: Hint: $2^{x^2}=\exp(\log (2^{x^2}))=\exp(x^2 \log 2)$, then use Stirling to approximate $x!$.


text:
Q: Как перебрать все комбинации формулы? Необходмио перечислить все возможные формулы произвольного размера, используются цифры 0, 1, 2, переменная x иоперации -, +, *, а также скобки.
Размер выражения - число использованных операций.
Например, формулы размера 1: 0+1, x*2, размера 4: x*x+2*x+1, (1+x)*1*2+0
Удалось сделать только "статически" и без скобок. Как это возможно реализовать в "движении" ??
https://repl.it/repls/AntiqueHoneydewCharactermapping  //код и тамже можно выполнить его
using System;
using System.Linq;

class MainClass {
  public static bool onlyOneVariable(params char[] values) => values.Count(char.IsLetter) == 1;

  public static void Main (string[] args) {
    var formulas = (
      from num1 in new[] { '0', '1', '2', 'X' }
      from num2 in new[] { '0', '1', '2', 'X' }

      from op1 in new[] { '-', '+', '*' }
      where onlyOneVariable(num1, num2)
      select $"{num1} {op1} {num2} "

    );
    foreach(var formula in formulas.Take(10)) {
      Console.WriteLine(formula);
    }

  }
}

A: Рассмотрим часть задачи, где надо только сегенерировать формулы, без проверки уникальности и скобочек.
Бинарная операция, которыми являются +, - и *, всегда содержат левую сторону, правую и операнд. Например, x+1, где x -левая, 1- правая, + - операнд.
Предположим, что мы строим уравнение, и у нас уже есть левая сторона и операнд, например x+, тогда осталось добавить к нему правую сторону, которая может либо закончить выражение, например x+1, либо оставить его незаконченным, чтобы можно было операцию по добавлению правой сторны повторить x+1+.
Отсюда появляется рекурсивная функция. Я добавли только отслеживание уже использованных операций и операнодов, чтобы они в формулах не дублировались
public IEnumerable<string> GetFormulas(string[] operands, string[] operators,
            bool[] operandsUsed, bool[] operatorsUsed,
            int operCount, List<string> states)
{
    if (operCount == 0)
    {
        for (int i=0; i<operands.Length; i++)
        {
            if (operandsUsed[i]) continue;
            var oper = operands[i];
            var sb = new StringBuilder();
            foreach (var state in states) sb.Append(state);
            sb.Append(oper);
            yield return sb.ToString();
        }
    }
    else
    {
        for (int j=0; j<operators.Length; j++)
        {
            if (operatorsUsed[j]) continue;
            var op = operators[j];

            for (int i=0; i<operands.Length; i++)
            {
                if (operandsUsed[i]) continue;
                var oper = operands[i];

                operandsUsed[i] = true;
                operatorsUsed[j] = true;

                states.Add(oper);
                states.Add(op);
                foreach(var f in GetFormulas(operands, operators,operandsUsed, operatorsUsed, operCount-1, states))
                    yield return f;

                operandsUsed[i] = false;
                operatorsUsed[j] = false;

                states.RemoveAt(states.Count-1);
                states.RemoveAt(states.Count-1);
            }
        }
    }
}

Как использовать:
var operands = new[] { "0", "1", "2", "X" };
var operators = new[] { "+", "-", "*" };
var L = 1;

foreach (var f in GetFormulas(operands,operators,
            new bool[operands.Length], new bool[operators.Length],
            L, new List<string>()))
    Console.WriteLine(f);

Где L - может принимать значение от 0 до 3, так как у нас только максимум 3 не повторяющихся оператора.
Пример вывода:
0+1
0+2
0+X
1+0
1+2
1+X
2+0
2+1
2+X
X+0
X+1
X+2
0-1
0-2
0-X
1-0
1-2
1-X
2-0
2-1
2-X
X-0
X-1
X-2
0*1
0*2
0*X
1*0
1*2
1*X
2*0
2*1
2*X
X*0
X*1
X*2


text:
Q: How do I configure pyodbc to correctly accept strings from SQL Server using freeTDS and unixODBC? I can not get a valid string from an MSSQL server into python. I believe there is an encoding mismatch somewhere. I believe it is between the ODBC layer and python because I am able to get readable results in tsql and isql.
What character encoding does pyodbc expect? What do I need to change in the chain to get this to work?
Specific Example
Here is a simplified python script as an example:
#!/usr/bin/env python
import pyodbc

dsn = 'yourdb'
user = 'import'
password = 'get0lddata'
database = 'YourDb'

def get_cursor():
    con_string = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (dsn, user, password, database)
    conn = pyodbc.connect(con_string)
    return conn.cursor()

if __name__ == '__main__':
    c = get_cursor()
    c.execute("select id, name from recipe where id = 4140567")

    row = c.fetchone()
    if row:
        print row

The output of this script is:
(Decimal('4140567'), u'\U0072006f\U006e0061\U00650067')

Alternatively, if the last line of the script is changed to:
print "{0}, '{1}'".format(row.id, row.name)

Then the result is:
Traceback (most recent call last):
  File "/home/mdenson/projects/test.py", line 20, in <module>
    print "{0}, '{1}'".format(row.id, row.name)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

A transcript using tsql to execute the same query:
root@luke:~# tsql -S cmw -U import -P get0lddata
locale is "C"
locale charset is "ANSI_X3.4-1968"
using default charset "UTF-8"
1> select id, name from recipe where id = 4140567
2> go
id      name
4140567 orange2
(1 row affected)

and also in isql:
root@luke:~# isql -v yourdb import get0lddata
SQL>  select id, name from recipe where id = 4140567
+----------------------+--------------------------+
| id                   | name                     |
+----------------------+--------------------------+
| 4140567              | orange2                  |
+----------------------+--------------------------+
SQLRowCount returns 1
1 rows fetched

So I have worked at this for the morning and looked high and low and haven't figured out what is amiss.
Details
Here are version details:

*

*Client is Ubuntu 12.04

*freetds v0.91

*unixodbc 2.2.14

*python 2.7.3

*pyodbc 2.1.7-1 (from ubuntu package) & 3.0.7-beta06 (compiled from source)

*Server is XP with SQL Server Express 2008 R2
Here are the contents of a few configuration files on the client.
/etc/freetds/freetds.conf
[global]
    tds version = 8.0
    text size = 64512
[cmw]
    host = 192.168.90.104
    port = 1433
    tds version = 8.0
    client charset = UTF-8

/etc/odbcinst.ini
[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
CPTimeout =
CPReuse =
FileUsage = 1

/etc/odbc.ini
[yourdb]
Driver = FreeTDS
Description = ODBC connection via FreeTDS
Trace = No
Servername = cmw
Database = YourDB
Charset = UTF-8

A: So after continued work I am now getting unicode characters into python. Unfortunately the solution I've stumbled upon is about as satisfying as kissing your cousin.
I solved the problem by installing the python3 and python3-dev packages and then rebuilding pyodbc with python3.
Now that I've done this my scripts now work even though I am still running them with python 2.7.
So I don't know what was fixed by doing this, but it now works and I can move on to the project I started with.

A: Any chance you're having a problem with a BOM (Byte Order Marker)? If so, maybe this snippet of code will help:
import codecs
if s.beginswith( codecs.BOM_UTF8 ):
    # The byte string s begins with the BOM: Do something.
    # For example, decode the string as UTF-8

if u[0] == unicode( codecs.BOM_UTF8, "utf8" ):
    # The unicode string begins with the BOM: Do something.
    # For example, remove the character.

# Strip the BOM from the beginning of the Unicode string, if it exists
u.lstrip( unicode( codecs.BOM_UTF8, "utf8" ) )

I found that snippet on this page.

A: If you upgrade the pyodbc to version 3 the problem will be solved.


text:
Q: Beam: CombinePerKey(max) hang in dataflow job I am try to load data from GCS through pub\sub way, and fetch user max level by userid. The following codes runs well in DirectRunner but job is hang in CombinePerKey(max) in dataflow.
Here are the codes
class ParseAndFilterFn(beam.DoFn):
    def process(self, element):
        text_line = element.strip()
        data = {}
        try:
            data = json.loads(text_line.decode('utf-8'))
            if 'user_id' in data and data['user_id'] and 'level' in data and data['level']:
                yield {
                    'user': data['user_id'],
                    'level': data['level'],
                    'ts': data['ts']
                }

def str2timestamp(t, fmt="%Y-%m-%dT%H:%M:%S.%fZ"):
    return time.mktime(datetime.strptime(t, fmt).timetuple())

class FormatFieldValueFn(beam.DoFn):
    def process(self, element):
        yield {
            "field": element[0],
            "value": element[1]
        }

...

        raw_event = (
                    p
                    | "Read Sub Message" >> beam.io.ReadFromPubSub(topic=args.topic)
                    | "Convert Message to JSON" >> beam.Map(lambda message: json.loads(message))
                    | "Extract File Name" >> beam.ParDo(ExtractFileNameFn())
                    | "Read File from GCS" >> beam.io.ReadAllFromText()
            )

        filtered_events = (
            raw_event
            | "ParseAndFilterFn" >> beam.ParDo(ParseAndFilterFn())
        )

        raw_events = (
            filtered_events
            | "AddEventTimestamps" >> beam.Map(lambda elem: beam.window.TimestampedValue(elem, str2timestamp(elem['ts'])))
        )

        window_events = (
            raw_events
            | "UseFixedWindow" >> beam.WindowInto(beam.window.FixedWindows(5 * 60))
        )

        user_max_level = (
            window_events
            | 'Group By User ID' >> beam.Map(lambda elem: (elem['user'], elem['level']))
            | 'Compute Max Level Per User' >> beam.CombinePerKey(max)
        )

        (user_max_level
         | "FormatFieldValueFn" >> beam.ParDo(FormatFieldValueFn())
        )

        p.run().wait_until_finish()

Then I put one new zip file to GCS, then pipeline of dataflow is running , but hang in Compute Max Level Per User

Is there anything I am missing?

A: The root of the problem likely has to do with watermarks and lateness on the Combine transform (you can read a summary of the concept here). The reason watermarks are possibly an issue is because you set the timestamps for your elements manually, using beam.Map, even though your watermarks have already been set when reading from the PubSub source, since it is an unbounded source which sets its own timestamps.
The ReadFromPubSub transform has a parameter labeled timestamp_attribute which is the intended way to use an attribute timestamp with PubSub. If you set this parameter to ts then ReadFromPubSub should emit elements with timestamps already set to ts, and the watermark should be set appropriately as well.
If that doesn't work, there are other things you can look at. Double checking that the timestamps are being set correctly is a good initial step (compare the timestamps of the elements produced by ReadFromPubSub to the value of ts). Another possibility is that setting a trigger on the windows might help. A processing time trigger, for example, might be able to prevent windows from waiting forever for the watermark to catch up, although it might not be appropriate based on the needs of your pipeline. As an extra note, the metrics you screenshotted above can sometimes be unreliable for python streaming, so if you need to do fine-grained debugging you may have better luck by making your transforms output logs you can read through.


text:
Q: Определить количество положительных чисел Написать программу, в которой пользователь вводит несколько чисел, программа выводит количество положительных чисел.
int x, y = 0, z, b;
Console.WriteLine("Введите колличество цифр: ");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите число 1: ");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите число 2: ");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите число 3: ");
x = Convert.ToInt32(Console.ReadLine());
{
    if (x >= 0)
        Console.WriteLine("Положительных чисел: " + x);
        Console.ReadLine();
    }

A: Протестируйте и разберите это решение.
Console.Write("Введите колличество чисел: ");
int n = int.Parse(Console.ReadLine());
int count = 0;
for (int i = 0; i < n; i++)
{
    Console.Write($"Введите число {i + 1}: ");
    int x = int.Parse(Console.ReadLine());
    if (x > 0)
        count++;
}
Console.WriteLine($"Положительных чисел: {count}");

Познакокомьтесь с отладкой, пошаговое выполнение кода сильно помогает понять, что происходит, когда программа выполняется.


text:
Q: Zend Framework Architecture Hi Need to confirm Zend Framework Hierarchy of Objects ,

*

*Zend_Application has a Property Object Bootstrap

*Bootstrap has a Property Object Zend_Controller_Front inside

*Zend_Controller_Front has nested Objects like Request , Response , Plugins and also a
dispatcher() method through dispatcher Interface

*When Zend_Front_Controller's dispatch() method is called a Controller Method is called as viewed in Request Object.

*Now, Zend_Controller_Action has a Variable called $view which stores the Name of the PHTML Script

*Now , Zend_Controller_Action has a render() which basically does include() for the given PHTML Script

*When everything is done by PHP Interpretor , the Response comes back to Browser

Did I get it right , If not please correct
Thanks

A: This is explained at

*

*Zend_Controller Basics and

*Zend Framework MVC Request Lifecycle and

*Zend Framework Dispatch Workflow
Usually I do not like pointing to external resources without giving a few words to it, but to explain what's going on is too much to type in my own words, so bear with me on this one.
If the explanation at the given links dont suffice, you could install XDebug and step through the execution flow if you want to know all the nittygritty details.

A: Here is a bit less orthodox view on how zend framework application could be architectured.


text:
Q: MS ACCESS Syntax error (missing operator) in query expression  SELECT t.Padal, u.Nool
   FROM  (SELECT m.*, @n1:=@n1 + 1 num,
                 @n2:=IF(Padal = 'பசிப் பிடி உதைத்த ஓமைச் செவ் வரை' , @
                         n1, @n2) pos
            FROM tbl_padal m, (SELECT @n1:=0, @n2:=0) n
           ORDER BY m.uqPadalid
         ) t, tbl_Nool u
  WHERE t.uqnoolId = u.uqnoolID
    and u.nool = 'நற்றிணை'
    and @n2 >= num - 2
    AND @n2 <= num + 2

I want to get above and below two records ( totally five records )

A: @mcbalaji
For an outline, lets build up the sql gradually, from easy and known steps.
Create and run each of these--
1st  SELECT m.* From tbl_padal  m    (note that it is not ordered by uqPadalid)

2nd  SELECT m.* From tbl_padal  m  ORDER By uqPadalid     (now it is ordered)

3rd  SELECT
     (SELECT Count(*) + 1 FROM tbl_padal AS A WHERE A.uqPadalid < m.uqPadalid ) as RowNum,
     m.*  From tbl_padal  m  ORDER By m.uqPadalid         (now it also has RowNum-s)

4th  So lets pick the central one that we want--
     SELECT RowNum FROM
       (   SELECT
           (SELECT Count(*) + 1 FROM tbl_padal AS A WHERE A.uqPadalid < m.uqPadalid ) as RowNum,
           m.Padal,
           m.uqPadalid  From tbl_padal  m  ORDER By m.uqPadalid
       )
     Where m.Padal = 'your constant'

Lastly--

SELECT
  nums.RowNum,
  mm.RowNum,
  mm.Padal,
  mm.uqPadalid
  u.nool

FROM  (
  (   SELECT RowNum, uqPadalid FROM
       (   SELECT
           (SELECT Count(*) + 1 FROM tbl_padal AS A WHERE A.uqPadalid < m.uqPadalid ) as RowNum,
           m.Padal,
           m.uqPadalid  From tbl_padal  m  ORDER By m.uqPadalid
       )
     Where m.Padal = 'constant1'
  ) as nums

LEFT JOIN

  (   SELECT
           (SELECT Count(*) + 1 FROM tbl_padal AS A WHERE A.uqPadalid < m.uqPadalid ) as RowNum,
           m.Padal,
           m.uqPadalid  From tbl_padal  m  ORDER By m.uqPadalid
  ) as mm
   ON                      mm.RowNum  <=   nums.RowNum +2
    AND nums.Rownum -2 <= mm.RowNum )

LEFT JOIN
   tbl_nool  u
Where mm.uqPadalid = u.uqPadalid
And  u.nool = 'constant2'

Order By  mm.RowNum


text:
Q: Update user roles in Laravel I have three user roles: Student, Teacher, Admin.
If a user is a student I want to display the option to Elevate them to either Teacher or Admin in a dropdown and the same for the other roles eg. Teacher gets Admin and Student option.
Currently this looks like this:
Index
@if ($user->role == 'admin')
    <form action="/admin/users/{{ $user->id }}" method="POST">
        @csrf

        @method('PATCH')

        <input class="hidden" name="role" value="user">

        <button>Make User</button>
    </form>
@else
    <form action="/admin/users/{{ $user->id }}" method="POST">
        @csrf

        @method('PATCH')

        <input class="hidden" name="role"value="teacher">

        <button>Make Teacher</button>
    </form>
@endif

Controller
public function update(User $user)
{
    $attributes = request()->validate([
        'role' => ['required', Rule::exists('users', 'role')]
    ]);

    $user->update($attributes);

    return back()->with('success', 'User Updated!');
}

How would I be able to do an if statement to list all the roles except for the current role assigned to the user or perhaps this is better done in the controller instead?
And is it possible to put the role in a slug and then run a foreach so I don't repeat code?
Im new top Laravel so any help would be appreciated :)
Thanks

A: *

*Provide all roles to your page.

*Add to User hasRole() method if it does not exists.

*Use FormRequest for validation.

*Don't forget to get roles with a $user to avoid n+1 queries with User::with('roles')->find($id).

@foreach($allRoles as $role)
    @if(! $user->hasRole($role))
        Your form
    @endif
@endforeach


text:
Q: python-pptx: extract image with transparent background from PPT I have a PowerPoint that contains an image with a transparent background. I want to use the python-pptx package to extract it, but it doesn't include the transparent background.
Basically I have an image variable which is a python-pptx PICTURE object.
        file = "test.png"
        image_bytes = image.image.blob
        image_stream = BytesIO(image_bytes)
        im = Image.open(image_stream)
        im.save(file, format="PNG")

But instead of an image with a transparent background I get a black background. Any help?


text:
Q: Is there a synchronous alternative of setState() in Reactjs functional components I know how to do this in class components but when i use same code in functional component i get an error. This is what i want -
this.setState({cnt:this.state.cnt+1})
alert(this.state.cnt);

now i want the alert to show count as 1 .
How we do it in class component -
this.setState({cnt:this.state.cnt+1}, () => alert(this.state.cnt));
But when i do same in functional component like this
const[count, setCount] = useState(0);
setCount(count+1, () => alert(count));

I get an error - "expected no of arguments - 1".

A: State updater with react-hooks doesn't provide a callback. You need to use useEffect to achieve the same behavior. Also since you would want the useEffect to run only on update you can disable its initial execution with the help of a useRef
setCount(prev => prev+1);
...
const initialRender = useRef(true);
useEffect(() => {
   if(!initialRender.current) {
     alert(count);
   } else {
     initialRender.current = false;
   }
}, [count]);

In some cases you may not want the useEffect to trigger whenever count is updated but only when count is updated from a special function. In such cases you can make use of useRef
const runEffect = useRef(false);
const initialRender = useRef(true);
useEffect(() => {
   if(!initialRender.current) {
     // This will only be executed when you toggle ref

     alert(count);
   } else {
     initialRender.current = false;
   }
}, [runEffect.current]);
// adding ref as a dependency is fine here since we know that a re-render will be triggered by setCount

someFunction = () => {
   setCount(prev => prev + 1);
   runEffect.current = !runEffect.current;
}

A: The pattern here is to also use a useEffect hook with a dependency array of the state value you want to alert on. The effect hook runs once per render when state updates, and the dependency array helps filter when the effect actually triggers, in this case when count updates.
const [count, setCount] = useState(0);

useEffect(() => {
  alert('count updated!);
}, [count]);


text:
Q: Sending query strings with $.ajax type OPTIONS My REST API developer told me to check if a file is available for download before going to the actual link by first doing an ajax call using OPTIONS type.
If it returns OK, then I can go ahead and redirect the browser to that page and download the file.
return $.ajax({
  type: 'OPTIONS',
  url: 'http://api/account-data',
  data: {user_id: '5'}
}).done(function(data) {
  // redirect browser to http://api/account-data?user_id=5
});

The problem I encountered is that I can't attach any query strings when I use OPTIONS. Also, I've never heard of anyone using OPTIONS before. From what I've read, the browser does this automatically when doing certain cross-origin calls. I told him this, but I was told to search for a solution to attach the query strings. Is there a way?

A:
Also, I've never heard of anyone using OPTIONS before.

People are generally pretty bad about using HTTP correctly.
That said, I would expect to use a HEAD request to determine is a resource was available or not.

From what I've read, the browser does this automatically when doing certain cross-origin calls.

The CORS spec mandates an OPTIONS request as a pre-flight request under some circumstances, but OPTIONS predated CORS and there are other reasons to use that HTTP verb.

I was told to search for a solution to attach the query strings. Is there a way?

jQuery ignores data when you make an OPTIONS request. Put the query string directly in the URL.
$.ajax({
  type: 'OPTIONS',
  url: 'http://api/account-data?user_id=5'
})


text:
Q: Como deixar o Oracle 12c enterprise com Logs em inglês Bom tarde a todos,
Baixei o oracle 12 Oracle 12c enterprise do site da Oracle com minha conta logada e  o instalador estava todo em portugues porem quando aparece aopção de selecionar o idioma estava portugues e ingles retirei o portugues e salvei, instalou normal o banco porém os erros ORA aparecem em portugues.
Alguem sabe como mudo isso ?
Ja alterei o idioma do windows para ingles como idioma principal ja esta tudo em ingles menos o BD.
Já reinstalei e continua.
Até baixei por vpn com ip no USA.
Não sei mais oque fazer.

A: Ola,
Os arquivos com as mensagens ficam dentro de uma pasta $ORACLE_HOME/..../mesg
Remova todos aqueles que não sejam us.
No arquivo $ORACLE_HOME/install/oraparam.ini altere a seguinte variável
NLS_ENABLED=FALSE
Abs

A: No arquivo $ORACLE_HOME/install/oraparam.ini altere a seguinte variável
NLS_ENABLED=FALSE
Isso eu conssegui fazer.
mas a outra parte nao tem muitas pastas com esse nome dentro da pasta do oracle.
C:\app\oracle\product\12.1.0\dbhome_1
tem 22 pastas com esse nome dentro da DBHOME_1 cada uma dentro de uma pasta diferente.
Sabe me dizer qual devo apagar ?


text:
Q: Elastic/NEST will not handle null values I am currently limited to NEST v2.4.6.
I have objects with attributes that can sometimes be null and must be persisted with those null attributes.
According to the documentation:
https://www.elastic.co/guide/en/elasticsearch/client/net-api/2.x/modifying-default-serializer.html#_modifying_settings_using_serializerfactory
This should allow me to serialize Null values.
Unfortunately, once setting this up, all my ElasticDB queries start to return nothing.
This is confusing as when I put the
[JsonProperty(NullValueHandling = NullValueHandling.Include)]

attribute, it works fine.
I obviously however would like to enable this globally.
This is what my implementation looks like:
    var pool = new SingleNodeConnectionPool(new Uri(ConfigurationManager.AppSettings["ElasticInstanceAddress"]));
    var connection = new HttpConnection();
    var settings = new ConnectionSettings(pool, connection,
        new SerializerFactory((s, values) =>
    {
        s.NullValueHandling = NullValueHandling.Include;
    }));

An example NEST query that suddenly starts to return nothing after the NullValueHandling is enabled on the serializer is as below:
var dog = _client.Get<Dog>(query.DogName).Source;

Any ideas?

A: Why should your object be persisted with null values? Persisted or not, the value should be null when deserialized back from _source because the field is either missing or actually set to null. In any case, it should work by default. Checking for null in a query can be done with an Exists Query, see : https://www.elastic.co/guide/en/elasticsearch/reference/2.4/query-dsl-exists-query.html


text:
Q: How could i start two new window with two thread in WPF I'd like to open a window in a thread. I'd like to use the Thread class as you can see in my code:
namespace WFPThreadin {

public partial class MainWindow : Window
{
    private static Window1 win1;
    private static Window2 win2;
    Thread tid1, tid2;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void gomb_Click(object sender, RoutedEventArgs e)
    {
        if (((Button)sender).Name == "button1")
        {
            tid1 = new Thread(new ThreadStart(MainWindow.winshow1));
            tid1.SetApartmentState(ApartmentState.STA);
            tid1.Start();
        }

        if (((Button)sender).Name == "button2")
        {
            tid2 = new Thread(new ThreadStart(MainWindow.winshow2));
            tid2.SetApartmentState(ApartmentState.STA);
            tid2.Start();
        }
    }

    public static void winshow1()
    {
        win1 = new Window1();
        win1.Show();
    }

    public static void winshow2()
    {
        win2 = new Window2();
        win2.Show();
    }

}}

It doesn't works well, because when i clicking the button1 (or button2) the window1 (or window2) showed for a moment...
If you have any suggestion for solve my problem i could appreciate that!

A: Try this
Running on the Same UI Thread:
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
             new Thread(() =>
            {
                Dispatcher.Invoke((Action)(() =>
                    {
                        Window2 w2 = new Window2();
                        w2.Show();
                    }));
            }).Start();

        new Thread(() =>
        {
            Dispatcher.Invoke((Action)(() =>
            {
                Window3 w3 = new Window3();
                w3.Show();
            }));
        }).Start();

 }

Running on Two Different Threads:
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {

Thread   _firstWindowThread = new Thread(new ThreadStart(CallWindow1));
        _firstWindowThread.SetApartmentState(ApartmentState.STA);
        _firstWindowThread.IsBackground = true;
        _firstWindowThread.Start();

Thread  _secondWindowThread = new Thread(new ThreadStart(CallWindow2));
        _secondWindowThread.SetApartmentState(ApartmentState.STA);
        _secondWindowThread.IsBackground = true;
        _secondWindowThread.Start();

  }

  private void CallWindow1()
    {
        Window2 w2 = new Window2();
        w2.Show();
        System.Windows.Threading.Dispatcher.Run();
    }

    private void CallWindow2()
    {
        Window3 w3 = new Window3();
        w3.Show();
        System.Windows.Threading.Dispatcher.Run();
    }

For more details take a look at WPF Threading Model

A: Just try with Task instead of using Thread
 if (((Button)sender).Name == "button1")
    {
       Task.Factory.StartNew(() =>winshow1());
    }

    if (((Button)sender).Name == "button2")
    {
       Task.Factory.StartNew(() =>winshow2());
    }


text:
Q: Getting Specific Values from string If i have a string that is
string Text="@Time:08:30PM,@Date:08/30/2015,@Duration:4,"

How would one go about extracting each of those starting with "@" and ending with the ",". I've searched and I've seen people get one pair with substring, but not how I need it. I want to say:
string Time = "08:30PM" //However i can extract it from that string
string Date = "08/30/2015" //etc...

Could it be done with Regex?
Thanks!

A: How about using Regex and converting your key-value pairs to a dictionary
string input = "@Time:08:30PM,@Date:08/30/2015,@Duration:4,";
var dict = Regex.Matches(input, @"@(\w+):(.+?),")
           .Cast<Match>()
           .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);

Console.WriteLine(dict["Time"]);

A: Try using String.Split() to make an array, then use a substring on each element of the array.
Example:
string example = "@Time:08:30PM,@Date:08/30/2015,@Duration:4,";
string[] splitText = example.Split('@');

After this, splitText will contain these elements:
{"", "Time:08:30PM,", "Date:08/30/2015,", "Duration:4," }

A: Here's a first shot at it.  Works fine for your example, of course there's edge cases you will probably need to handle as needed.
 static void Main(string[] args)
 {
     var text = "@Time:08:30PM,@Date:08/30/2015,@Duration:4,";

     var Time = GetValueForItem("Time", text);
     var Date = GetValueForItem("Date", text);
     var Duration = GetValueForItem("Duration", text);
 }

 static string GetValueForItem(string item, string text)
 {
     item = $"@{item}:"; //if pre C#6 use string.Format("@{0}:", item)
     var index = text.IndexOf(item);

     var chars = text.Substring(index + item.Length).TakeWhile(c => c != ',');
     return string.Concat(chars);
 }

get the index of the text you want, use that to grab all the characters until you reach your delimeter.  Gives you a little more mobility over Regex IMHO.


text:
Q: Twitter Not working In my Project I am implemented twitter integration into my android project the problem is the code working some times some times it's showing the error. I am not understanding what wrong with my code.Below is my code and log-cat errors.
consumer = new DefaultOAuthConsumer(TWITTER_OAUTH_KEY,TWITTER_OAUTH_SECRET);
    provider = new DefaultOAuthProvider(
            "http://twitter.com/oauth/request_token",
            "http://twitter.com/oauth/access_token",
            "http://twitter.com/oauth/authorize");

    mTwitterBtn = (CheckBox) findViewById(R.id.twitterCheck);

    mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
    mTwitter.setListener(mTwLoginDialogListener);

    mTwitterBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (mTwitter.hasAccessToken()) {
                postToTwitter = mTwitterBtn.isChecked();

                Intent shareIntent = new Intent(
                        ShareApplicationTweeter.this, PostApplication.class);
                startActivity(shareIntent);

                // share("Hi", "Test");

            } else {
                mTwitterBtn.setChecked(false);
                mTwitter.authorize();
            }

        }
    });

    if (mTwitter.hasAccessToken()) {
        username = mTwitter.getUsername();
        username = (username.equals("")) ? "No Name" : username;
        mTwitterBtn.setText("  Twitter  (" + username + ")");
    }

04-19 01:24:04.001: E/AndroidRuntime(545): FATAL EXCEPTION: main
04-19 01:24:04.001: E/AndroidRuntime(545): java.lang.NoClassDefFoundError: oauth.signpost.basic.DefaultOAuthConsumer
04-19 01:24:04.001: E/AndroidRuntime(545):  at com.a1.buzzmob.ShareApplicationTweeter.onCreate(ShareApplicationTweeter.java:86)
04-19 01:24:04.001: E/AndroidRuntime(545):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-19 01:24:04.001: E/AndroidRuntime(545):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-19 01:24:04.001: E/AndroidRuntime(545):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-19 01:24:04.001: E/AndroidRuntime(545):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-19 01:24:04.001: E/AndroidRuntime(545):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-19 01:24:04.001: E/AndroidRuntime(545):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-19 01:24:04.001: E/AndroidRuntime(545):  at android.os.Looper.loop(Looper.java:123)
04-19 01:24:04.001: E/AndroidRuntime(545):  at android.app.ActivityThread.main(ActivityThread.java:4627)
04-19 01:24:04.001: E/AndroidRuntime(545):  at java.lang.reflect.Method.invokeNative(Native Method)
04-19 01:24:04.001: E/AndroidRuntime(545):  at java.lang.reflect.Method.invoke(Method.java:521)
04-19 01:24:04.001: E/AndroidRuntime(545):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-19 01:24:04.001: E/AndroidRuntime(545):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-19 01:24:04.001: E/AndroidRuntime(545):  at dalvik.system.NativeStart.main(Native Method)
04-19 01:29:04.033: I/Process(545): Sending signal. PID: 545 SIG: 9
Thanks,
Murali.

A: Move your libraries to "libs" folder


text:
Q: java dx utility: UNEXPECTED TOP-LEVEL ERROR java.lang.ExceptionInInitializerError I'm trying to convert a normal Java application library for use on Android. The library dates from Java 1.1 and has been maintained, improved, etc, all this time, and is in service on other platforms so it's unlikely that the source code is involved.
Normally, due to the details of deployment, this library is not encapsulated in a jar, but is merely kept in a tree where CLASSPATH does its magic. However, for purposes of putting it on Android, a jar was created. That went fine - no warnings or errors.
As there will be some new development - and therefore debugging - the step of processing through ProGuard was skipped - the time will come for that later.
The error comes in the next step, running dx to convert it for use with Android. The processing proceeds without error until the fatal one described here. (There's one minor warning.)
The error splash:
UNEXPECTED TOP-LEVEL ERROR:
java.lang.ExceptionInInitializerError
        at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)
        at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
        at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:244)
        at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:136)
        at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:113)
        at com.android.dx.command.dexer.Main.processOne(Main.java:247)
        at com.android.dx.command.dexer.Main.processAllFiles(Main.java:183)
        at com.android.dx.command.dexer.Main.run(Main.java:139)
        at com.android.dx.command.dexer.Main.main(Main.java:120)
        at com.android.dx.command.Main.main(Main.java:89)
        at com.spartacusrex.spartacuside.external.dx.main(dx.java:14)
        at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.UnsatisfiedLinkError: native_get
        at android.os.SystemProperties.native_get(Native Method)
        at android.os.SystemProperties.get(SystemProperties.java:47)
        at com.htc.profileflag.ProfileConfig.<clinit>(ProfileConfig.java:168)
        ... 12 more

The development environment is Terminal-IDE. (Google code site here.)
I'm running Terminal-IDE v 2.02 - the very latest. My Android versions are:
Android 4.0.3
Software version 2.14.531.3 71ORD
(the rest aren't likely pertinent, but more on request)

EDIT - New Information
With the idea that there was something missing from the Terminal-IDE environment, I set about trying to run dx on a Windows 7 box running Eclipse. Eclipse is running DX somehow as its converting over the code from a plain .jar into something that actually runs as a part of an Android application. However, I was not able to get dx to run from the command line - it complains it can't find the source input file! (any clues?)
Meanwhile, at someones' suggestion, I set about doing the whole build in the Terminal-IDE environment. That meant a little hacking to simplify the scenario, and also it kept failing on not finding java.RMI, so I commented those sections out - I presume there's an Android-Ready RMI library I can just point to? ...Continuing on, everything worked without error until I got to DX again and had a VERY SIMILAR error as reported above:
UNEXPECTED TOP-LEVEL ERROR:
java.lang.ExceptionInInitializerError
        at com.android.dx.util.FileUtils.readFile(FileUtils.java:72)
        at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:139)
        at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:196)
        at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:127)
        at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:196)
        at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:127)
        at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:113)
        at com.android.dx.command.dexer.Main.processOne(Main.java:247)
        at com.android.dx.command.dexer.Main.processAllFiles(Main.java:183)
        at com.android.dx.command.dexer.Main.run(Main.java:139)
        at com.android.dx.command.dexer.Main.main(Main.java:120)
        at com.android.dx.command.Main.main(Main.java:89)
        at com.spartacusrex.spartacuside.external.dx.main(dx.java:14)
        at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.UnsatisfiedLinkError: native_get
        at android.os.SystemProperties.native_get(Native Method)
        at android.os.SystemProperties.get(SystemProperties.java:47)
        at com.htc.profileflag.ProfileConfig.<clinit>(ProfileConfig.java:168)
        ... 14 more

A: That bug means a JNI call was made and it couldn't find the native function it was trying to tie to.  Looks like android.os.SystemProperties.get was trying to call a native library function called native_get to actually do some work.  Do you have the library properly included in the project?

A: I'm super-skeptical of the com.htc.profileflag.ProfileConfig.<clinit> entry in your stack trace. I suspect that maybe the environment on your device is slightly different than what terminal-ide expects, and it hasn't included the correct jni libraries for whatever that HTC specific thing is.
To check if this really is a device-specific issue, you might try setting up terminal-ide in an emulator and see if you get the same error when building your library.


text:
Q: type casting in K&R K&R provide this getchar() example:
int getchar(void)
{
    char c;

    return (read(0, &c, 1) == 1) ? (unsigned char) c : EOF;
}

c is cast to unsigned char here to avoid sign extension issues, but in the fputs() example...
int fputs(char *s, FILE *iop)
{
    int c;

    while (c = *s++)
        putc(c, iop);
    return ferror(iop) ? EOF : 0;
}

*s is assigned to an int without first casting to an unsigned char.  Why is the cast unnecessary this time?

A: It is not about "sign extension issues". This implementation of getchar makes sure that all successfully read characters are returned as non-negative int values. This behavior is required by the specification of getchar, which literally says that the character read is returned as unsigned char values converted to int, even if char is signed on the given platform. What you see there is basically a direct implementation of getchar spec.
Meanwhile fputs does not return any specific character values. fputs does not return c to the user. That c is a purely internal variable. It should preserve the original value of char type on the given platform, since the value of c is then passed to putc. putc does not expect character values converted to non-negative range, it expects original character values, which could easily be negative if char is signed.
BTW, why did you look at fputs, and not fputc? If you look at fputc, which just like getchar returns a character value, you will probably see that it is implemented similarly to getchar in that regard.

A: I completely misunderstood the question the first time around. The problem here is that getchar() needs to return either a char in the entire range 0-255 or EOF. On most platforms EOF = -1. In order to return both a negative value and a char, int must be used.
This is not the case in fputs. In this example, a char is being assigned to an int in the while loop. "Lower" types are promoted to "higher" types. From page 44 KR, The C Programming Language:

If either operand is a long double, convert the other to a long double.
  Otherwise, if either operand is a double, convert the other to a double.
  Otherwise, if either operand is a float, convert the other to a float.
Otherwise, convert char and short to int
  Then, if either operand is a long, convert the other to long.

A: According to the man page,

The fputc() function writes the character c (converted to an unsigned char) to the output stream pointed to by stream.

The cast is specifically performed for you inside the function.
Aside from that, assigning from char to negative int and back to char is guaranteed to produce the correct result, and char to negative int to unsigned char is guaranteed to have the same result as a direct cast from char to unsigned char. Other cases may produce signed integer overflow, which produces undefined behavior (i.e., could crash). But most platforms handle that by quiet binary truncation, in such a way that many programmers never worry about it at all.


text:
Q: Android SharedPreferences don't seem to work I have a small game that I'm working on, and I'm just working on updating the score, but I can't get it to work properly.
Note: I cut pieces of my program to show here, I've got a whole bunch of other things that are being set, but they don't touch the "score" at all, that's why the code is a little shorthand.
My Code:
public class Start_Test extends Activity {

TextView total_points;
long new_total;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_three);
    total_points = (TextView) findViewById(R.id.points);
        SharedPreferences pref = getSharedPreferences("Prefs",
                Context.MODE_PRIVATE);
        new_total = pref.getLong("total_points", 0);
        setTouchListener();
    updateTotal(0);

}

public void updateTotal(long change_in_points) {
        SharedPreferences pref = getSharedPreferences("Prefs",
                Context.MODE_PRIVATE);
        new_total = new_total + change_in_points;
        pref.edit().putLong("total_points", new_total);
        pref.edit().commit();
        total_points.setText("" + new_total);

    }

public void setTouchListeners() {

        button.setOnTouchListener(new OnTouchListener() {
            SharedPreferences pref = getSharedPreferences("Prefs",
                    Context.MODE_PRIVATE);

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                updateTotal(25);
                return false;
            }

        });
}

A: I think its because you are creating a new shared preference Edit instance. ( as you call .edit() twice and commit an uneditted version)
Change your code...
    SharedPreferences pref = getSharedPreferences("Prefs",
            Context.MODE_PRIVATE);
    new_total = new_total + change_in_points;
    pref.edit().putLong("total_points", new_total);
    pref.edit().commit();

To the following:
    SharedPreferences.Editor pref = getSharedPreferences("Prefs",
            Context.MODE_PRIVATE).edit();
    new_total = new_total + change_in_points;
    pref.putLong("total_points", new_total);
    pref.commit();

A: Each call to .edit() creates a new Editor.
Change
pref.edit().putLong("total_points", new_total);
pref.edit().commit();

to
Editor editor = prefs.edit();
editor.putLong("total_points", new_total);
editor.commit();


text: Q: Move Multiple Workbooks in Excel to Database I have two workbooks with the same formatted columns: Name, Phone Number, and Place. My current thought process is I would merge both workbooks together and remove any duplicates, then move that master workbook to a database table in SSMS. However, I need a better way than manually checking for duplicates. Any direction? Thanks.


text:
Q: java.io.FileNotFoundException No such file or directory error but directory exists I'm getting the filenotfoundexception on my apps directory but my directory clearly exists.  I'm doing this on my local machine.  I'm doing a very simple post to a servlet.  Does anyone knw what could be happening?

A: it turns out this was due to my firewall (firestarter) blocking my servers ip address.  I allowed the exception and everything worked.

A: A few of thoughts (hopefully you haven't tried them :-):
Do you have read access to the directory?
Try putting in something like:
System.out.println("the directory = " + directory);

Assuming "directory" is the File variables that holds the directory.
Try putting in something like:
System.out.println("the directory exists = " + directory.exists());

and making sure it returns true.

A: Do you have traversal authority to all intervening path segments, and appropriate authority to the final file?


text:
Q: buffered - UE: INDEX_SIZE_ERR: DOM Exception 1 Function causes an error in the browser chrome, how to treat?
http://jsfiddle.net/6QaWc/
Uncaught Error: INDEX_SIZE_ERR: DOM Exception 1
pu
(anonymous function)
jQuery.event.dispatch
elemData.handle

I would be very grateful for any help!

A: It appears that you're trying to activate the objects before they are ready to be used.
If I wrap part of your code in the 'loadeddata' event:
$(mme).bind('loadeddata', function() {
    console.log("Data is loaded...");
    gp();
    setTimeout(function () {
        gt();
    }, 2500);
});

the error goes away. Now, I'm not sure if this works the way you want it to, because I noticed some strange behavior in how the progress meter works after that, but maybe that will give you a nudge in the right direction to pursue a working solution?
http://jsfiddle.net/6QaWc/16/


text:
Q: Compiler doesn' see created bean from few days I am trying to solve problem that occurs in my program, I tried many ways of solving, but nothing has worked. Here's the stack trace:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.caveofprogramming.spring.web.dao.UsersDao.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5077)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5591)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardContext.reload(StandardContext.java:4097)
    at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:425)
    at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1344)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1545)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1555)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1555)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1523)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.caveofprogramming.spring.web.dao.UsersDao.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
    ... 24 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
    ... 26 more

Here's my UsersDao class:
package com.caveofprogramming.spring.web.dao;

import java.util.List;

import javax.sql.DataSource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Component("usersDao")
public class UsersDao {

    private NamedParameterJdbcTemplate jdbc;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    public void setDataSource(DataSource jdbc) {
        this.jdbc = new NamedParameterJdbcTemplate(jdbc);
    }

    public Session session() {
        return sessionFactory.getCurrentSession();
    }

    @Transactional
    public boolean create(User user) {

        MapSqlParameterSource params = new MapSqlParameterSource();

        params.addValue("username", user.getUsername());
        params.addValue("password", passwordEncoder.encode(user.getPassword()));
        params.addValue("email", user.getEmail());
        params.addValue("name", user.getName());
        params.addValue("enabled", user.isEnabled());
        params.addValue("authority", user.getAuthority());

        return jdbc.update(
                "insert into users (username, name, password, email, enabled, authority) values (:username, :name, :password, :email, :enabled, :authority)",
                params) == 1;
    }

    public boolean exists(String username) {
        return jdbc.queryForObject("select count(*) from users where username=:username",
                new MapSqlParameterSource("username", username), Integer.class) > 0;
    }

    @SuppressWarnings("unchecked")
    public List<User> getAllUsers() {
        return session().createQuery("from User").list();
        // return jdbc.query("select * from users",
        // BeanPropertyRowMapper.newInstance(User.class));
    }

}

Here's my dao-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="com.caveofprogramming.spring.web.dao">
    </context:component-scan>

    <beans profile="production">

        <jee:jndi-lookup jndi-name="jdbc/spring" id="dataSource"
            expected-type="javax.sql.DataSource">
        </jee:jndi-lookup>

        <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <tx:annotation-driven />

    </beans>

</beans>

And here's my datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:component-scan base-package="com.caveofprogramming.spring.test">
    </context:component-scan>

    <beans profile="dev">
        <context:property-placeholder
            location="com/caveofprogramming/spring/web/test/config/jdbc.properties" />

        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">

            <property name="driverClassName" value="${jdbc.driver}"></property>
            <property name="url" value="${jdbc.url}"></property>
            <property name="password" value="${jdbc.password}"></property>
            <property name="username" value="${jdbc.username}"></property>
        </bean>

        <bean id="sessionFactory"
            class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                </props>
            </property>
            <property name="packagesToScan">
                <list>
                    <value>com.caveofprogramming.spring.web.dao</value>
                </list>
            </property>
        </bean>

        <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <tx:annotation-driven />

    </beans>

</beans>

Here's program structure:

Any ideas what is incorrect in code? I will be very grateful for any ideas, cause I've already lost many hours trying to solve that.

A: The "sessionFactory" bean you have is a factory for creating SessionFactory instances. A Factory Factory, if you will. It doesn't implement the Hibernate SessionFactory interface directly.
Try adding another bean to your configuration that is SessionFactory obtained from this factory:
<bean id="hibernateSessionFactory"
    factory-bean="sessionFactory"
    factory-method="newSessionFactory"/>


text:
Q: Ubuntu Server 16 from ISO in UEFI preseed file Installing Ubuntu Server 16 from ISO in UEFI mode on a Hyperv Gen2 virtual machine with preseed file.  This worked without issues on Ubuntu Server 14.
I am looking for the preseed command to bypass this screen. I answer yes.

Partition disks
This machine's firmware has started the installer in UEFI mode but it looks like there may be existing operating
System  already installed using  BIOS compatiblity mode.  If you continue to install Debian in UEFI mode, it might be difficult to reboot the machine into any BIOS-mode operating system later.
If you wish to install UEFI mode and don't care about keeping the ability to boot one of the existing systems, you have the option to force that here.  If  you wish to keep the option to boot an existing operating system you should choose NOT to force UEFI installtion here.
Force UEFI installation?
Both Seed File have the same issue.
Seed File #1  used for
d-i partman-auto/method string lvm
d-i partman-auto-lvm/guided_size string max
d-i partman-auto/choose_recipe select atomic
d-i partman-partitioning/confirm_write_new_label boolean true
d-i partman/confirm_write_new_label     boolean true
d-i partman/choose_partition            select  finish
d-i partman/confirm_nooverwrite         boolean true
d-i partman/confirm                     boolean true
d-i partman-auto/purge_lvm_from_device  boolean true
d-i partman-lvm/device_remove_lvm       boolean true
d-i partman-lvm/confirm                 boolean true
d-i partman-lvm/confirm_nooverwrite     boolean true
d-i partman-auto/init_automatically_partition       select      Guided - use         entire disk and set up LVM
d-i partman/choose_partition                select      Finish partitioning and write changes to disk
d-i partman-auto-lvm/no_boot            boolean true
d-i partman-md/device_remove_md         boolean true
d-i partman-md/confirm                  boolean true
d-i partman-md/confirm_nooverwrite      boolean true

Seed File #2
# disk partitioning
d-i partman/confirm_write_new_label                         boolean     true
d-i partman/choose_partition                                select         finish
d-i partman/confirm_nooverwrite                             boolean     true
d-i partman/confirm                                         boolean     true
d-i partman-auto/purge_lvm_from_device                      boolean     true
d-i partman-lvm/device_remove_lvm                           boolean     true
d-i partman-lvm/confirm                                     boolean     true
d-i partman-lvm/confirm_nooverwrite                         boolean     true
d-i partman-auto-lvm/no_boot                                boolean     true
d-i partman-md/device_remove_md                             boolean     true
d-i partman-md/confirm                                      boolean     true
d-i partman-md/confirm_nooverwrite                          boolean     true
d-i partman-auto/method                                     string      lvm
d-i partman-auto-lvm/guided_size                            string      max
d-i partman-partitioning/confirm_write_new_label            boolean     true

A: Try adding the following into your preseed:

d-i partman-efi/non_efi_system boolean true

I ran into same issue with Ubuntu Desktop 16.04.1 on a blank disk, so I turned on the debug options, and saw in the /var/log/installer/debug file that the "Force UEFI Install" text corresponded to that component.  Adding that to my preseed automated that step for me.


text:
Q: Render page doesn't exist Like Twitter in rails 3 How do I render a 404 or page doesn't exist like Twitter does?
I use rails 3.2.3
My code
def rescue_with_handler(exception)
  redirect_to '/500.html'
end

def method_missing(id, *args)
 redirect_to '/404.html'
end

That works, but I want to be like twitter. For example if I access this page
https://twitter.com/abcd/skka/asafaga
and https://twitter.com/abcd/skka

A: You have to handle Routing Error with rescue_from.
This question was already answered:

*

*Dynamic error pages in Rails 3

*Best way to handle 404 in Rails3 controllers with a DataMapper get

*rescue_from NoMethodError

*...

Also there is solution here:

*

*https://github.com/rails/rails/issues/671
In any case, try to Google it, you will find a lot of different solutions.


text:
Q: CCMenuItem that added as a child to another CCMenuItem doesn't respond to touch I'm implementing a decorator pattern for adding the selected/unselected events to CCMenuItem inheritors:
  public class MenuItemDecorator : CCMenuItem
  {
    public event EventHandler OnSelected;
    public event EventHandler OnUnselected;
    private readonly CCMenuItem _menuItem;

    public MenuItemDecorator(CCMenuItem menuItem) //set a decorated item
    {
      menuItem.ThrowIfNull("menuItem");

      _menuItem = menuItem;
      AddChild(_menuItem);
    }

    public override void Selected()
    {
      base.Selected();
      _menuItem.Selected();

      if(OnSelected != null)
        OnSelected(this, null);
    }

    public override void Unselected()
    {
      base.Unselected();
      _menuItem.Unselected();

      if(OnUnselected != null)
        OnUnselected(this, null);
    }
  }

Then I "decorate" my items:
...
var soundToggle = MenuItemToggleBuilder.New(soundOffBtn, soundOnBtn)
                                       .SetPosition(positionX, positionY)
                                       .SetTarget(ToggleSelector)
                                       .Build();

var decorToggle = new MenuItemDecorator(soundToggle);
decorToggle.SetTarget(Selector); // for debugging
decorToggle.OnSelected += (s, e) => toggleWafer.Scale = 0.95f;
decorToggle.OnUnselected += (s, e) => toggleWafer.Scale = 1f;

LayerMenu.AddChild(soundToggle, int.MaxValue); //LayerMenu is CCMenu
...

private void Selector(object o)
{//breakpoint is here
}
...

But when I start the application and click on my decorToggle it doesn't respond.
Moreover it doesn't step into my Selector method (where I've set the breakpoint).
So what I'm doing wrong? Could it be made easier? Thanks in advance

Thank you, @LearnCocos2D. But why debugger doesn't stop on breakpoint in Selector method?
Also what with the second part of question? Could I add custom behavior to Selected/Unselected events on CCMenuItem inheritors without inheritance from a concrete CCMenuItem inheritor(sorry for the pun) and overriding the Selected/Unselected methods?
i.e. CCMenuItemImageWithExtendedSelect, CCMenuItemLabelWithExtendedSelect, CCMenuItemToggleWithExtendedSelect etc. and each of these classes just overriding Selected/Unselected methods (as in my MenuItemDecorator)

A: If CCMenu has the same behavior as in cocos2d-iphone, which is safe to assume, then CCMenuItem are not stackable. You can't have a CCMenuItem as child of another menu item and both reacting to touches properly.


text:
Q: Jekyll liquid split by '---' I'm looking for code to split content of md file when generating jekyll site by string '---'.
When I do {% assign blocks = content | split:'<!--break-->' %} all is ok.
But {% assign blocks = content | split:'---' %} not working, how to be?

A: The three dashes are needed to split your frontmatter from the content. You'll need to use another string as a separator.


text:
Q: how to handle floating point values going beyond the range in Python? I am writing a unigram naive bayes classifier in Python. I am calculating probabilities and multiplying those. Such cumulative multiplication is reducing the value to 0 after reaching some number. I am trying to get rid of extremely low values by removing stop words or not considering the denominator of prior in Naive Bayes classifier.
I don't however, know how to make approximation or handle floating point values beyond the lower limit.Following is a snippet of code
for word in para:
            probofwordgivenclass=int(likelihood[key][word])
            if(probofwordgivenclass>10):
                mult=(float(probofwordgivenclass+1)/float(totalwordcount+vocabularsize))
                prob= prob*mult

In above code prob is cumulative probability. It reduces to 0 at the end. What approximations would you suggest? or how to handle it in Python?


text:
Q: Workflow Column renders 'undefined' with attr selector I'm using SPServices to get list items. I'm having difficulty getting the value for my workflow status column as it keeps coming back undefined.  I am using the internal name so not sure why it would come back undefined?  There are values in the column.  I know that SP stores the Workflow Status value as an integer.  Also, this is a Nintex Workflow not Designer if that makes a difference.  See code below:
$()SPServices({
operation: "GetListItems",
async: false,
CAMLViewFields: "<ViewFields><FieldRef Name='docLink' /></ViewFields>",
list name: "Program",
debug: true,
completefunc: function (xData, Status) {
   $(xData.responseXML).SPFilterNode("z:row").each(function(){
     console.log($(this).attr("ows_docLink0"));
});
}
});


text:
Q: What is armv7s? This seems to be a new option in newer XCode - instead of "armv6 armv7" under Valid architectures I now see "armv7 armv7s". What is armv7s and do I need to build for it as well as armv7?

A: The iPhone 5 will ship with and only run iOS 6.0. To coincide with the launch of iOS 6.0, Apple has seeded developers with a newer version of its development tools. Xcode 4.5 makes two major changes: it drops support for the ARMv6 ISA (used by the ARM11 core in the iPhone 2G and iPhone 3G), keeps support for ARMv7 (used by modern ARM cores) and it adds support for a new architecture target designed to support the new A6 SoC: armv7s.

A: You do not have to build for armv7s to add support for the iPhone 5. The iPhone 5 can run armv7 compiled code as well. My app has just been submitted to the store and it is build on armv7 only and working perfect!

A: armv7s is the architecture of the A6 processor in the iPhone 5. And yes, you need to include this as well. With the latest version of Xcode, support for armv6 is dropped.


text:
Q: Extract all conditions from Expression by Type Given an Expression<Func<TEntity, bool>> along the lines of
entity => entity.SubEntity.Any(
    subEntity => (
        (subEntity.SomeProperty == False)
        AndAlso
        subEntity.SubSubEntity.FooProperty.StartsWith(
            value(SomeClass+<>c__DisplayClass0).ComparisonProperty
        )
        AndAlso
        subEntity.SubSubEntity.BarProperty == "Bar"
        AndAlso
        subEntity.SubSubEntity.SubSubSubEntity.Any(
            subSubSubEntity => (x.SubSubSubSubEntity.BazProperty == "whatever")
        )
    )
)

I am trying to extract a list property conditions by type, i.e.
TEntity             : [ /* no conditions for immediate members of TEntity */ ]
TSubEntity          : [ { SomeProperty == False } ]
TSubSubEntity       : [ { FooProperty.StartsWith(/* ... */) },
                        { BarProperty == "Bar" } ],
TSubSubSubEntity    : [ /* no conditions for immediate members of TSubSubSubEntity */ ],
TSubSubSubSubEntity : [ { BazProperty == "whatever" } ]

So far, I have created an ExpressionVisitor and identified the VisitBinary method as the one I want to plug into in order to obtain my information.
I am still at a loss about

*

*how to determine whether the BinaryExpression I am looking at represents a terminal statement (in the sense that there are no more nested expressions that I need to look at)

*how to determine the Entity type that the BinaryExpression is concerned with

*whether I need to override any of the other ExpressionVisitor methods to cover for cases that I have not considered yet.

A: Not sure what really is the use case, but here is some starting point
class TestVisitor : ExpressionVisitor
{
    public Dictionary<Type, List<Tuple<MemberExpression, Expression>>> Result = new Dictionary<Type, List<Tuple<MemberExpression, Expression>>>();
    Stack<Expression> stack = new Stack<Expression>();
    public override Expression Visit(Expression node)
    {
        stack.Push(node);
        base.Visit(node);
        stack.Pop();
        return node;
    }
    protected override Expression VisitMember(MemberExpression node)
    {
        if (node.Expression.NodeType != ExpressionType.Constant && (node.Type == typeof(string) || !typeof(IEnumerable).IsAssignableFrom(node.Type)))
        {
            var expression = stack.Skip(1).FirstOrDefault();
            if (expression != null && expression.Type == typeof(bool))
            {
                List<Tuple<MemberExpression, Expression>> resultList;
                if (!Result.TryGetValue(node.Expression.Type, out resultList))
                    Result.Add(node.Expression.Type, resultList = new List<Tuple<MemberExpression, Expression>>());
                resultList.Add(Tuple.Create(node, expression));
            }
        }
        return base.VisitMember(node);
    }
}

The idea is simple. Override Visit method just to maintain a stack of processing expressions. The main processing is inside the VisitMember override, which is called for each property/field accessor. The node.Expression.NodeType != ExpressionType.Constant is used to eliminate the closure members, while the second condition eliminates collection properties. Finally, the potential condition expression is extracted from the stack.
The result is including both MemberExpression and the Expression where it is used. MemberExpression.Expression.Type is your entity type, MemberExpression.Member is the property/field of that type.
Sample test:
class Entity
{
    public ICollection<SubEntity> SubEntity { get; set; }
}

class SubEntity
{
    public bool SomeProperty { get; set; }
    public SubSubEntity SubSubEntity { get; set; }
}

class SubSubEntity
{
    public string FooProperty { get; set; }
    public string BarProperty { get; set; }
    public ICollection<SubSubSubEntity> SubSubSubEntity { get; set; }
}

class SubSubSubEntity
{
    public SubSubSubSubEntity SubSubSubSubEntity { get; set; }
}

class SubSubSubSubEntity
{
    public string BazProperty { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        string comparisonProperty = "Ivan";
        Expression<Func<Entity, bool>> e =
            entity => entity.SubEntity.Any(subEntity =>
                subEntity.SomeProperty == false
                &&
                subEntity.SubSubEntity.FooProperty.StartsWith(comparisonProperty)
                &&
                subEntity.SubSubEntity.BarProperty == "Bar"
                &&
                subEntity.SubSubEntity.SubSubSubEntity.Any(subSubSubEntity => subSubSubEntity.SubSubSubSubEntity.BazProperty == "whatever")
                );
        var v = new TestVisitor();
        v.Visit(e);
        var result = v.Result;
    }
}


text:
Q: Getting text bounds in GTK+ How can I get bounds of a text, provided string with attributes say, font size, font style, and font family in GTK+?

A: For GTK+, you should probably look at Pango. I believe the required call is pango_layout_line_get_pixel_extents(), although this will of course require you to parse whatever string it is you have with the specs, and set up the corresponding Pango object before getting the extents.


text:
Q: Jetpack Compose navigation with arguments I want to navigate from ViewModelOne to ViewModelTwo where I send data to ViewModelTwo during navigation.
This is my navigation sealed class with route and ID argument
sealed class AnimationsNavigation : NavigationAction {
    class PopUpAnimationNavigation(val id: String = "{id}") : AnimationsNavigation() {
        override val route: String
            get() = "animationNavigator/$id"
    }
}

This is my example compose holder, where I pass my backStackEntry

fun NavGraphBuilder.composableHolder(
    action: NavigationAction,
    content: @Composable (NavBackStackEntry) -> Unit
) {
    composable(
        route = action.route,
    ) { navBackStack->
        content(navBackStack)
    }
}

And this is where I used it
private fun NavGraphBuilder.commonDestinations() {
    composableHolder(AnimationsNavigation.PopUpAnimationNavigation()){
        AnimationsNavigator()
    }
}

This is the viewModel I am navigating with the argument I will pass to other screen where I eventually will use it
class OrderDetailScreenViewModel(
    private val navigationDispatcher: NavigationDispatcher
) : ViewModel() {

    fun confirmButtonClicked() {
        navigateToAnimation()
    }

    private fun navigateToAnimation() {
        viewModelScope.launch {
            navigationDispatcher.navigateTo(AnimationsNavigation.PopUpAnimationNavigation(id = "here will be posible id"))
        }
    }
}

and this is the viewModel I am trying to get it
class AnimationsViewModel(
    savedStateHandle: SavedStateHandle
) : ViewModel() {

    init {
        val id = savedStateHandle.get<String>("id").orEmpty()
    }
}

The problem is that I always get empty string like SaveStateHandle is empty (I saw part of this way for navigation and adapt it to my app), any ideas how I can pass data like that?


text:
Q: Where is the Windows 7 games icon located? I've created my own Games folder on my data drive and i'd like to add a picture to the default folder icon:  Right-Click on Folder > Properties > Customize > Folder Pictures > Choose File...
I'd like that picture to be the games icon in Windows 7 but I don't know where it is.  I've attached a screen capture of the games icon, but the system version will have an alpha channel and already be on the system, which is better than using this screen capture.

A: It's in C:\Windows\System32\imageres.dll.

A: The icon is also stored in %windir%\system32\gameux.dll
You can find the icon's resource file by doing the following:

*

*Search for Games in the Start Menu

*Right-click Games Explorer

*Click Change Icon...


text:
Q: What is file ']' ? How is it created? I wonder how this file got in my directory? When I run ls -lrt it shows -rw-r--r-- 1 and size 117562 . Can I get any directions for this?

A: To see that is going on, in your case I would do
$ ls -l ]?
$ ls | od -x

You can create a file will any ASCII char (man 7 ascii) in unix. Almost always they are created by accident. Sometimes there is a trailing char in a file.
$ ls | od -x   # to find out.

I usually carefully remove them with ? since ? matches 1 char. First ls ? to see what is matches, then rm ? Or if there is a weird trailing char to a file then <wierdfile?>
There was a trick to make a file with the BEL ASCII code (07), so then when you did a ls, you would hear a sound.
$ touch `echo -e "\a"`   # \a is BEL
$ ls # the filename is not really ?, it is really the BEL sign (07)
?

$ ls | od -x   # see that it is 07

0000000 0a07
0000002

$ ls ? #  ? with match any file with 1 char.
?
$ rm ?  # just 1 file so safe to run it.

or interactive for even safer removal.
$ rm -i ?

rm: remove regular empty file '\a'? y
$ ls ?
ls: cannot access ?: No such file or directory

Yep file is gone.

A: Some faulty script could to that. You can delete it with
rm -vf ']'


text:
Q: Generating change set between two maps What is the best/cleanest/most-efficient way to detect changes between two Map instances. I.e.
val before = Map(1 -> "foo", 2 -> "bar", 3 -> "baz")
val after  = Map(1 -> "baz", 2 -> "bar", 4 -> "boo")

// not pretty:
val removed = before.keySet diff after.keySet
val added   = after.filterNot { case (key, _) => before contains key }
val changed = (before.keySet intersect after.keySet).flatMap { key =>
  val a = before(key)
  val b = after (key)
  if (a == b) None else Some(key -> (a, b))
}

A: Here is an idea. It probably takes O(N * log N) with N = max(before.size, after.size):
sealed trait Change[+K, +V]
case class Removed[K   ](key: K)                      extends Change[K, Nothing]
case class Added  [K, V](key: K, value : V)           extends Change[K, V]
case class Updated[K, V](key: K, before: V, after: V) extends Change[K, V]

def changes[K, V](before: Map[K, V], after: Map[K, V]): Iterable[Change[K, V]] ={
  val b = Iterable.newBuilder[Change[K, V]]
  before.foreach { case (k, vb) =>
    after.get(k) match {
      case Some(va) if vb != va => b += Updated(k, vb, va)
      case None                 => b += Removed(k)
      case _ =>
    }
  }
  after.foreach { case (k, va) =>
    if (!before.contains(k)) b += Added(k, va)
  }
  b.result()
}

changes(before, after).foreach(println)

// Updated(1,foo,baz)
// Removed(3)
// Added(4,boo)