text:
Q: Trying to prevent overflow when adding two longs I am trying to prevent overflow in two situations, one is when multipling a long with a float, and the other is when adding two longs.
Like:
public static long multiplyLong(long value, float multiplier)
{
    if (value * multiplier > long.MaxValue)
    {
        Debug.Log("greater then max value");
        return value = long.MaxValue;
    }
    else
    {
        Debug.Log("not greater then max value");
        return (long) (value * multiplier);
    }
}

public static long addLong(long value, long adder)
{
    if(value + adder > long.MaxValue)
    {
        Debug.Log("greater then max value");
        return value = long.MaxValue;
    }
    else
    {
        Debug.Log("not greater then max value");
        return value + adder;
    }
}

"multiplyLong" works perfectly, while "addLong" doesn't work like it should. When using addLong, and there will be a overflow it doesn't detect the overflow. I think this is weird because the code seems okay.
Can someone help me?
"checked" isn't an option btw.

A: Like @Bradley said, you are getting an overflow in your check for overflows. But the problem is bigger than that.
Lets look at this line first
if(value + adder > long.MaxValue)

Here, both value and adder are longs, and adding them together will result in a long. But the problem is that longs automatically roll over instead of throwing exceptions, so if your values are larger than the max value for long, you will just get some other long value seemingly at random.
Now it should be clear why you don't want to do this but before we get into what the correct solution is, lets look at your multiplyLong method. Specifically, the following line
if (value * multiplier > long.MaxValue)

In this value is a long, and multiplier is a float, and multiplying them together results in a float, which can easily be checked against a long so your check is going to appear to work.
But what if the value of value * multiplier is greater than long.MaxValue and cast it as a long?
the answer is that you get long.MinValue, which is certainly less than long.MaxValue
There is much more that can be said on this topic but, this should be enough to convince you that what you are doing is not great.
Now, what should you do? I recommend using the decimal type for two reasons. One, it has a much larger range than long (decimal can go up to 79228162514264337593543950335, where long can only go up to 9223372036854775807), the other reason is that it throws explicit exceptions when overflows happen.
For example, here is my rewritten version of your code
public static long multiplyLong(decimal value, decimal multiplier)
{
    try
    {
        return value*multiplier;
    }
    catch (OverflowException e)
    {
        Debug.Log("greater then max value");
        return decimal.MaxValue;
    }

}

public static long addLong(decimal value, decimal adder)
{
    try
    {
        return value+adder;
    }
    catch (OverflowException e)
    {
        Debug.Log("greater then max value");
        return decimal.MaxValue;
    }
}

A: By performing the addition value + adder (which returns a long) you are causing the overflow in your check for overflow.
Either force the result to something that can hold bigger numbers, ie:
if(value + (Decimal)adder > long.MaxValue)

Or catch the Overflow exception instead of trying to check for the overflow ahead of time. The reason your multiplication check works is your result is a float which can hold bigger numbers.
Note that you can cast either operand, the point is that you are getting the Decimal add operator instead of the long one; the same way you force floating point division.

A: You can have two possible overflow cases:

*

*Two big positive value and adder return non-positive result

*Two big negative value and adder return non-negative result

So you have to check both conditions for both borders in the form:
  if ((value + adder < value && value + adder < adder) ||
      (value + adder > value && value + adder > adder)) {
    // Overflow
  }

Or as you, probably, want to put it
public static long addLong(long value, long adder) {
  unchecked { // we'll detect overflow manually
    if (value + adder < value && value + adder < adder) {
      Debug.Log("greater then max value");
      return long.MaxValue;
    }
    else if (value + adder > value && value + adder > adder) {
      Debug.Log("less then min value");
      return long.MinValue;
    }
    else {
      Debug.Log("within the [min..max] range");
      return value + adder;
    }
  }
}

Tests:
addLong(2, 3);                   // within the [min..max] range
addLong(long.MaxValue - 3, 5);   // greater then max value
addLong(long.MinValue + 2, -5);  // less then min value


text:
Q: Using make_scorer in GridSearchCV to score based on recall on postive class I am trying to use Sklearn's GridSearchCV for a binary classifcation problem (originally a multi-class problem, but I was having issues as asked about here, so I decided to simplify to a binary target). In short, I have observations that are either "cancer" or "not cancer". The goal is to be able to correctly classify some observations as certainly not cancer so as to reduce the number of cases professionals would have to look over. It is clearly more important to make sure all "cancer" cases are caught than to worry about if some "not cancer" cases are accidentally classed as "cancer", so I am passing GridSearchCV a scorer that has score=recall_score, average='binary', and pos_label='cancer'. In my understanding, this will make it choose the best model (e.g find the best parameter set) based on the percent of cancerous observations that are caught. However, running the model with the best parameters as chosen by GridSearchCV produces recall on the postive class that is actually the same or even worse that that found with the defualt parameters. This is true for multiple models. Here is the code:
## Model 1: logistic regression

print('\nLogistic Regression')
mod = LogisticRegression(penalty='l2', max_iter=10000, solver='lbfgs')
mod.fit(X_train, y_train)
y_predict = mod.predict(X_test)
test_precision, test_recall, test_fscore, _ = precision_recall_fscore_support(y_test, y_predict, average='binary', pos_label='unhealthy')
print('With default params, test recall on the postive label: ', test_recall)

kf = KFold(shuffle=True, random_state=72018, n_splits=3);
mod = LogisticRegression(penalty = 'l2', max_iter=10000, solver='lbfgs')
estimator = Pipeline([("mod", mod)])
params = {'mod__C' : np.linspace(0.1, 0.5, 10)}
recall_scorer = make_scorer(recall_score, average='binary', pos_label='unhealthy')
best_model = GridSearchCV(estimator, params, cv=kf, scoring=recall_scorer)
best_model.fit(X_train,y_train)
best_final_score = best_model.best_score_ ; best_final_params = best_model.best_params_
print('Using GS, best params are: ', best_final_params)
y_predict = best_model.predict(X_test)
test_precision, test_recall, test_fscore, _ = precision_recall_fscore_support(y_test, y_predict, average='binary', pos_label="unhealthy")
print('Using these params, test recall on the postive label: ', test_recall)

## Model 2: KNN

print('\nKNN')
mod = KNeighborsClassifier()
mod.fit(X_train, y_train)
y_predict = mod.predict(X_test)
test_precision, test_recall, test_fscore, _ = precision_recall_fscore_support(y_test, y_predict, average='binary', pos_label='unhealthy')
print('With default params, test recall on the postive label: ', test_recall)

kf = KFold(shuffle=True, random_state=72018, n_splits=3);
mod = KNeighborsClassifier()
estimator = Pipeline([("mod", mod)])
params = {'mod__n_neighbors': np.linspace(1, 30, 30, dtype=int)}
recall_scorer = make_scorer(recall_score, average='binary', pos_label='unhealthy')
best_model = GridSearchCV(estimator, params, cv=kf, scoring=recall_scorer)
best_model.fit(X_train,y_train)
best_final_score = best_model.best_score_ ; best_final_params = best_model.best_params_
print('Using GS, best params are: ', best_final_params)
y_predict = best_model.predict(X_test)
test_precision, test_recall, test_fscore, _ = precision_recall_fscore_support(y_test, y_predict, average='binary', pos_label='unhealthy')
print('Using these params, test recall on the postive label: ', test_recall)

This gives the following output:
Logistic Regression
With default params, test recall on the postive label: 0.8297872340425532
Using GS, best params are:  {'mod__C': 0.27777777777777}
Using these params, test recall on the postive label: 0.8297872340425532

KNN
With default params, test recall on the postive label: 0.7588652482269503
Using GS, best params are:  {'mod__n_neighbors': 1}
Using these params, test recall on the postive label: 0.75177304964539

Am I messing up in how I define the scorer?

redpajama_set_name: RedPajamaStackExchange


text:
Q: как правильно развиваться джуниору до мидла , в ширь или в глубь? Всем привет, работаю уже полгода фронтенд разработчиком и сильно заморачиваюсь о том что мое развитие медленное и что учить чтобы стать мидлом! В интернете очень много вариантов дорожных карт по тому какими знаниями должен обладать фронтенд разработчик, но не сказано какими должен обладать мидл и на каком уровне компетенции знать ту или иную технологию! Кто то говорит что нужно учить фундамент, например если ты фронт, то React и js, но если так, то как же другие технологии! Так будешь топтаться на одном месте, я думаю! Или же сначала пока я junior изучить основы лучше, а только потом налегать на другие технологии!?
Я запутался, и мне нужен совет от опытных ребят которые с высоты своего опыта могут подсказать над чем стоит заморачиваться а над чем нет! В связи больших требований к специалисту мидл, обучаться в ширь или в глубь? Большое спасибо за понимание!


text:
Q: Photoshop script - suppressWarnings, disable error dialogs I have a script.jsx for photoshop, that exports some stuff from many PSD files. Sometimes (1 in 20 files), upon opening the psd file, the following dialog shows up:
var fileToOpen = new File(...);
open(fileToOpen);

I'm running this script on hundreds of files, and I need it to somehow ignore those dialogs. "Keep layers" would be ok, but in general, anything that will prevent the dialog will help.
I've found in a manual the option suppressWarnings, but it is only available to PdfOpenOptions or PhotoshopSaveOptions - there is no such thing as PsdOpenOptions or PhotoshopLoadOptions, neither does simple object {suppressWarnings: true} work. I have even tried adding displayDialogs = DialogModes.NO but that doesn't help either.
Is there a way to prevent this dialog? (ie. stop it from blocking the script's execution)

A: try try catch construction. If this does not help, then set the user interaction (though this may be cumbersome):
https://forums.adobe.com/thread/289239?tstart=0
Example:
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.neverInteract;
var fileToOpen = new File(...);
open(fileToOpen);
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;


text:
Q: easeljs Stage width and height are half their specified value I'm new to EaselJS and I've been having trouble positioning shapes correctly on the stage for days now. It's only today that I discovered that, while I set the canvas width and height to 800px and 450px respectively, easeljs seems to assume that the width is 400px and the height 225px (half of the set values).
I'm pretty sure I must be doing something wrong so could someone please look at this code and see what's causing the issue:
index.html
<!doctype html>
<html>
    <head>
        <title>Ludacris Labs</title>
        <meta charset='utf-8'></meta>
        <link rel='stylesheet' type='text/css' href='css/index.css'/>
        <script type='text/javascript' src='//code.jquery.com/jquery-1.10.2.min.js'></script>
        <script type='text/javascript' src="http://code.createjs.com/easeljs-0.6.0.min.js"></script>
        <script type='text/javascript' src='js/TestTube.js'></script>
        <script type='text/javascript' src='js/index.js'></script>
    </head>
    <body>
        <canvas id='canvas' width='800' height='450'>
            This application will not run on your browser because your browser is out of date.
        </canvas>
    </body>
</html>

index.css
#canvas{
    border: 1px solid #cccccc;
}

index.js
function init()
{
    var stage = new createjs.Stage("canvas");
    var dimensions = {
        width: $('#canvas').width(),//800
        height: $('#canvas').height()//450
    };

    var solution = new TestTube('water','blue');
    stage.addChild(solution);
    solution.x = dimensions.width/2-100;//300
    solution.y = 0.44*dimensions.height/2;//99
    solution.width = 50;
    solution.height = 0.55*dimensions.height;//247.5
    solution.level = 90;
    solution.render();

    stage.update();
}

$(document).ready(function(){
    init();
});

TestTube.render
    TestTube.prototype.render = function(){

        console.log(this.name,this.x,this.y,this.level);

        this.graphics.clear();

        this.graphics.setStrokeStyle(2,1,1);
        //set stroke color black.
        this.graphics.beginStroke("#000000");
        //set fill color
        this.graphics.beginFill(this.color);
       //START DRAWING------------------------------------

    //move to origin.
    this.graphics.moveTo(this.x,this.y);

    //draw line uptil point of liquid in test tube [liquid start point]
    _level = (100 - this.level)/100;
    this.graphics.lineTo(this.x,this.y+_level*this.height);

    //draw line uptil bottom of test tube.
    this.graphics.lineTo(this.x,this.y+(this.height-this.width/2));

    //draw the round part of test tube.
    //graphics.arc(centerX,centerY,radius,startAngle,endAngle,anticlockwise);
    this.graphics.arc(this.x + this.width/2,this.y+(this.height-this.width/2),this.width/2,Math.PI,0,true);

    //go back to upto level of liquid in tube [liquid end point]
    this.graphics.lineTo(this.x+this.width,this.y+_level*this.height);

    //connect liquid start point with liquid end point to fill in liquid colour.
    this.graphics.lineTo(this.x,this.y+_level*this.height);
    this.graphics.endFill();

    //go back to liquid end point
    this.graphics.moveTo(this.x+this.width,this.y+_level*this.height);

    //draw the rest of the test tube.
    this.graphics.lineTo(this.x+this.width,this.y);

    //stop drawing.
    this.graphics.endStroke();

}

Screenshot
Based on the code on index.js, you'd expect the test tube to appear near the centre of the canvas, but it appears on the bottom-right because the canvas size used is half of the canvas size set.

A: Your issue is with the drawing-coordinates inside your shape:
Each object (Bitmap, Shape, MovieClip, ect.) in EaselJS has its' own coordinate-space.
That means: If you place the shape at: 100|100  AND  draw a dot at this.x|this.y (100|100) your dot will appear on the stage at 200|200.
What you should do instead is to use 0|0 as your base and not this.x|this.y.
//move to origin.
this.graphics.moveTo(0,0);

//draw line uptil point of liquid in test tube [liquid start point]
_level = (100 - this.level)/100;
this.graphics.lineTo(0,0+_level*this.height);

//...and so on...

Trivia
The benefits of that are: If you remove the Shape and add it to a different container, it will be automatically positioned relative to that new containers' position.
Also: You do not have to worry about the absolut position of an object, this comes in very handy with more complex constructs with multiple shapes and containers. You only need to know the position relative to the parent-container.


text:
Q: Term for someone who feel the need to learn Is there any specific term for someone who feel the need of constantly learning something new ? like a learning disease.
What should the appropriate term be?

A: Bookworm may refer to excessive dedication to learning:

*

*a person excessively devoted to studying or reading (Collins)

A: An intellectually curious person?

A: The closest single definition to what you've outlined is a philomathic, from the Greek root φιλια (philia) meaning love and μαθανω (mathanó) meaning learn. It's an adjective and it means: relating to or enjoying the process of learning new facts and acquiring new knowledge. As in, "All he did was study and read all day. His friends thought he was crazy, but he was just philomathic".

A: It's not exactly what you asked for, but I think inquisitive is not bad

given to inquiry, research, or asking questions; eager for knowledge; intellectually curious: an inquisitive mind.

Dictionary.com


text:
Q: How to have VSCode look in other directories An application I am working with has a large amount of shared source in a completely separate location.  How can I configure VSCode to look there when resolving a "Go to definition" request.

A: It sounds like you need a multi-root workspace. Essentially just open both directories and save it as a workspace file.


text:
Q: JQuery issue with getting string from local file I found this solution for getting string from text file but when I try to alert it, the pop up says "Data Loaded: undefined". I put my file to the root directory, but I don't know hot to use local host on my computer. I am testing it in dreamweaver and did not send any updates to the server. Which url I should use for local testing on my Mac computer to get string from file.

A: You can get python(https://www.python.org/downloads/mac-osx/) and install it. Then open a terminal and change to the directory that your html/text file is in and run python3 -m http.server which will start a very basic server (enough for your needs) on port 8000. Very easy!


text:
Q: How to pass and store function into an object, later to be called with a method? I'm trying to create a button class that will have a press method, but when the object is created the function that I pass while creating the object is returned immediately. Is it possible to pass functions into objects and store the results to later be called?
class Button:
    def __init__(self, function):
        self.function = function

    def press(self):
        return self.function

def func():
    print("results")

button1 = Button(func())
#results is printed here
button1.press()
#I want results to be printed here

A: You want to pass in a function, not the output of that function so you'll need Button(func). Inside press however, you want to call it: return self.function()

A: You have to pass the function func not the result of the function func(), then call it in press() with function()
class Button:
    def __init__(self, function):
        self.function = function

    def press(self):
        return self.function()

def func():
    print("results")

button1 = Button(func)
#results is NOT printed here

button1.press()
#results is printed here


text:
Q: MySql join three tables together and counting row Join three tables and count
Table Ministry
mid  m_name
1    Health
2    Telecom
3    Economic

Table DocumentDetail
id  m_id doc_type
1    3    1
2    1    2
3    2    3
4    3    2
5    2    4
6    3    1

Table Type:
dID   d_name
1     pdf
2     xls
3     doc
4     png
5     zip

I would like out put like this
m_name   pdf  xls  doc  png  zip
health   0    1    0    0    0
Telecom  0    0    1    1    0
Economic 2    1    0    0    0

can we query for output like this ? thank in advance.

A: SELECT m_name,(SUM(CASE doc_type WHEN 1 THEN 1 ELSE 0 END)) as pdf,
      (SUM(CASE doc_type WHEN 2 THEN 1 ELSE 0 END)) AS xls,
      (SUM(CASE doc_type WHEN 3 THEN 1 ELSE 0 END)) AS doc,
      (SUM(CASE doc_type WHEN 4 THEN 1 ELSE 0 END)) AS png,
      (SUM(CASE doc_type WHEN 5 THEN 1 ELSE 0 END)) AS zip
FROM  Ministry INNER JOIN DocumentDetail ON Ministry.`mid` = DocumentDetail.`m_id`
GROUP BY m_name

Check here in SQL Fiddle
Hope this helps

A: If the number of doc_type is fixed, then you can try the following query else you may need to try dynamic sql query.
Query
select t1.m_name,
count(case t2.doc_type when 1 then 1 end) as pdf,
count(case t2.doc_type when 2 then 1 end) as xls,
count(case t2.doc_type when 3 then 1 end) as doc,
count(case t2.doc_type when 4 then 1 end) as png,
count(case t2.doc_type when 5 then 1 end) as zip
from Ministry t1
join DocumentDetail t2
on t1.mid = t2.m_id
group by t1.m_name;

A: If the number of types will vary over time, use this solution:
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      ', SUM(CASE dd.doc_type when ', dID,
      ' then 1 else 0 END) AS ', d_name, ' ')
  SEPARATOR '') INTO @sql
FROM Type;

SET @sql = CONCAT(
  'SELECT m.m_name',
  @sql,
  'FROM
  Ministry AS m
  INNER JOIN DocumentDetail AS dd ON (m.mid = dd.m_id)
  GROUP BY m.m_name
  ORDER BY m.m_name'
);

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Output:
m_name      pdf xls doc png zip
Economic    2   1   0   0   0
Health      0   1   0   0   0
Telecom     0   0   1   1   0


text:
Q: Some class in scala - Map side join in spark This is my code .
val ss  =  SparkSession.builder()
                       .appName("broadcastvariable")
                       .master("local")
                       .getOrCreate()

val sq  =  ss.sparkContext.parallelize(Seq("UK","UN","US","IN"))

val mp  =  Map("UK"->"United Kingdom","US"->"United State","IN"-> "India")

val br  =  ss.sparkContext.broadcast(mp)

val newVal  =  sq.map(f=>br.value.get(f))

newVal.foreach(f=> println(f))

and I am getting below output.
Some(United Kingdom)
None
Some(United State)
Some(India)

Why am I getting Some(United Kingdom) instead of just United Kingdom and how do I get only United kingdom instead of Some(United kingdom).


text:
Q: How to troubleshoot Windows? Post your checklist There is sometimes a situation when Windows suddenly goes crazy: is slow, unresponsive, some things don't work, it crashes. I wonder how do you approach diagnosing those issues.
I'm merely a programmer, not really knowing Windows too deply. There is probably more people like me... I strongly believe that experienced Windows administrators have a bunch of useful tricks that can make diagnosing easier.
Please post your techniques, the more advanced/tricky/unstandard, the better.

A: Let me start with the list:
General:

*

*Install most current updates/service packs.

*Verify drivers, look for conflicts, upgrade to newer ones.

*Use Process Explorer to see a bit more details about what's being run

*Use Process Monitor(combined filemon and regmon) to see details about particular process

*Check the services - (services.msc from command prompt).

*Problems with graphics/sound (especially with older apps) - verify DirectX (run dxdiag from console), try disabling hardware acceleration.

*See what's being run on windows boot time - Windows start points

*Scan for viruses (anyways, you should have it updated and running all the time).

*Run some anti-malware tool

*Look at windows event log (eventvwr from console)

*Make sure there is at least ~250mb free space on Windows drive.

*Check virtual memory settings.

Network:

*

*See network settings (from console: ncpa.cpl and ipconfig /all)

*Inspect firewall configuration. If you have turned Windows firewall off, check if it isn't started up.

*Look if hosts file is not modified %WINDIR%\System32\drivers\etc\hosts

Hardware:

*

*Run full HDD scan and defragment.

*Run memory test http://www.memtest86.com/
You should know most (if not all) of it already, but hopefully this helps somebody.

A: Start -> Run -> msconfig -> startup tab
Uncheck everything.  Restart and try to duplicate the problem (some apps/services will not function).  If the problem is resolved, go back into msconfig and re-check half the startup items.  Restart & duplicate the problem.  Narrow the services down by 1/2 each time.

A: If you are in the a wondrous situation where you have an image of a workstation you can just nuke it, if it was a software problem its fixed, if its a hardware problem you now know.


text:
Q: How to make bootstrap buttons in the navbar span the entire navbar I am using bootstrap to make my navbar right now and the only things I want in my navbar are 3 buttons that when clicked link to other pages. As of right now I have it looking like this:
https://i.stack.imgur.com/31s1f.jpg
As you can see those buttons are all just the size of the text that's in them.
The code is pretty simple for them right now too:

        <button class="btn btn-default" id="settings" name="settings">SETTINGS</button>

        <button class="btn btn-default" id="create" name="create">CREATE A NEW POST</button>

        <button class="btn btn-default" id="myprofile" name="myprofile">MY PROFILE</button>

How can I make the buttons take up the entire navbar? or is there a better way I should be going about this?

A: You need to use the li element inside the ul element.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

        <button class="btn btn-default" id="settings" name="settings">SETTINGS</button>

        <button class="btn btn-default" id="create" name="create">CREATE A NEW POST</button>

        <button class="btn btn-default" id="myprofile" name="myprofile">MY PROFILE</button>

A: Welcome to the community.

flex-grow-1 takes as much space as available.
There are a couple of ways to do so. But I think it is best to use the flex-grow-1 class on the buttons.
It is bugs free, and when there is not enough place for the three on the same line, the line breaks, and they each occupy all the available space.

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />

  <button class="btn btn-default flex-grow-1" id="settings" name="settings">SETTINGS</button>
  <button class="btn btn-default flex-grow-1" id="settings" name="settings">CREATE A NEW POST</button>
  <button class="btn btn-default flex-grow-1" id="settings" name="settings">MY PROFILE</button>

https://codepen.io/anon/pen/YOaXwb
Now, since there are three elements with the flex-grow-1 class, their parent's width is divided proportionately between them.

You may use mb-* or my-* class on the buttons to add some margin. If the line breaks, it is good to have same space below the buttons.
https://codepen.io/anon/pen/vzRNWm

If you want that each of the buttons takes 100% width of the nav, use d-block on the nav and w-100 on the buttons.

*

*navbar is flex by default. d-block makes it block

*w-100 sets width of buttons to 100%

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />

  <button class="btn btn-default w-100 m-1" id="settings" name="settings">SETTINGS</button>
  <button class="btn btn-default w-100 m-1" id="settings" name="settings">CREATE A NEW POST</button>
  <button class="btn btn-default w-100 m-1" id="settings" name="settings">MY PROFILE</button>

https://codepen.io/anon/pen/eLMpJX


text:
Q: How to call java method from javascript method that located within another jsni method  public class A{
    private void javaMethod(int a,int b){}

    private native void init()/*-{
            function OnMouseMove(e) {
             //blow calling doesn't work
              this.@p::javaMethod(Ljava/...teger;Ljava.../Integer;)(intVal,intVal);
            }
    }-*/;
  }

As described above,how to make that invoking work?

A: You're doing two things wrong:

*

*You're not defining the class name after @p, (assuming @p is actually just a shortened version of the real package's name);

*You're attempting to pass java.lang.Integer in place of int. You should be saying (II) as the types, as described here.
Your code should look more like this:
package com.my.package;

public class ClassA {
    private static void javaMethod(int a, int b) { ... }
    public static native void init() /*-{
       $wnd.javaMethod = function(a, b) {
          return @com.my.package.ClassA::javaMethod(II)(a,b);
       }
       function OnMouseMove(e) {
          $wnd.javaMethod(a,b);
       }
    }-*/;
}

A: Answered on the Google Group: https://groups.google.com/d/msg/google-web-toolkit/qE2-L4u_t4s/YqjOu-bUfsAJ
Copied here for reference and convenience:
First, int is not java.lang.Integer, so your method signature in JSNI is wrong; it should read javaMethod(II).
(I suppose the @p:: while javaMethod is defined in class A is over-simplification in your question, but is OK in your code)
You'll also probably have a problem with this, that might not be what you think it is. A common pattern is to assign the current object (this, at the time) to a variable that you'll reference from your closure:
var that = this;
…
function OnMouseMove(e) {
   that.@p.A::javaMethod(II)(intVal, intVal);
}


text:
Q: Successive Bounces of Ball Paradox Assume a Ball is bouncing and is travelling in the horizontal direction at constant horizontal velocity v.
Also assume that after each successive bounce, the ball is is in the air for half the time of the previous bounce.
We therefore conclude that each bounce covers half the distance of the previous bounce.
If the initial bounce is 1m, how far will the ball travel?
Method 1:
Each bounce is half the previous bounce, giving an infinite geometric series, evaluating to a travel distance of 2m.
Method 2:
The ball is travelling at a constant velocity so the ball will go on forever.
What is the explanation behind this apparant paradox?

A: This is a paraphrasing of Zeno's paradoxes.
To explain a bit further, In say the ball travels at velocity $v$, then in $t$ time, it has traveled a distance $x \cdot t$. However, each bounce, it travels half the distance, so let total distance be $D$, however, then total time is $D/v$ which is a contradiction, you said it goes on for ever, not a fixed amount of time. Yes, however, in that fixed amount of time, it travels a distance $D$.

A: I think the "paradox" arises from the fact that both 1 and 2 are correct, in the following sense.
The total horizontal distance covered whilst the ball is in the air is 2m. But after 2 seconds (assuming a horizontal speed of 1m/s)  2m has been covered whilst the ball is in the air and from now on the ball is rolling on the ground. The total horizontal distance covered is unbounded but to get the unbounded distance you have to (also) consider the distance travelled whilst the ball is on the ground.
I have made some assumptions here, like the (vertical) height of each bounce is strictly less than the height of the bounce before it but this usually happens in real life (on earth, anyway).


text:
Q: .NET-based setup project fails at installation I have created a setup project using Visual Studio 2008. When installing on a different machine, I get the following error:

The installer was interrupted before
  MyApplication could be installed. You
  need to restart the installer to try
  again.

How do I fix this problem?
The log file shows the following.
MSI (s) (D8:20) [14:06:01:020]: Executing op: ComponentUnregister(ComponentId={533BAFA2-3A54-B4D7-B625-38EB0DB9BBB7},ProductKey={B10107EF-3C57-451E-9080-40FB1F4A8B95},BinaryType=0,)
MSI (s) (D8:20) [14:06:01:020]: Executing op: ComponentUnregister(ComponentId={B55DBDAF-0BCB-061A-9EA2-5AC798377ABA},ProductKey={B10107EF-3C57-451E-9080-40FB1F4A8B95},BinaryType=0,)
MSI (s) (D8:20) [14:06:01:020]: Executing op: End(Checksum=0,ProgressTotalHDWord=0,ProgressTotalLDWord=0)
MSI (s) (D8:20) [14:06:01:020]: Error in rollback skipped.  Return: 5
MSI (s) (D8:20) [14:06:01:030]: No System Restore sequence number for this installation.
MSI (s) (D8:20) [14:06:01:030]: Unlocking Server
MSI (s) (D8:20) [14:06:01:030]: PROPERTY CHANGE: Deleting UpdateStarted property. Its current value is '1'.
Action ended 14:06:01: INSTALL. Return value 3.
MSI (s) (D8:20) [14:06:01:060]: MainEngineThread is returning 1603
MSI (s) (D8:40) [14:06:01:060]: Destroying RemoteAPI object.
MSI (s) (D8:B8) [14:06:01:060]: Custom Action Manager thread ending.
MSI (c) (10:80) [14:06:01:130]: Back from server. Return value: 1603
MSI (c) (10:80) [14:06:01:140]: Decrementing counter to disable shutdown. If counter >= 0, shutdown will be denied.  Counter after decrement: -1
MSI (c) (10:80) [14:06:01:140]: PROPERTY CHANGE: Deleting SECONDSEQUENCE property. Its current value is '1'.
Action ended 14:06:01: ExecuteAction. Return value 3.
MSI (c) (10:80) [14:06:01:150]: Doing action: FatalErrorForm
Action start 14:06:01: FatalErrorForm.
DEBUG: Error 2826:  Control Line1 on dialog FatalErrorForm extends beyond the boundaries of the dialog to the right by 3 pixels
The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2826. The arguments are: FatalErrorForm, Line1, to the right
DEBUG: Error 2826:  Control Line2 on dialog FatalErrorForm extends beyond the boundaries of the dialog to the right by 3 pixels
The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2826. The arguments are: FatalErrorForm, Line2, to the right
DEBUG: Error 2826:  Control BannerBmp on dialog FatalErrorForm extends beyond the boundaries of the dialog to the right by 3 pixels
The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2826. The arguments are: FatalErrorForm, BannerBmp, to the right
Action ended 14:06:04: FatalErrorForm. Return value 1.
Action ended 14:06:04: INSTALL. Return value 3.
MSI (c) (10:80) [14:06:04:475]: Destroying RemoteAPI object.
MSI (c) (10:F4) [14:06:04:485]: Custom Action Manager thread ending.
=== Logging stopped: 5/12/2009  14:06:04 ===
MSI (c) (10:80) [14:06:04:495]: Note: 1: 1708
MSI (c) (10:80) [14:06:04:505]: Product: CMS -- Installation failed.

MSI (c) (10:80) [14:06:04:515]: Grabbed execution mutex.
MSI (c) (10:80) [14:06:04:525]: Cleaning up uninstalled install packages, if any exist
MSI (c) (10:80) [14:06:04:545]: MainEngineThread is returning 1603
=== Verbose logging stopped: 5/12/2009  14:06:04 ===

`

A: Trying installing via the command line to get a log file. That should contain the error information.
msiexec /i program_name /lv mylogfile.log
You can use Wilogutl to make analyzing the log file easier.

A: The Visual Studio setup project will create two files for you: an MSI file and a setup.exe bootstrapper. The latter installs any pre-requisites of your application and then launches the MSI file.
When launching the setup.exe bootstrapper, a log file will be created in a subfolder of your %TMP% folder. Check for any error messages in this file.
You can also start the MSI file directly and have it create a log file:
msiexec /i mySetup.msi /l*vx log.txt

Analyzing the log should help you to find the problem. If you need any help with the error message you could edit your question and add the error message.

A: We had a similar problem and found a useful tip at the MSDN forums:
The answer was to install the "IIS Management Compatibility" server role.

A: *

*Browse to the location for the BFE service in the registry (HKLM\System\CurrentControlSet\Services\BFE\Parameters\Policy), right click and select permissions.

*In the "Permissions for Policy" window, click advanced | Add.

*Once the "Select Users, Computers or Group" box appears, change the "From this location:" to point to the local machine name.

*After changing the search location, enter "NT Service\BFE" in the "Enter the object name to select" box and click "Check names" - this will allow you to add the BFE account.

*Give the following privileges to the BFE account:


text:
Q: Steps in the Simplex Method I'm trying to look at how the Simplex method in standard form works. I understand the basics of how ti works, but I can't understand what happens between two steps.
I'm using the example from chapter 6 of Seymour Lipschutz's book Schaum's Outline of Finite Mathematics. The formulas I'm trying to maximize:
$$
x+y+z+u=3
$$
$$
2x+2y+z+v=4
$$
$$
x-y+w=1
$$
$$
-4x+2y+z+f=0
$$
I understand how to create the initial tableau, which is:

I can follow the steps to get the pivot entry (the $1$ in the $w$ row and $x$ column) and I can follow most of the steps to get the next tableau, however some entries seem to change with no explanation. The steps I'm following are:

*

*Divide each entry in the row of the pivot by the pivot entry

*In all other rows, introduce a zero in the column of the pivot entry

*Replace the variable label to the left of the pivot by the variable label above the pivot

After following this you're meant to get:

The first and third steps I'm fine with. I think the problem I'm having is with the second step. I can't see why the other values in the $u$, $v$ and $f$ rows change. Any pointers on what I'm missing?
This is a repost from CS Theory

A: To get the $0$'s in the other rows in the pivot column you're supposed to apply elementary matrix row operations.  For instance, to get the $0$ in column $x$, row $u$, multiply row $w$ by $-1$ and add it to row $u$.  Similarly, to get the $0$ in column $x$, row $v$, multiply row $w$ by $-2$ and add it to row $v$.  Finally, to get the $0$ in column $x$, row $f$, multiply row $w$ by $4$ and add it to row $f$.  This causes most of the other values in rows $u, v$, and $f$ to change as well.
What's going on under the hood here is that you're manipulating the original set of equations.  At first the equations are in terms of $u$, $v$, and $w$ ($f$ is special because it is the objective function), in the sense that if you let $x$, $y$, and $z$ be $0$ you can just read off the current solution $u = 3, v = 4, w = 1$.  We say that $u$, $v$, and $w$ are basic variables.  The next step of pivoting on row $w$, column $x$, moves $x$ into the basis and $w$ out of the basis.  Now, by letting $y$, $z$, and $w$ be $0$ you can read off the new solution $x = 1, u = 2, v = 2$.  In fact, the whole point of doing this pivot thing is that you can read off the current solution like this.
(You may ignore the following if you're not sufficiently comfortable with linear algebra.)  The pivot step is actually encoding the process of switching bases of the column space of the constraint matrix.  At first the columns consisting of the coefficients of $u$, $v$, and $w$ comprise the basis.  The pivot stop consists of the elementary matrix operations required to change the basis to the columns consisting of the coefficients of $x$, $u$, and $v$.


text:
Q: Invalid formating for empty XML tags using XMLint I have a XML unformated document, like this one :
<foo>
<bar>
<hop>
<hey>
</hey>
</hop>
</bar>
</foo>

As you can see, the tag "hey" is empty. I remember that in this case, it should be written like <hey/>, but that's not a thing I can change.
To format this document, I use the xmllint --format command. But instead of outputing
<foo>
  <bar>
    <hop>
      <hey>
      </hey>
    </hop>
  </bar>
</foo>

or
<foo>
  <bar>
    <hop>
      <hey></hey>
    </hop>
  </bar>
</foo>

it outputs
<foo>
  <bar>
    <hop>
      <hey>
</hey>
    </hop>
  </bar>
</foo>

which is not what I want. I tried to write a sed command in order to indent these particular tags after xmllint work, but I couldn't prevent sed from loading the whole (huge) xml file, and it took several minutes, like more than xmllint.
The solution would be to find an option to ask xmllint to format these tag correctly, but I could not find it in the man. Do you know something that may help me please ?

A: The hey element isn't empty, it contains a single text node whose value is a newline character. Processes that reformat the XML will typically respect that, and leave the value of the element unchanged.


text:
Q: How to span a column equal to one and half column in html table In this image two columns are spanned equal to three columns

How can I achieve this in my situation,

    Top

    Left
    Center
    Right

    Left
    Right

A:

                Top

                Left
                Center
                Right

                Left
                Right


text:
Q: MUI override custom Roboto font It seems that overriding the CSSBaseline won't work.
I'm building a website using Next.js and the MUI library, but I can't seem to get the font customization working. I tried to follow the guide and none of it works. I don't know if it has something to do with the CssBaseline theme.
_app.tsx
import { createTheme, ThemeProvider } from '@mui/material/styles'
import CssBaseline from '@mui/material/CssBaseline'

const theme = createTheme({
  typography: {
    fontFamily: [
      '"IBM Plex Sans"',
    ].join(','),
  },
  components: {
    MuiCssBaseline: {
      styleOverrides: {
        "@font-face": {
          fontFamily: "IBM Plex Sans",
          src: `url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans&display=swap')`
        },
      }
    }
  }
});

export default ({Component, pageProps}:any) => <><CssBaseline /><ThemeProvider theme={theme}><Component {...pageProps} /></ThemeProvider></>

_document.tsx
// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html>
        <Head>
            <link rel="preconnect" href="https://fonts.gstatic.com" />
            <style>@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans&display=swap');</style>

        </Head>
      <body><Main /><NextScript /></body>
    </Html>
  )
}

SOLVED: Had to put the baseline element inside the theme provider. Duh!

A: SOLVED: Had to put the baseline element inside the theme provider. Duh!


text:
Q: Java arraylist not returning correct data so I've created an arraylist in my main class called:
private static ArrayList<Job> teamNoOne = new ArrayList<Job>();

It's of type Job which is in another java file with the variables;
public class Job {
    public long time;
    public int teamNo;
    public String regNo;
    public String gridRef;
}

When the user inputs data into a textfield, I get the text entered and save it under one of the variables and add it to an arraylist.
Job job = new Job();
job.gridRef = tfGridRef.getText();

when I add the data to the array (teamNoOne.add(job.gridRef); I keep getting an error

The method add(Job) in the type ArrayList is not applicable for the arguments (String)

Thanks guys

A: You are trying to add an String to an arraylist of Job objects in the following statement:
(teamNoOne.add(job.gridRef));

because job.gridRef is a String and not a Job object.
You should try to add the Job objects to the list, something like this:
Job job = new Job();
job.gridRef = tfGridRef.getText();

teamNoOne.add(job);

A: You declared your Collection(list) telling that have only Job object's and trying to add String's.
You have to add Job object
List<Job> teamNoOne = new ArrayList<Job>();

and then
teamNoOne.add(job);  //adding job obj //correct

teamNoOne.add(job.gridRef);  //adding String/ wrong

A: Since your ArrayList is a collection of Job object, you need to add/append specific Job on it.
Job job = new Job();
job.gridRef = tfGridRef.getText();

teamNoOne.add(job);

A: When you create an array list of some object type, you have to pass the same type of objects to the add method,
 ArrayList<ObjectType> arrayListName = new ArrayList<ObjectType>();
   arrayListName.add(objectOfGivenType);

So what you have to do is assign the values to the Job object and then you can add it to the array list as above.

A: Seems like job.gridRef is a String  but as you can see that from
private static ArrayList<Job> teamNoOne = new ArrayList<Job>();, teamNoOne is list of Job. Which mean teamNoOne require Job object. So try like this:
Job job = new Job();
job.gridRef = tfGridRef.getText();
teamNoOne.add(job);


text:
Q: I want to hide tab content of previously opened tab on clicking next tab? I have 3 tabs suppose A,B and C. When user clicks on tab A its content must show, then user click on tab B the previously opened tab A content should hide and tab content of B must show and same for tab C.
this functionality should work on any randomly selected tabs.
Any Idea to perform this?
This is mine code:
>  jQuery('.view.view-user-info-page-mobile-view-responsive.view-display- id-block_1').hide();
         >jQuery('.view.view-display-id-block_2').hide();
> jQuery('#block-user-form').hide();

     >jQuery('#kes').toggle(function(){
     >jQuery('.view.view-display-id-block_1').show();
     >},
     >function(){
     >jQuery('.view.view-display-id-block_1').hide();
     >});

     >jQuery('#bookmark').toggle(function(){
     >jQuery('.view.view-display-id-block_2').show();
     >},
     >function(){
     >jQuery('.view.view-display-id-block_2').hide();
     >});

But Its not working:(

A: I have created a sample this should work i have used a dummy html for example:
it is just removal and addition of class:
$('ul.tabs li').click(function(){
    var tab_id = $(this).attr('data-tab');
$('ul.tabs li').removeClass('current');
$('.tab-content').removeClass('current');

$(this).addClass('current');
$("#"+tab_id).addClass('current');

})
Please click here to see the demo
this is the HTML that i have used: you can view the complete code in the jsfiddle link

Tab One

Tab Two

Tab Three

Tab Four

        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

         Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

        Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.


text:
Q: Windows 7 client, 2003 Server, user account locked out repeatedly and repeatably I have a Windows 7 laptop (domain member), and when I connect a VPN to the office, within 5-10 minutes the main file server/domain controller reports a failed logon for the user account, then 3, then 5, then the user account locks.
It happens with no extra software running, so it's not an Outlook problem, for instance.
I have been through control panel and cleared out the Windows and .Net password cache. There are no mapped printers, there is a mapped drive but it appears to work, and there are no scheduled tasks I can find which run so often. I have reset the user's password and put the new one on the laptop.
I have also put Wireshark on the laptop, but all that can see is "encrypted traffic" going over the VPN.
A friend has said there are issues with Windows 7 and Windows 2003 Server, e.g. with the LM hash settings which needs a hotfix. He was quite vague and there's another user with Windows 7 for whom this doesn't happen.
My suspicion is that it's Windows doing this, not a third party installed program.... but how can I dig into this further and find what's causing it?
****Update: I have disconnected the mapped drive, and the problem still happened - 4 login failures within two minutes of connecting the VPN to the office.
Event logs on the server shows Source: Security, Category: Account Logon, ID 675, Pre-authentication failed. Username: (computer-name)$, Service Name: krbtgt/domain.fqdn.example.org, failure code: 0x19
Followed by Event Security / 680 / Account Logon, MICROSOFT_AUTHENTICATION_PACKAGE_V1_0
 / Error Code: 0xC000006A
Account logoff / Unknown user name or bad password
(both repeat 4 times)
Update
I think I have it - the VPN username is the same as the Windows account username, but the passwords are different (because the VPN connects to a firewall, not a Windows server), however when accessing network resources Windows seems to be trying the VPN credentials first - because the account name is the same, the password failures cause the Windows account to become locked.
I've changed it so the VPN uses a different username and in a few minutes of testing, that seems to workaround it at least.
Would be interested if anyone knows why the (Windows 7 PPTP) VPN might behave like this and if there's an official way to stop it.

A: I have seen this happen when someone has left himself or herself logged in to another system using the same AD account. We had a rough time here with one such example. We ended up looking in the security logs on the Domain Controllers to figure out where the user had left herself logged in. Once we found out where that was we logged the user out and everything went back to normal.
I have not heard of the Win 7 / Server 2003 issue. I regularly use a Win 7 machine to administer my 40+ Server 2003 and 2008 boxes. But that's not to say this isn't the cause.
Also, I've seen a couple times when a vpn connection is unstable, and a user has the credentials saved, it may attempt to authenticate each time that the connection is dropped. This could potentially result in such a situation.
Good luck :)

A: Dennis raises a good point. The other way I've seen this happen is that you have 3rd party applications or something (3rd party or not) installed as a service that has been given the credentials and is repeatedly using them to attempt to connect to something.

A: As my last update - I think I have it - the VPN username is the same as the Windows account username, but the passwords are different (because the VPN connects to a firewall, not a Windows server), however when accessing network resources Windows seems to be trying the VPN credentials first - because the account name is the same, the password failures cause the Windows account to become locked.
I've changed it so the VPN uses a different username and in a few minutes of testing, that seems to workaround it at least.

A: Windows can sometimes record a failed login if a station attempting to log in and the server can't reach a mutually agreeable encryption setting, or worse, agree on one mistakenly (thus generating a login failure)  before falling back to another one.
By default Windows 7 is set to "Send NTLMv2 response only". The Server 2003 server may be set to "Send LM & NTLM - use NTLMv2 session security if negotiated". A bug in the protocol negotiations can produce the errored logins you are experiencing. The hotfix your friend mentioned is probably this one:
http://support.microsoft.com/kb/893318
As a workaround (and probably why that other Win7 machine is working) you can change your local security policy to work around it:
Search for "Local Security Policy". You can also find it under admin-tools in the Control Panel. Open it.
Browse to Local Policies -> Security Options.
In the list will be "Network Security: LAN Manager Authentication Level".
It will probably be set to "Send NTLMv2 response only". Change it to "Send LM & NTLM - use NTLMv2 session security if negotiated".
There is a good reason why Microsoft changed the default on this, so once the VPN server gets updated you'll want to set it back.


text:
Q: Rails Log user in after view rendered I have an apply view (index page) where the user can leave his credentials if he applies from that views an account will be generated an the user will be logged in. And an overview page will be shown (create page)
But if he is already logged in and applies the sentence "we have send your password to ... cannot be shown in my view.
So I have made the following:
  <% unless user_signed_in? %>

        <%= t("apply.create.labels.password") %>:

        <%= t("apply.create.labels.emailed_password_html", :link => mail_to(@user.personal_info.e_mail))%>
        <%= link_to(t("apply.create.labels.choose_password"), user_profile_path) %>

    <% priv_sign_in %>
   <% end %>

This code is because. If the user applies the @user info is filled in but he can only be logged in after this part of the view is generated.
In my applycontroller create I have the following to do priv_sign_in:
 # Helpers
  helper_method :priv_sign_in

  # Sign in User from View
  private
  def priv_sign_in
    sign_in(@user)
  end

Is there any better way to do is. So in an effort to make things more clear.
When I enter the create view this has to be done:
If the user is logged in --> Hide part of view
If the user is not logged in --> Show part of view and try to log in
If it is not clear please ask some questions, thanks a lot! :)

A: You should not deal with this much logic in your views.
controller :
@was_signed_in = user_signed_in?
sign_in(@user) unless @was_signed_in

View :
<% unless @was_signed_in %>

    <%= t("apply.create.labels.password") %>:

     <%= t("apply.create.labels.emailed_password_html", :link => mail_to(@user.personal_info.e_mail))%>
     <%= link_to(t("apply.create.labels.choose_password"), user_profile_path) %>

<% end %>


text:
Q: How to permanently rearrange the order of features in a Shapefile with QGIS? I have created a trimmed/clipped map of Europe, the Middle East and North Africa in QGIS 1.7.3 by deleting all the other countries from a world map shapefile. I would like to permanently rearrange the countries that are left in the shapefile in a particular sequence in the attribute table. I searched for other similar questions on this website and one answer suggested that the .dbf file be modified using a spreadsheet program, e.g., MS Excel 2003. I tried doing that and it seemed to work; but then I realized that when I pointed at Austria in the shapefile, the name that came up was Egypt. Hence, on the map itself, the names of the countries are all mixed up now.
Can you please suggest a way to arrange the countries in the attribute table according to a specific sequence without its affecting the countries on the map itself?

A: MMQGIS Sort should cover that: http://michaelminn.com/linux/mmqgis/
Never change the order of lines in a Shapefile's DBF. Can you provide the link to the answer which made you think that that's a good idea?


text:
Q: Multiple keyboard shortcuts for the same command in OS X? I am used to doing Ctrl-Shift-Tab to cycle through tabs.
I do slowly pick up the niceness about using Cmd-Shift-[ or ] to do the same on the Mac.
I have currently set TextMate to take Ctrl-Shift-Tab to do the tab cycling, but I'd want the Ctrl-Shift-[ or ] in addition to that to perform tab cycling. Is this possible?
The reason I ask is because I see that Chrome can do it both ways (not through any configuration of my own of course).

A: (I'm working at 10.11.4 environment, but I think this can work)
In my case, I have both external Screen and Keyboard (EN physical layout) attached to my MacBook Pro (ES physical layout).
Different keyboards, different keys
The thing is that the keys that I press to cycle through windows in the MacBook Cmd+§ are different from the External Keyboard Cmd+`.
So, I've forced to have two different shortcuts to achieve same action.
The solution
1. Go to:  System Preferences… > Keyboard > Shortcuts (Tab) > Keyboard (section)
2. Select: Move focus to next window
3. Create: The first shortcut you prefer
4. Go to: System Preferences… > Keyboard > Shortcuts (Tab) > App Shortcuts (section)
5. Select: Finder (as target application)
6. Create: The second shortcut you prefer
7. Voilá

A: If in TextMate tab cycling is exposed through menu items, you can also use AppleScript and QuickSilver to add the shortcuts you need.
You can find detailed instructions in this answer for a similar question (adding a second shortcut for a command in Xcode)

A: The original question is generic and the answers are specific to the presenting problem of cycling through tabs. I had this problem for a very different keyboard shortcut.
In my case, installing MacVim added a Service of "New MacVim Buffer With Selection" and I have had the keyboard shortcut of Ctrl+Shift+M set there for several years and I'm very used to using it.
But this one proprietary app was not accepting the Ctrl+Shift+M hotkey. I could change the hotkey to a wide variety of other key combinations, e.g., Ctrl+Shift+2 or Ctrl+Shift+, and it would work just fine. Something about this one hotkey was not working and the app has no mechanism for custom hotkeys.
The issue for me is that my fingers remember Ctrl+Shift+M and I didn't want to have to relearn that in all other contexts just to be able to use the command in this one proprietary app. I thought maybe I could somehow duplicate the Service and assign a different hotkey to each insance, but other threads convinced me that this was not a good option.
The solution from Darboscalante gave me the clue I needed.
In the Shortcuts window under App Shortcuts it's possible to set an app-specific hotkey for any existing menu item in an app. And "New MacVim Buffer With Selection" does indeed appear in the apps Services menu. My own personal Services are there too. I added an App Shortcuts entry for the app, used the exact menu item name, set that to Ctrl+Shift+, (comma, next to the M), and voilá, both shortcuts would open a MacVim window containing the selection.
This is a more generic solution to the original problem: The Services menu can have one hotkey and the App Shortcuts can call the same Service with a different hotkey.
For my specific purpose I discovered that I could put Ctrl+Shift+M in the App Shortcuts so now I have the same shortcut in all contexts and my (different) problem is solved, too.
I hope this helps.


text:
Q: Problem with Crystal report and connection to database - oracle i have Oracle 10g database that connect to my C# program, and i have crystal report that connect to this
database.
in my computer all work excelent !!, in customer computer the program works - except the crystal report.
what can be the problem ?
thank's in advance

A: Make sure the customer has oracle client installed depending on your senario.Maybe you have it one you machine that is why it works.


text:
Q: Problems with data binding on dependency properties I'm getting an exception telling me "Binding' cannot be set on the 'InitialStartDateTime' property of type 'WinFormsWrapper'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject." but my properties are dependency properties as you can see here, right?
public class WinFormsWrapper : WindowsFormsHost
{
    /// <summary>
    /// The control element
    /// </summary>
    private static EtDateTimeRange control = new EtDateTimeRange();

    /// <summary>
    /// The dependency property for InitialStartDateTime
    /// </summary>
    public static readonly DependencyProperty InitialStartDateTimeProperty = DependencyProperty.Register("StartDateTime", typeof(DateTime), typeof(WinFormsWrapper), new FrameworkPropertyMetadata(control.InitialStartDateTime, new PropertyChangedCallback(InitialStartDateTime_Changed)));

    /// <summary>
    /// Handles the event
    /// </summary>
    /// <param name="sender">The sender</param>
    /// <param name="e">The arguments</param>
    private static void InitialStartDateTime_Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        control.InitialStartDateTime = (DateTime)e.NewValue;
    }

    /// <summary>
    /// Gets, sets the InitialStartDateTime
    /// </summary>
    public DateTime InitialStartDateTime
    {
        get { return (DateTime)GetValue(InitialStartDateTimeProperty); }
        set { SetValue(InitialStartDateTimeProperty, value); }
    }

    /// <summary>
    /// The dependency property for InitialEndDateTime
    /// </summary>
    public static readonly DependencyProperty InitialEndDateTimeProperty = DependencyProperty.Register("EndDateTime", typeof(DateTime), typeof(WinFormsWrapper), new FrameworkPropertyMetadata(control.InitialEndDateTime, new PropertyChangedCallback(InitialEndDateTime_Changed)));

    /// <summary>
    /// Handles the event
    /// </summary>
    /// <param name="sender">The sender</param>
    /// <param name="e">The arguments</param>
    private static void InitialEndDateTime_Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        //_control.InitialEndDateTime = (DateTime)e.NewValue;
    }

    /// <summary>
    /// Gets, sets the InitialEndDateTime
    /// </summary>
    public DateTime InitialEndDateTime
    {
        get { return (DateTime)GetValue(InitialEndDateTimeProperty); }
        set { SetValue(InitialEndDateTimeProperty, value); }
    }
}

and this is my xaml:
<controls:WinFormsWrapper InitialStartDateTime="{Binding StartDateTime}" InitialEndDateTime="{Binding EndDateTime}" />

Thank you in advance!
EDIT: Thanks alot, its running now, but it's still not displaying my control, any ideas why?

A: You are using the wrong properties in your DependencyProperty creation.
public static readonly DependencyProperty InitialEndDateTimeProperty = DependencyProperty.Register("EndDateTime", typeof(DateTime), typeof(WinFormsWrapper), new FrameworkPropertyMetadata(control.InitialEndDateTime, new PropertyChangedCallback(InitialEndDateTime_Changed)));

In the Register part, it should have been InitialEndDateTime instead of EndDateTime.

A:  DependencyProperty.Register("StartDateTime",

You have to Name it
 DependencyProperty.Register("InitialStartDateTime",

:)
Same Problem with the EndDateTime
I hope that solves your problem


text:
Q: Block website from loading in native Android app Someone have created an Android app using my website URL * (There are many online free tools by which Android app can be created by just putting website URL)* and have uploaded it in Playstore. The app have 1000+ install.
Problem is - my webpages have adsense ad and these ads are also appearing in the app which is violation of adsense ad terms.
So, is there any code/JavaScript which I can place on my website and then it will stop loading my website in any such Android app using my URL.

A: You can look at this answer to detecting a mobile browser:
Detecting a mobile browser
but you should probably just report the app to the Play store for the reason you gave.


text:
Q: Multiple object request using Volley Android I want to call API Using Volley. There is an Multiple object Request So i don't Know Proper way. I was tried to code as below.But it does not give me Response.So can Anyone help me???
MainActivity
public void  getJsonResponsePost(){

    JSONObject jsonData = new JSONObject();
    JSONObject json = new JSONObject();

    /*{"data":{"lang_type":"1","keyword":"","latitude":23.022499999999997,"longitude":72.57139833333333,"category":6}}*/
    try {
        jsonData.put("data",json);
        json.put("lang_type","1");
        json.put("keyword","");
        json.put("latitude",23.022499999999997);
        json.put("longitude",72.57139833333333);
        json.put("category",6);
        Log.d("TAG",jsonData.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response)
                {
                    Log.d("String Response :",response.toString());
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(" Error getting  :",error.toString());
        }
    });

    jsonObjectRequest.setTag(REQ_TAG);
    requestQueue.add(jsonObjectRequest);
}

I get the following response
String Response :: {"status":"0","message":"Please pass the language type."}

A: Can you try this?
    try {
    json.put("lang_type","1");
    json.put("keyword","");
    json.put("latitude",23.022499999999997);
    json.put("longitude",72.57139833333333);
    json.put("category",6);
    jsonData.put("data",json);
    Log.d("TAG",jsonData.toString());
} catch (JSONException e) {
    e.printStackTrace();
}

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonData, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response)
            {
                Log.d("String Response :",response.toString());
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.d(" Error getting  :",error.toString());
    }
});


text:
Q: Process byte array as the user is still speaking from Microphone in a UWP application using the Audio Graph API I have been trying to replicate a feature of NAudio that allows the processing of user input when it is available to be processed and fed into a Google API as a byte[] Buffer.
_waveIn.DataAvailable += ProcessAudio;

The ProcessAudio method passes the Audio Buffer to the Google API
private void ProcessAudio(object sender, WaveInEventArgs e)
        {
            if (canSend)
            {
                WriteAudioData(e.Buffer);
            }
        }

Then passing the Buffer to Google API works fine.
However, with a UWP App the NAudio does not work and so I am trying to use the Audio Graph API to do the same thing but I want to access the audio data as byte[] not byte*
The following is taken from the example I have been following:
unsafe private AudioFrame ProcessAudioFrame(AudioMediaFrame audioMediaFrame)
        {
            using (AudioFrame audioFrame = audioMediaFrame.GetAudioFrame())
            using (AudioBuffer buffer = audioFrame.LockBuffer(AudioBufferAccessMode.Read))
            using (IMemoryBufferReference reference = buffer.CreateReference())
            {
                byte* dataInBytes;
                uint capacityInBytes;

                ((IMemoryBufferByteAccess)reference).GetBuffer(out dataInBytes, out capacityInBytes);

            }
        }

The issue is getting the dataInBytes as a byte Array and not as dataInBytes*.
Then I will similarly use the byte array and pass it through to the API.
So my question is, is what I am thinking of doing correct and how could I use the Audio Graph API to help solve this?
Thanks


text:
Q: Conditional probability exercise I have a following exercise:
At the exam there is $0.7$ probability that student has prepared and $0.3$ that he has not prepared. Those who are prepared have $0.9$ probability of success, those who have not prepared have $0.2$ probability of success.
What is the probability that:

*

*randomly selected student will succeed;

*student who passed the exam has not prepared for it;

*student who did not pass the exam has prepared for it.

I think that solution to 1) is simply $0.7*0.9 + 0.3*0.2 = 0.69$. Chance of succeeding in each group summed - because the sets are disjunct.
I can't figure out 2 and 3 - can you please give me an advice? Thank you.
It will probably require using formula $P(A|B) = P(A \cap B) / P(B)$.
In 2) I consider that A is event of passing the exam and B of not being prepared for it;  $P(A|B) = P(A \cap B)/0.3$. But I don't know how to compute $P(A \cap B)$.

A: We do 2. A similar procedure handles 3.
We want the probability that a student who passes did not prepare. So we want the probability she did not prepare, given that she passed.
Let $P$ be the event "she passes," and let $N$ be the event "she did not prepare."  In symbols, we want $\Pr(N|P)$. This is the key observation, the rest is downhill.
By the formula that you quoted, we have
$$\Pr(N|P)=\frac{\Pr(N\cap P)}{\Pr(P)}.$$
You found $\Pr(P)$ correctly in part 1 of the problem.
To find $\Pr(N\cap P)$, note that the probability of $N$ is $0.3$.  Given that she does not prepare, the probability the passes is $0.2$. So the probability she does not prepare and passes is $(0.3)(0.2)$.
An informal version: We have a group of $1000$ students. About $700$ prepared, and of these about $630$ passed. About $300$ did not prepare, and about $60$ of them passed. So about $690$ students passed. If we confine attention (restrict the sample space) to the $690$ who passed, about $60$ did not prepare. So the probability a student who passed did not prepare is $\frac{60}{690}$.


text:
Q: server client socket programming output difficulties m new in socket programming...i hv to create a server that stores name & id from a client in a queue and then it stores all the inputs given by the client in another queue.  when the client writes 'test', server retrieves all the stored data as the client types some value i.e. integer...when client types 'resume' server again starts storing client's given input in the queue...if client types 'exit' server sends back the client's name and id and starts waiting for a ne client. And the receives those info and closes the socket.
Problem faced:
m facing problem in retrieving the data from queues. when i type exit, i can see the name and id which i'm retriving through the for loop. if i put this line outToClient.writeBytes("Thank You!"+'\n'); after the for loop then it shows the client's name & id but the client doest go off.
in the if else condition while checking for 'test' again i'm facing problem in retrieving data. server asks for integer..client types an integer and then i dont get the data from server.
here is my code
Server Side:
import java.io.*;
import java.net.*;
import java.util.*;

class server
{
  public static void main(String argv[]) throws Exception
{
 String clientSentence;
 String replySentence;
 ServerSocket welcomeSocket= new ServerSocket(6789);

while(true)
{
System.out.println("#########Server Waiting#########");
Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

Queue<String> qe = new LinkedList<String>();

outToClient.writeBytes("Enter your Name and ID Please..."+'\n');
for(int i=0;i<=1;i++)
{
 clientSentence = inFromClient.readLine();
 qe.add(clientSentence);
}

outToClient.writeBytes("Thank you! You may now proceed further..."+'\n');

Queue<String> chatq = new LinkedList<String>();
clientSentence = inFromClient.readLine();

while(!clientSentence.equals("exit"))
{

  if(clientSentence.equals("test"))
  {
    outToClient.writeBytes("Enter Integers to fetch data or 'resume' to continue..."+'\n');
    clientSentence = inFromClient.readLine();

    while(!clientSentence.equals("resume"))
    {
        replySentence = chatq.remove();
        outToClient.writeBytes(replySentence+'\n');
        clientSentence = inFromClient.readLine();
    }

    if(clientSentence.equals("resume"))
    {
      outToClient.writeBytes("You may now proceed again..."+'\n');
      clientSentence = inFromClient.readLine();

    }
  }

  else
  {
    chatq.add(clientSentence);
    clientSentence = inFromClient.readLine();
  }

}

if(clientSentence.equals("exit"))
{
  outToClient.writeBytes("Client Name & ID: "+'\n');

 for(int i=0;i<=1;i++)
  {
    replySentence = qe.remove();
    outToClient.writeBytes(replySentence+'\n');
  }

}
}
}
}

Client Side:
import java.io.*;
import java.net.*;
import java.util.*;

class client
{
   public static void main(String argv[]) throws Exception
   {
   String sentence;
   String modifiedSentence;

   BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

   InetAddress inetAddress=InetAddress.getLocalHost();
   System.out.println(inetAddress);

   Socket clientSocket = new Socket(inetAddress,6789);
   while(true)
   {

      DataOutputStream outToServer =  new DataOutputStream(clientSocket.getOutputStream());

      BufferedReader inFromServer = new  BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

      modifiedSentence=inFromServer.readLine();
      System.out.println("From Server: "+modifiedSentence+'\n');

      for(int i=0;i<=1;i++)
      {
       sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence+'\n');
      }
       modifiedSentence=inFromServer.readLine();
       System.out.println("From Server: "+modifiedSentence + '\n');

        sentence = inFromUser.readLine();
         while(!sentence.equals("exit"))
         {

if(sentence.equals("test"))
{
  outToServer.writeBytes(sentence+'\n');
  modifiedSentence=inFromServer.readLine();
  System.out.println("From Server: "+modifiedSentence + '\n');
  sentence = inFromUser.readLine();

  while(!sentence.equals("resume"))
  {
    outToServer.writeBytes(sentence+'\n');
    modifiedSentence=inFromServer.readLine();
    System.out.println("From Server: "+modifiedSentence + '\n');
    sentence = inFromUser.readLine();
  }

  if(sentence.equals("resume"))
  {
    outToServer.writeBytes(sentence+'\n');
    modifiedSentence=inFromServer.readLine();
    System.out.println("From Server: "+modifiedSentence + '\n');
    sentence = inFromUser.readLine();

  }

}

else
{
  outToServer.writeBytes(sentence+'\n');
  sentence = inFromUser.readLine();
 }
}

  if(sentence.equals("exit"))
  {
  outToServer.writeBytes(sentence+'\n');
  modifiedSentence=inFromServer.readLine();
  System.out.println("From Server: "+modifiedSentence + '\n');
  for(int i=0;i<=1;i++)
  {
    modifiedSentence=inFromServer.readLine();
    System.out.println(modifiedSentence + '\n');
  }

  clientSocket.close();
  break;
}

}

}
}

A: I assume this is [homework] however...
You are mixing binary (DataOutputStream) with text (BufferedReader).  You should use one or the other or you are bound to confuse yourself.
It appears you want to send text so I would use BufferedReader and PrintWriter. DataOutputStream is better suited for binary protocols.


text:
Q: Center figure in section I cant get these figures to centered. They're inside a section, I've tried so many variations. All is as it should be, they float in the right way. But no matter what I try with the sections or figure codes, they still do not center within the sections.

section {
  width: 100%;
  padding: 1rem;
  display: table;
  margin: 0 auto;
  max-width: none;
  background-color: #373B44;
  height: 100vh;
}

section:nth-of-type(2n) {
  background-color: white;
}

figure.snip1165 {
  float: left;
  margin: 1rem;
  overflow: hidden;
  min-width: 150px;
  max-width: 300px;
  background: #000000;
  color: #333;
  text-align: left;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
}

Useful Tips

        Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us.

Caspian Bellevedere

        I don't need to compromise on my principles, because they don't have the slightest bearing on what happens to me anyway.

Parsley Montana

        That's the problem with nature, something's always stinging you or oozing mucous all over you. Hobbes, I think it is time you and me when and watched some TV.

A: Use text-align: center; on the section and remove float: left; on figure and use display: inline-block; and vertical-align: top; instead.
Should do the trick, see below snippet :

section {
  width: 100%;
  padding: 1rem;
  display: table;
  margin: 0 auto;
  max-width: none;
  background-color: #373B44;
  height: 100vh;
  text-align: center;
}

section:nth-of-type(2n) {
  background-color: white;
}

figure.snip1165 {
  display: inline-block;
  vertical-align: top;
  margin: 1rem;
  overflow: hidden;
  min-width: 150px;
  max-width: 300px;
  background: #000000;
  color: #333;
  text-align: left;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
}

Useful Tips

        Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us.

Caspian Bellevedere

        I don't need to compromise on my principles, because they don't have the slightest bearing on what happens to me anyway.

Parsley Montana

        That's the problem with nature, something's always stinging you or oozing mucous all over you. Hobbes, I think it is time you and me when and watched some TV.


text:
Q: Python Celery - Permission Issue - Unable to upload files from a download task I have a Celery task whose job is to download files to a local directory, and then upload to a S3 bucket when download is complete.
My issue is that with a recent update of the workers, I'm getting permission denied errors when accessing the folder to upload.  The code was fundamentally unchanged other than from going to script-method to class based implementation.
I made a task just to create the directories, with a single method call:
os.mkdirs(path, 777)

and it creates the directory with permissions 300
This is despite
CELERYD_USERS='ubuntu'
CELERYD_GROUP='ubuntu'
CELERYD_CREATE_DIRS=1

in the config.
According to the docs, the last option allows celery to create a directory owned byt the user/group specified above.  That much is happening, but nothing is said about permissions.
Is there any way around this?

A: The CELERY_CREATE_DIR only tells celery create its operational directories:

Always create directories (log directory and pid file directory). Default is to only create directories when no custom logfile/pidfile set.

I believe your problem is with the os.mkdirs. According to the os.mkdir doc, mode may be ignored on your system and you need to use os.chmod to change the mode.


text:
Q: How to Write GRUB stage1.S in NASM? I am trying to write a multi stage boot loader using NASM and gcc.
For this purpose I am referring grub boot loader source.
I have written a stage1 loader, but stuck at over writing partition
tables of MBR.
In grub stage1.S, they are using code like this to skip partition tables:
. = _start + STAGE1_PARTEND
.word   STAGE1_SIGNATURE

How can I do that in NASM?.
using times it will over write the partition tables.
So please help me.

A: Assigning a value to . is treated the same as a .org directive (see this page).

Thus, the code you pasted is changing the current origin to _start + STAGE1_PARTEND and placing a word with the value STAGE1_SIGNATURE there.
So in NASM code you should be able to do something like:
fill: times _start+STAGE1_PARTEND-$ db 0
dw    STAGE1_SIGNATURE
                     ; .word is 16 bits on x86 (regardless of .code16 / .code64)

Also see this example in the NASM manual showing how to pad a BIOS boot sector this way, as a replacement for MASM-style org or GAS-style . = new_position actually seeking and filling with padding in a flat binary output file.

A: times STAGE1_PARTEND-($-_start) db 0
dw STAGE1_SIGNATURE

A: Right, Nasm will accept only one "org" directive. The Nasm equivalent of "." is "$", but I don't think that'll help you either. I don't have the GRUB code on hand, or I'd look. Where does the partition table "come from"? If it's read from disk, there may be a signature already in place(?). Perhaps you can simply "stop" the Nasm code before overwriting the partition table and leave the existing sig in place? Nasm will do almost "anything you want", but this may be an exception. It won't "move" (skip) and assemble more at a new place as (G)as is apparently doing here - at least not readily. I may need to download the GRUB code to figure out a workaround. Possibly something like...

; stage1 code
; possible padding here?
%incbin "partition_table.bin"
dw (SIG) ; if not part of the .bin code?

... or something.


text:
Q: Change Facebook sdk language in ember I have a multilingual ember application in which i've included the facebook sdk (async):
window.fbAsyncInit = function() {
  FB.init({
    appId      : 'YOUR_APP_ID', // App ID
    channelURL : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
    status     : true, // check login status
    cookie     : true, // enable cookies to allow the server to access the session
    oauth      : true, // enable OAuth 2.0
    xfbml      : true  // parse XFBML
  });

// Additional initialization code here
  };

  // Load the SDK Asynchronously
  (function(d){
     var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     d.getElementsByTagName('head')[0].appendChild(js);
   }(document));

When the user change the application's language, i would like to change the fb sdk language as well and reparse every fb tag to get everything translated;
I've made a function to set the js.src attribute properly, but the sdk is loaded only when the page refresh, and it happens only on the first load.
How can i reload the sdk with the properly js.src attribute in ember at runtime?


text:
Q: "A well Oxford-educated politician" OR "A well-Oxford-educated politician"? I saw many examples like "He is an Oxford-educated politician" and I'm curious about the usage of hyphens here by adding "well" in the front.
Is it

*

*"He is a well-Oxford-educated politician"
or

*"He is a well Oxford-educated politician" ?

My intention is to tell that he is well-educated in Oxford.

A: It doesn't really work to string adjectives together with hyphens like that. You would have to say that he is a well-educated Oxford-educated politician, but the repetition is awkward. I would use a well-educated politician who attended Oxford.


text:
Q: Objc computed property vs method I just saw this in the Apple source:
@property (readonly, copy) NSString *uppercaseString;

So to uppercase a string one would do
@"sdfks".uppercaseString;

Is there any advantage doing it this way and not just a method
- (NSString *) uppercaseString;

I am positive it is the same, but I really want to know why would you use the readonly variant instead of method or other way around.

A: One way or the other, you are using a method.
Objective-C properties boil down to a method (or a pair of methods for settable properties) that you can call using two alternative kinds of syntax - the dot syntax
@"sdfks".uppercaseString

and the regular method call syntax
[@"sdfks" uppercaseString]

Dot syntax becomes more convenient when you need to access properties of objects produced by other method calls:
person.address.city.uppercaseString

syntax has less punctuation than
[[[person address] city] uppercaseString]

and for that reason may be more visually appealing to some programmers.


text:
Q: Will an application on PHP Yii framework with MySQL database handle an ERP solution of 20K employees? We have got a project to build an ERP system for one of the largest garment industry of Bangladesh.
They have around 20,000 employees and about 10% of them get out/in every month. We are a small company with 5 PHP developers and don't have much experience with such a large project. We have developed different small/medium scale projects previously with Codeigniter/Zend Framework and MySQL database.
For this project we decided to go with Yii framework and MySQL or PostgreSQL. There will be about 1 million database query every day. Now my question is can MySQL/PostgreSQL handle this load or is there a better alternative? Is it ok to do it with Yii framework or there have a better PHP framework for this kind of application? We have got only 5 months to build the payroll and employee management modules.

A: For one thing, consider using PostgreSQL rather than MySQL. You're going to be dealing with mission-critical data and, in general, you'll appreciate that:

*

*You will have access to window functions (useful for reports), with statements, and a much more robust query planner.

*You will have extra data types, namely geometry types which can be used to optimize date-range overlap related queries.

*You will have access to full text search functionality without needing to use an engine (MyISAM) which is prone to data corruption.

*You will have more options to implement DB replication (some of which are built-in).

With respect to scalability, be wary that scalability != performance. The latter is about making individual requests faster; the former is about being able to handle massive quantities of simultaneous requests, and often comes with a slight hit to the latter.
For the PHP framework, I've never used Yii personally, so I do not know how well it scales. But I'm quite certain that Symfony2 (or Symfony, if you're not into using beta software) will scale nicely: its key devs work in a web-agency whose main customers are mid- to large-sized organizations.

A: I think, Yii will work fine with (relatively) large amount of data. I'm using Yii to manage 1.3 million records, some thausend updates a day and some thousand querys a day on an small virtual host with an amazing performance.
If your database can handle this data, your Yii application will also handle that.
Your choice of the database will be an important point. So @Denis said some important thinks. By using MySQL probably you have to explore / determined the right storage-engine for your needs.
But, there are some points, which i realized by creating an growing project with Yii. You should think about those things:
-Yii is an young framework: new technologies (like ajax) are supported, but in some special cases it's a bit immature: it's very easy  to generate an basic application in a cuple of hours. Problem could be occur by special situation and requirements.
 Example: they have an nice validation-mechanism for user inputs(HTML Forms). But until Yii 1.1.6 that doesn't work with HTML Checkboxes, since Yii 1.1.7, Checkboxes are supported by default, but no groups of checkboxes. An other problem: Yii alway uses an table alias, which is always "t". That could be a problem! Sometimes you can define that alias, sometimes not (which is inconsistent). If you like to lock a couple of tables in MySql, you ran into a problem, because Yii calls every table with the same alias "t". So you are unable to loot the tables in MySql by tablename and it's also impossible to lock a couple of tables, which called by the same alias. -> those are specific problems, you can solve them, by writing pure PHP (not using Yii functionality) What I'm trying to say: the framework will not be helpful in very case, but in mostly.
-Yii is easy to extend. It's easy to add own extensions or functionality. So lot's of those "small problems" can be solved be writing own extensions, widgets or by overriding methods.
-Yii supports PHP 5.2. Yii is compatible with 5.3 but (Yii runs on 5.3 - i'm still using it since yesterday, it work's) but doesn't support new features from 5.3 (maybe you need one?)
PHP5.3 will be (maybe) supported with Yii 2.0 - in a distance future (2012)
-Yii has a small (but very good) community.
-there is no professional support (you can post bugs in hope, anybody will fix it - or you will fix it yourself)
-Yii is OO PHP. Think about that by handling with Data-Objects. It's possible to load large amount of data into Data-objects. But keep in mind, that your application server have enough RAM (but that's not a Yii specific thing)
At all: i like Yii an if your application is not to complex, you will have a lot of fun an an nice and powerful application at the end.

A: I think you might be asking the wrong question, though.
You have five months to build an ERP system. The primary concerns should be:

*

*security. You're dealing with money and personal details.

*reliability. Uptime is probably a big deal (at least during working hours)

*consistency. You don't want to risk losing data or corrupting data

*developer productivity. Five months is not much time do build what you describe

*maintainability. Sounds like this is a core enterprise asset, with a lifetime of years - it's likely to require maintenance and extension in the future.

*scalability. You need to support tens of thousands of workers, each with many time cards, pay roll runs etc.

*performance. You want the application to be responsive.

I would query whether performance is an absolute priority - it shouldn't be slow, but many ERP systems are a bit sluggish. Performance optimizations often mean trading off other priorities - for instance, an ORM system improves developer productivity, but can be slower than hand-crafted SQL.
As for scalability - as long as you have a reasonably designed schema, I don't think 20K employees is much of a challenge to any modern RDBMS on decent hardware.
So, if I were you, I'd probably go with PostgreSQL, for the reasons Denis mentions. Never used Yii, but it seems perfectly reasonable. I would use ORM until you find a situation where the performance really is unacceptable.
Critically, I would put together a testing framework which allows you to monitor performance and scalability during the development cycle (I use JMeter for this), and only make performance optimizations if you really have to. Sacrificing all the other things - especially productivity and maintainability - in the name of performance before you know you have a problem tends to create over-complex solutions, and they in turn tend to have more security issues and maintenance challenges.

A: Just to add ,
Yii scales very nicely in both directions (ie functionality addition using new modules etc and is one of the fastest php frameworks when it comes to performance ).
The only drawback I can see with Yii is that it has lesser user base so a bit lesser support than some other frameworks, but this is changing fast.
The best part of Yii is the gii based code generation which helps you get started really quickly once you get used to it.

A: Yii is very flexible, light and easy to learn PHP framework.


text:
Q: Listview items with rounded corners I am trying to make listview items rectangular shape with rounded corners but what's happening with me, only first row comes with rounded corners on upper part, rest of the child listview items comes in rectangular shapes with no rounded corners. I don't know why this is happening.
Here is my listview codes:
<ListView
    android:id="@+id/listViewdoctorwithappointment"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="7dp"
    android:layout_marginRight="7dp"
    android:layout_marginTop="10dp"
    android:minHeight="80dp"
    android:background="@drawable/customshapeduplicate"
    android:cacheColorHint="@android:color/transparent"
    android:divider="#4F94CD"
    android:dividerHeight="10dp"

    android:smoothScrollbar="true"

    android:listSelector="@drawable/selector"
    android:scrollbars="none" >
</ListView>

And Here is my customshapeduplicatefile is this:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:startColor="#ffffff" android:endColor="#ffffff"
        android:angle="270"/>

    <corners android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp" android:topRightRadius="10dp"/>
</shape>

And this is the image:

A: set the background not for the listview but the custom layout that you are using to display listview row
android:background="@drawable/customshapeduplicate"

A: I suggest you use a custom list adapter. Modify the below code according to your requirements.
 public View getView(final int arg0, View arg1, ViewGroup arg2) {
    final ViewHolder vh;
    vh= new ViewHolder();

    if(arg1==null )
    {
                    arg1=mInflater.inflate(R.layout.lyourcustomlayouttobe inflated, arg2,false);
            arg1.setTag(vh);
            }

    return arg1;
}

Your custom layout
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="horizontal"
 android:cacheColorHint="#000000"
 android:background="@drawable/listviewbkg">
 //other items to be inlfated.
 </LinearLayout>

Create a drawable folder under resources. post the below xml as listviewbkg
 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_pressed="true"
    android:drawable="@drawable/pressed" />
 <item  android:state_focused="false"
    android:drawable="@drawable/normal" />
 </selector>

Shape when normal under drawable with name normal.xml
 <?xml version="1.0" encoding="UTF-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android">
 <solid android:color="#FFFFFF"/>
 <stroke android:width="3dp"
        android:color="#0FECFF" /><!-- #330000FF #ffffffff -->
 <gradient                               // remove the gradient if do not wish to use.
    android:startColor="#ffffffff"
    android:endColor="#110000FF"
    android:angle="90"/>

 <padding android:left="5dp"
         android:top="5dp"
         android:right="5dp"
         android:bottom="5dp"/>
 <corners android:bottomRightRadius="7dp"      // change this to increase the rounded edge radius
         android:bottomLeftRadius="7dp"
         android:topLeftRadius="7dp"
         android:topRightRadius="7dp"/>
 </shape>

Shape when pressed under the name pressed.xml in drawable folder
  <?xml version="1.0" encoding="UTF-8"?>
  <shape xmlns:android="http://schemas.android.com/apk/res/android">
  <solid android:color="#FF1A47"/>
  <stroke android:width="3dp"
        android:color="#0FECFF"/>
  <padding android:left="5dp"
         android:top="5dp"
         android:right="5dp"
         android:bottom="5dp"/>
  <corners android:bottomRightRadius="7dp"
         android:bottomLeftRadius="7dp"
         android:topLeftRadius="7dp"
         android:topRightRadius="7dp"/>
  </shape>

A: That is because the background-attribute is the background of the entire list, not the individual rows.
To achieve what you want, either set a custom background through your Adapter or list-item layout, or look at this answer.


text:
Q: Beginning with SQL - dummies guide This is going to be the most simple question, but I'm new to this and can't figure out what to do. I am trying to learn Microsoft SQL for work, I have bought a course and started the modules. The problem is I cannot practice because I don't have SQL or any sort of database installed on my computer. And I have a mac! How can I practice - is there a database and version of sql that I can download on my mac, or is there some other way I can practice on my mac.
Apologies for the simple question, I'm fine with learning new languages, it's just the system requirements I don't get!

A: There is mac sql client can find on:
http://www.macsqlclient.com/
But there is no version of sql server available for MAC till date.

A: I was in the same situation I have a mac and I needed to learn SQL for work so i Used this site : http://www.w3schools.com/sql/default.asp
Its not a class but you can use its test database that is all online and through the browser.
Hope this helps. If not put windows OS on your mac using bootcamp and install the programs on the windows partition.


text:
Q: axis-java2wsdl task classpath setting problem here is my build.xml
<?xml version="1.0" standalone="yes"?>

<path id='axis2.classpath'>
<fileset dir='D:\Tools\axis2-1.5.1-bin\axis2-1.5.1\lib'>
            <include name='**/*.jar' />
        </fileset>
</path>

<path id='compiled.class.path'>
<fileset dir='./bin/pkg'>
            <include name='*.class' />
        </fileset>
</path>

<taskdef resource="axis-tasks.properties" classpathref="axis2.classpath" />

<target name="run" >
    <axis-java2wsdl
        output="out/TestService.wsdl"
        location="http://localhost:8080/axis2/service/TestService"
        namespace="service"
        classname="TestService">
        <classpath refid="compiled.class.path"/>
        <mapping namespace="TestService" package="pkg"/>
    </axis-java2wsdl>
</target>

here is my file structure:
prj->bin->pkg->TestService.class///////////
prj->src->pkg->TestService.java///////////
prj->build.xml
I get java.lang.ClassNotFoundException: TestService.
Can anybody tell me how to fix it? Thanks so much. !!!!!!!!!!!!!

A: Is TestService in a package called "pkg", or is it in the default package (i.e., no package)? If it's in a package called "pkg", you want to define your "compiled.class.path" like:
<path id='compiled.class.path'>
   <fileset dir='./bin'>
      <include name='**/*.class' />
   </fileset>
</path>


text:
Q: MySQL creationg table error with Positional message Hello I am new to MySQL and having trouble creating a table. It says that the types im using are not valid at their position with ')'.
Can someone tell me what is wrong with this code snippet?
create table CUSTOMER(
    CustomerID int AUTO_INCREMENT,
    LastName varchar,
    FirstName varchar,
    Address varchar,
    City varchar,
    State varchar,
    ZIP number,
    Phone number,
    EmailAddress varchar,
    constraint pk_cID primary key(CustomerID));

A: Your table should look like:
create table CUSTOMER(
    CustomerID int not null  AUTO_INCREMENT,
    LastName varchar(100),
    FirstName varchar(100),
    Address varchar(100),
    City varchar(100),
    State varchar(100),
    ZIP int,
    Phone varchar(50),
    EmailAddress varchar(100),
    primary key(CustomerID)
);

*

*number is not a datatype in MySQL

*When you assign auto_increment it should be not null auto_increment

*You don't need a constraint for primary key, just add primary key.

*I don't  think the best way of storing Phone  numbers is int, you might have different formatting the best way is to treat numbers as addresses , so varchar would be better


text:
Q: How to share a directory between windows and virtualbox? I recently installed virtualbox 6.1.4 on my windows 10.
I used the image ubuntu-18.04.4-server-amd64 as image.
When I try to share a directory between windows and linux, It doesn't appear on linux virtual machine.
The image of configuration used is below:
The program is in portuguese, however, the shared area of transference and the drag and drop are set to biderectional
The shared folder path is: C:\Users\my-user-name\VirtualBoxVMs\ubuntu_server\share
Folder name: share. And It is set to automaticaly mounting.
When I try the installed guest additions, this error appears:
Error 2
How can I create a shared folder between VM and Windows?

A: You have to install VBoxGuestAdditions manually! Start your virtual machine, open a terminal and type in this order those commands:
sudo apt-get install wget
wget http://download.virtualbox.org/virtualbox/4.3.8/VBoxGuestAdditions_6.1.4.iso
sudo mkdir /media/VBoxGuestAdditions
sudo mount -o loop VBoxGuestAdditions_6.1.4.iso /media/VBoxGuestAdditions
sudo sh /media/VBoxGuestAdditions/VBoxLinuxAdditions.run
rm VBoxGuestAdditions_6.1.4.iso
sudo umount /media/VBoxGuestAdditions
sudo rmdir /media/VBoxGuestAdditions

it may ask your root password, if your user does not belong to sudoers, just type su -, insert root psswd and repeat all above command without sudo:
apt-get install wget
wget http://download.virtualbox.org/virtualbox/4.3.8/VBoxGuestAdditions_6.1.4.iso
mkdir /media/VBoxGuestAdditions
mount -o loop VBoxGuestAdditions_6.1.4.iso /media/VBoxGuestAdditions
sh /media/VBoxGuestAdditions/VBoxLinuxAdditions.run
rm VBoxGuestAdditions_6.1.4.iso
umount /media/VBoxGuestAdditions
rmdir /media/VBoxGuestAdditions

You just have to reboot now and you should be able to see you shared folder!