text:
Q: boto: EC2 instance get_attribute results in AttributeError: 'EC2Connection' object has no attribute 'describe_attribute' What steps will reproduce the problem?
1.attempt to get a running EBS-backed instance's kernel attribute with instance.get_attribute('kernel')
>>> import boto.ec2
>>> regions = boto.ec2.regions()
>>> regions
[RegionInfo:eu-west-1, RegionInfo:us-east-1, RegionInfo:us-west-1, RegionInfo:ap-southeast-1]
>>> usw = regions[2]
>>> conn = usw.connect()
>>> reservations = conn.get_all_instances()
>>> reservations
[Reservation:r-XXXXXXXX]
>>> r1 = reservations[0]
>>> for i in r1.instances: print i
...
Instance:i-XXXXXXXX
>>> instance = r1.instances[0]
>>> instance.get_attribute('kernel')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/boto/ec2/instance.py", line 293, in get_attribute
    return self.connection.describe_attribute(self.id, attribute)
AttributeError: 'EC2Connection' object has no attribute 'describe_attribute'
>>>

What is the expected output? What do you see instead?
expect to get the attribute, but instead get this error: AttributeError: 'EC2Connection' object has no attribute 'describe_attribute'
What version of the product are you using? On what operating system?
boto.Version == 2.0b3 on Mac OS X 10.5 (boto installed using pip)
Please provide any additional information below.
Code on github repo seems to also indicate that there's not a describe_attribute
https://github.com/boto/boto/blob/master/boto/ec2/connection.py
submitted issue: http://code.google.com/p/boto/issues/detail?id=487

A: Problem was promptly fixed by the developers!
https://github.com/boto/boto/commit/899ab55752d31af22f41168f92fe39553504d6fc
However at time of writing, it's still not on pypi (so pip install --upgrade) won't help - must git clone and install from there.


text:
Q: What will happen if the N region in a PNP transistor is replaced with metal? I came across this question when I appeared for an interview at one of the IITs for my PhD course.
The interviewer also asked me to draw the I-V characteristic of the modified device. I asked this of many of my technical friends but all of them failed to convince me with the answer.
What I learned was that there will be some Schottky contact developed between metal and semiconductor.
Will the new device be still called a transistor?
Any reference or research paper link would be appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SurfaceView is clipping my Views I've programmed my own custom ViewGroup to be able to display several child views and also dynamically move them around and rotate them.
I also combine this custom ViewGroup with a background SurfaceView that is displaying the Camera preview in order to have the Camera Preview as a background all the times.
Everything works fine if I just use my ViewGroup without the Camera SurfaceView, but when I add the Camera SurfaceView I get this strange clipping behaviour as documented in the images. Notice that the clipping only happens if I move or rotate my views, they seem to be unclipped in the original location.
In the following images the blue lines are supposed to be the enclosing rectangle of the child Views that is passed onto the layout method that I call on all the child views of my custom ViewGroup:
public void layout (int l, int t, int r, int b)
http://developer.android.com/reference/android/view/View.html#layout(int, int, int, int)
Don't worry about the red lines.
My hypothesis is that when the ViewGroup is first created it only takes into account the position of the original childviews and this is the space that is reserved for them. And as soon as I rotate them they are clipped to their original rectangle.
270 degrees rotation:

The same with Camera background(the camera does not appear on the screen capture that's why it is also black):

320 degrees rotation:

The same with Camera

0 degrees rotation:

The same with Camera

Here are fragments of the code, I cut a lot of stuff out but this is the very basic functionality(mLayout is my custom ViewGroup):
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      requestWindowFeature(Window.FEATURE_NO_TITLE);
      cPreview = new CameraPreview(this);
      setContentView(cPreview, new ViewGroup.LayoutParams(FILL_PARENT, FILL_PARENT));
      test1();
    }

    private void test1() {
        addContentView(mLayout, new LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.FILL_PARENT));
    }

A: The solution found is to set this flag setWillNotDraw(false) in Your SurfaceView
The raison is explained here


text:
Q: AlarmManager LifeCycle and Canceling Error I've an application that has a widget already and have a service which updates that widget in every 5 seconds.
Here is my AppWidgetProvider:
public class MyWidget extends AppWidgetProvider {

    PendingIntent service = null;
    AlarmManager alarmManager;

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        final Intent i = new Intent(context, MyService.class);

        if(service == null) {
            service = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
        }

        alarmManager.setRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime(), 1000*5, service);
    }

    @Override
    public void onDisabled(Context context) {
        Log.d("LogTag", "onDisabled");
        alarmManager.cancel(service);
        service.cancel();
    }
}

And my Service:
public class MyService extends Service {

    int b = 5;

    @Override
    public void onCreate() { super.onCreate(); }

    public int onStartCommand(Intent intent, int flags, int startId) {
        this.buildUpdate();
        return 0;
    }

    private void buildUpdate() {
        Log.d("AAA", "Update is coming");

        RemoteViews rmViews = new RemoteViews(getPackageName(), R.layout.widget_layout);

        rmViews.setTextViewText(R.id.hello, "Iterator: " + Integer.toString(b));

        ComponentName thisWidget = new ComponentName(this, MyWidget.class);

        AppWidgetManager manager = AppWidgetManager.getInstance(this);

        manager.updateAppWidget(thisWidget, rmViews);

        b++;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}

Service and other things are fine. But still I've couple questions about all these stuff:

*

*What's for SystemClock.elapsedRealtime() which is a parameter in setRepeating method? Does it point when to start?

*When I try to delete widget, I got some errors (on below) and unfortunately AlarmManager still works not cancel. What am I missing?

*I need to do some network operations before widget has been initialized (or called). Widget should has some data from server. Should I use AsyncTask or what?
When I try to delete widget, getting:
03-04 23:39:51.428: E/AndroidRuntime(5646): Uncaught handler: thread main exiting due to uncaught exception
03-04 23:39:51.438: E/AndroidRuntime(5646): java.lang.RuntimeException: Unable to start receiver com.example.widget.MyWidget: java.lang.NullPointerException
03-04 23:39:51.438: E/AndroidRuntime(5646):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2646)
03-04 23:39:51.438: E/AndroidRuntime(5646):     at android.app.ActivityThread.access$3100(ActivityThread.java:119)
03-04 23:39:51.438: E/AndroidRuntime(5646):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913)
03-04 23:39:51.438: E/AndroidRuntime(5646):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-04 23:39:51.438: E/AndroidRuntime(5646):     at android.os.Looper.loop(Looper.java:123)
03-04 23:39:51.438: E/AndroidRuntime(5646):     at android.app.ActivityThread.main(ActivityThread.java:4363)
03-04 23:39:51.438: E/AndroidRuntime(5646):     at java.lang.reflect.Method.invokeNative(Native Method)
03-04 23:39:51.438: E/AndroidRuntime(5646):     at java.lang.reflect.Method.invoke(Method.java:521)
03-04 23:39:51.438: E/AndroidRuntime(5646):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
03-04 23:39:51.438: E/AndroidRuntime(5646):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
03-04 23:39:51.438: E/AndroidRuntime(5646):     at dalvik.system.NativeStart.main(Native Method)
03-04 23:39:51.438: E/AndroidRuntime(5646): Caused by: java.lang.NullPointerException
03-04 23:39:51.438: E/AndroidRuntime(5646):     at com.example.widget.MyWidget(MyWidget.java:33)
03-04 23:39:51.438: E/AndroidRuntime(5646):     at android.appwidget.AppWidgetProvider.onReceive(AppWidgetProvider.java:76)
03-04 23:39:51.438: E/AndroidRuntime(5646):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2637)
03-04 23:39:51.438: E/AndroidRuntime(5646):     ... 10 more

A: *

*SystemClock.elapsedRealTime() as you have it is currently in the triggerAtTime parameter, meaning that any number you put there is the time that you want the alarm to go off. elapsedRealtime() is counted in milliseconds since the system was booted, including deep sleep. This clock should be used when measuring time intervals that may span periods of system sleep.

*In you onDisabled method, you need to recreate the entire PendingIntent. My guess is it is null there because it doesn't actually exist when you call onDisabled, but only exists in the onUpdate. So recreate the service variable PendingIntent exactly the same way as you do before and then call cancel on it as you already are.

*AsyncTasks are good for things like that. An AsyncTask spawns a managed thread in the background and does work while the UI thread keeps going, then can update the UI thread when done. So if you have lots of heavy networking to do, an AsyncTask will handle that beautifully. The docs on AsyncTask are very useful. Find them here. There are many options for this depending on what you are doing, so you'd have to explain your issue on this third point in a little more detail to get a more tailored answer.


text:
Q: Deeplinking in Xamarin Forms I am trying to deep link my app with website and for that I tried two ways:
 <meta property = 'al:ios:url'  content = "realagent://chats"/>
 <meta property = 'al:android:url'  content = "realagent://chats"/>
 <meta property = 'al:android:package' content = "com.application.xyz"/>

and
window.location = 'yourapp://app.com/?screen=xxxxx';

But neither work for me. I tried the first one and it doesn't even work on a single platform, but second one works on Android.
Please help me with this, and suggest the correct way?


text:
Q: Post from front end to custom metabox I have a custom metabox in a custom post type. I'm using a front end posting page.
The information added by users in the form should be displayed in the post and appear in the back-end meta box in the custom meta boxe.
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['submitted'] ) &&  $_POST['submitted'] == "new_post") {

    // Do some minor form validation to make sure there is content
    if (isset ($_POST['postTitle'])) {
        $title =  $_POST['postTitle'];
    } else {
        echo 'Please enter the wine name';
    }
    if (isset ($_POST['postContent'])) {
        $description = $_POST['postContent'];
    } else {
        echo 'Please enter some notes';
    }

    // ADD THE FORM INPUT TO $new_post ARRAY
    $new_post = array(
    'post_title'    =>  $title,
    'post_content'  =>  $description,
    'post_status'   =>  'pending',           // Choose: publish, preview, future, draft, etc.
    'post_type' =>  'portfolio'  //'post',page' or use a custom post type if you want to
    );

    //SAVE THE POST
    $pid = wp_insert_post($new_post);

    wp_redirect( home_url() );

} // END THE IF STATEMENT THAT STARTED THE WHOLE FORM

//POST THE POST YO
do_action('wp_insert_post', 'wp_insert_post');

get_header();

here is the form
<input type="text" id="short_description" name="short_description" style="padding: 7px; width: 100%;" value="<?php echo $short_description_no_html; ?>" />


text:
Q: How to pass a captured value (handle) from {% raw %} to get a object from shopify in liquid? I'm using vue3 and liquid for some Shopify theme developments.In my case, there is a value from vue component and I want to use this value to get a shopify object within liquid file.
<div v-for="handle in featuredHandlesArray" :key="handle" >
  {% capture article_liquid %}
    {% raw %}{{ handle }}{% endraw %}
  {% endcapture %}

  {% assign article_obj = articles[article_liquid] %}
</div>

Here I'm getting above 'featuredHandlesArray' from vue component and looping with a v-for. There's no issue with it. If I echo these 'handle' value in the loop, it prints my relevant handle. Even when I echo captured 'article_liquid' variable below the '{% endcapture %}' tag, it prints too. But when I try to pass that handle to get the article object from shopify, it's nothing. It means 'articles[article_liquid]' is not working. I just want to get that article object from shopify by passing handle and assign that object into a variable like 'article_obj'.
If anyone experienced this kind of issue, please give me a support. Or any suggestion will be very appreciated. Thanks!


text:
Q: position is an array in javascript or jquery

  //array 1

  //array 2

  //array 3

  //array 4

  //array 5

  //array 6

  //array 7

I need to get the position of a certain div
but when I run the code I get error
VM163:1 Uncaught TypeError: $(...)[0].position is not a function(…)

A: Try this: http://jsbin.com/liliwarogo/1/edit
var x = $($(".example")[0]).position();  //array 1 [0]
alert("Top: " + x.top + " Left: " + x.left);

Basically, if you do $(".example")[0] it's not a jQuery element anymore, so position() doesn't exists. I wrapped everything up in jQuery again, to get the position() function.
Of course, the optimal solution would be something like this: $(".example:eq(0)").position()

A: This solution only use JavaScript.
var x = document.getElementsByClassName("example")[0].getBoundingClientRect();
alert("Top: " + x.top + " Left: " + x.left);

Here is the Jsbin example


text:
Q: How to create a monolithic Composer package with a built-in composer-plugin? I want my package to ship with a built-in composer-plugin.
I have a structure like this:
composer.json
src/
    ...
plugin/
    composer.json
    src/
        ...

The root composer.json is configured like this:
{
    "name": "foo/bar",
    "type": "library",
    "autoload": {
        "psr-4": {
            "Foo\\Bar\\": "src/"
        }
    },
    "repositories": [
        {
            "type": "path",
            "url": "./tools",
            "options": {
                "symlink": false
            }
        }
    ],
    "require": {
        "foo/bar-plugin": "*"
    }
}

And the built-in composer-plugin's plugin/composer.json like this:
{
    "name": "foo/bar-plugin",
    "type": "composer-plugin",
    "require": {
        "composer-plugin-api": "^1",
        "composer/composer": "^1",
        "foo/bar": "*"
    },
    "autoload": {
        "psr-4": {
            "Foo\\Bar\\Plugin\\": "src/"
        }
    },
    "extra": {
        "class": "Foo\\Bar\\Plugin\\MyComposerPlugin"
    }
}

Notice how there's a two-way dependency here - the plugin depends on foo/bar, and the project itself depends on foo/bar-plugin.
Here's where it gets weird. During a fresh installation with e.g. composer install or composer update, everything is fine - the plugin does it's thing, which, right now, means just announcing itself on the console.
Now, after installation, if I type just composer, I'd expect to see the plugin announce itself, same as before, right?
Instead, it generates a fatal "class not found error", as soon as it tries to reference any class belonging to the foo/bar package.
It's as though composer lost track of the fact that foo/bar-plugin requires foo/bar, and for some reason it's classes aren't auto-loadable.
Is there any reason this shouldn't be possible? Why not?
Of course I can just package this stuff in separate external package, but that isn't going to make much sense, since these packages are just going to depend on each other - they're effectively one unit, a packaging them as two packages is going to result in a mess of major version increases with every small change, as basically every release of foo/bar will break foo/bar-plugin.
Ideally, I'd like to simply add the composer-plugin directly into the main package, but it appears that's not possible for some reason? Only a package with type composer-plugin is allowed to add plug-ins, it seems?

A: If the plugin is essentially a part of your package, you should not use it as such. Composer offers alternatives.
As Jens mentioned in a comment to your question, there is 'scripts' key in composer.json. You can invoke shell commands inside, but also call static class methods.
About plugin solution - composer explicitly mentions this on its site:

Composer makes no assumptions about the state of your dependencies prior to install or update. Therefore, you should not specify scripts that require Composer-managed dependencies in the pre-update-cmd or pre-install-cmd event hooks. If you need to execute scripts prior to install or update please make sure they are self-contained within your root package.

(my side note - this also roughly applies to plugins).
Anyway - to provide you with a solution: discard 'plugin' approach. Instead modify your composer.json file so it looks as follows:
composer.json
{
    "name": "foo/bar",
    "type": "library",
    "autoload": {
        "psr-4": {
            "Foo\\Bar\\": "src/"
        }
    },
    "require": {
    },

    "scripts": {
        "post-install-cmd": [
            "Foo\\Bar\\Composer\\Plugin::postInstall"
        ],
        "post-update-cmd": [
            "Foo\\Bar\\Composer\\Plugin::postUpdate"
        ]
    }

}

Additionally, in src/Composer folder create Plugin.php:
src/Composer/Plugin.php
<?php

namespace Foo\Bar\Composer;

use Foo\Bar\Test;

/**
 * Composer scripts.
 */
class Plugin
{
    public static function postInstall()
    {
        print_r("POST INSTALL\n");
        print_r(Test::TEST_CONST);
        print_r("\n");
    }

    public static function postUpdate()
    {
        print_r("POST UPDATE\n");
        print_r(Test::TEST_CONST);
        print_r("\n");
    }
}

As you see, it prints constant from Test class. Create it in src/:
src/Test.php
<?php

namespace Foo\Bar;

/**
 * Test class.
 */
class Test
{
    const TEST_CONST = "HERE I AM";
}

Run this and check, how it plays out.


text:
Q: kerastuner tune hyperparameter that selects a subset of input features I have a toy problem, where I have some data (X,Y) where the labels Y are frequencies, and X are cosine functions with frequency Y: X=cos(Y*t+phi)+N, where t is a time vector, phi is some random phase shift and N is additive noise. I am developing a CNN in keras (tensorflow backend) to learn Y from X. However, I don't know how long my time window needs to be. So, I would like to use keras-tuner to help identify the best hyperparameters (winStart,winSpan) to determine which times to select t[winStart:winSpan].
It is unclear if/how I can slice my learning features X using tuned hyperparameters.
First, I defined my data as:
# given sine waves X, estimate frequencies Y
t=np.linspace(0,1,1000)
Y=np.divide(2*np.pi,(np.random.random((100))+1))
X=np.transpose(np.cos(np.expand_dims(t, axis=1)*np.expand_dims(Y,axis=0)+np.ones((t.size,1))*np.random.normal(loc=0,scale=np.pi,size=(1,Y.size)))+np.random.normal(loc=0,scale=.1,size=(t.size,Y.size)))
Y=np.expand_dims(Y,axis=1)

Following tutorials, I have written a function to construct my CNN model:
def build_model(inputSize):
    model = Sequential()

    model.add(Conv1D(10,
              kernel_size=(15,),
              padding='same',
              activation='ReLU',
              batch_input_shape=(None,inputSize,1)))

    model.add(MaxPool1D(pool_size=(2,)))
    model.add(Dropout(.2))

    model.add(Conv1D(10,
              kernel_size=(15,),
              padding='same',
              activation='ReLU',
              batch_input_shape=(None,model.layers[-1].output_shape[1],1)))

    model.add(MaxPool1D(pool_size=(2,)))
    model.add(Dropout(.2))

    model.add(Flatten())

    # add a dense layer
    model.add(Dense(10))
    model.add(Dense(1))

    model.compile(loss='mean_squared_error',
                  optimizer='adam')

    return model

Additionally, I have written a hypermodel class:
class myHypermodel(HyperModel):
    def __init__(self,inputSize):
        self.inputSize=inputSize

    def build_hp_model(self,hp):
        inputSize=1000

        self.winStart=hp.Int('winStart',min_value=0,max_value=inputSize-100,step=100)
        self.winSpan=hp.Int('fMax',min_value=100,max_value=inputSize,step=100)

        return build_model(self.winSpan)
    def run_trial(self, trial, x,y,*args, **kwargs):

        hp=trial.hyperparameters

        # build the model with the current hyperparameters
        model=self.build_hp_model(hp)

        # Window the feature vectors
        x=x[:,self.winStart:np.min([self.winStart+self.winSpan,self.inputSize])]

        print('here')
        return model.fit(x,y,*args,**kwargs)

Here, the build_hp_model() method is intended to link the hyperparameters to internal variables so that they can be used during when run_trial() method is called. My understanding is that run_trial() will be called by tuner.search() when performing hyperparameter optimization. I expect the run_trial() method to pick a new combination of winStart and winSpan hyperparameters, rebuild the model, remove all values of x except in the window defined by winStart and winSpan, and then run model.fit().
I call my hypermodel class and attempt to perform the hyperparameter search using:
tuner_model=myHypermodel(X.shape[1])

tuner = kt.Hyperband(tuner_model.build_hp_model,
                    overwrite=True,
                    objective='val_loss',
                    max_epochs=25,
                    factor=3,
                    hyperband_iterations=3)

tuner.search(x=np.expand_dims(X,axis=2),
             y=np.expand_dims(Y,axis=2),
             epochs=9,
             validation_split=0.25)

When I run the script, I get the error:
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 100, 1), found shape=(None, 1000, 1)
So it seems like the build_model() function is being called for a hyperparameter winSpan=100, but then the model is being fit using the full feature vectors X instead of X[:,winStart:winStart+winSpan].
Any suggestions on how I can properly implement this tuning?


text:
Q: kendo chart export pdf using angular I have kendo scatter line chart using angular. I am trying to add export to pdf but getting error as exportpdf is not a function. Has anyone tried kendo chart exportpdf using angularjs? Here's the example
http://dojo.telerik.com/uMube/8

A: Hope this help you: Instead of var chart = $scope.chartOptions; use var chart = $("#chart").getKendoChart();.
Here is the code
Greetings

A: Put a name into declarative code:
<div kendo-chart="michar"...

and in your controller put:
var chart = $scope.michar


text:
Q: apply css to after element last child I have a requirement where I need to remove the last border of an element, but the border is applied using the after element.
My code :

Hello

Hello

Hello

.abc::after {
  content: "";
  border-bottom: 1px solid #e1e1e1;
  display: block;
  margin-top: 32px;
}

I've tried removing the border for after element using the below code, but not working.
.abc:after:not([style*="display: none"]):last-child {
  border-bottom: none;
}

Is this possible using this approach? JSFiddle

A: Try this
.abc:last-child:after{
  border-bottom:none;
}

A: The problem with the selector you're using is that it's invalid, according to the specifications for pseudo-elements:

Only one pseudo-element may appear per selector, and if present it must appear after the sequence of simple selectors that represents the subjects of the selector.
  https://drafts.csswg.org/selectors-3/#pseudo-elements

Therefore your selector is invalid; and should instead be:
.abc:after:not([style*="display: none"]):last-child

Instead, because you're styling the pseudo-element for the :last-child element, you should use:
.abc:last-child::after

.abc::after {
  content: "";
  border-bottom: 1px solid #e1e1e1;
  display: block;
  margin-top: 32px;
}

.abc:last-child::after {
  border-bottom: none;
}

Hello

Hello

Hello

A:

.abc::after {
  content: "";
  border-bottom: 1px solid #e1e1e1;
  display: block;
  margin-top: 32px;
}

.abc:last-child::after {
  border-bottom: none;
}

Hello

Hello

Hello

A: Also you can try this, if you don't go with after then:
.abc{
  content: "";
  border-bottom: 1px solid #e1e1e1;
  display: block;
  margin-top: 32px;
}

.abc:last-child {
  border-bottom: 0px;
}


text:
Q: How to make "this" not refer to the element an event was called on? I know that there are no classes in Javascript, I refer to constructor functions as to classes for convenience.
I'm making a class called InputHandler in Javascript. It has a method called onMouseDown, and it registers it as an event handler like this:
Irenic.InputHandler.prototype.attach = function()
{
    var inputHandler = this; //Get the instance of InputHandler

    document.addEventListener("keydown", inputHandler.onKeyDown, false); //Concentrate on this, but the question applies to all of these.
    document.addEventListener("keyup", inputHandler.onKeyUp, false);
    document.addEventListener("mousemove", inputHandler.onMouseMove, false);
    document.addEventListener("mouseup", inputHandler.onMouseUp, false);
    document.addEventListener("mousedown", inputHandler.onMouseDown, false);
}

(Irenic is the name of the engine I'm building, it is also a global object which has all these classes.)
The inputHandler.onMouseDown method looks like this:
Irenic.InputHandler.prototype.onMouseDown = function(event)
{
    var inputHandler = this; //This sadly refers to the document, not an instance of InputHandler
console.log(inputHandler); //Logs #document

if (event.button == 0)
{
    inputHandler.mouse.lmb = true;
}

if (event.button == 1)
{
    inputHandler.mouse.wheel = true;
}

if (event.button == 2)
{
    inputHandler.mouse.rmb = true;
}

}
As I've said in the comments, the this keyword refers to the element the event fired on. I obviously don't want that: so how do I make it refer to an instance of InputLoader?

A: Use Function.prototype.bind to lock the context of a function:
inputHandler.onKeyDown.bind(inputHandler)

PS. use switch, or at least else if instead of multiple if constructs. Only one of them can be true.

A: In your constructor, bind the instance's methods to that instance:
function InputHandler() {
    this.onKeyDown = this.onKeyDown.bind(this);
    this.onKeyUp = this.onKeyUp.bind(this);
    this.onMouseMove = this.onMouseMove.bind(this);
    this.onMouseUp = this.onMouseUp.bind(this);
    this.onMouseDown = this.onMouseDown.bind(this);
}

This way the instance is ready to go as soon as it is constructed.
See Function#bind

A: I believe bind doesn't work with IE <= 8, so if this is required this should work:
document.addEventListener("keydown", function (ev) { return inputHandler.onKeyDown(ev); }, false)


text:
Q: Angle between two complex vectors I'm trying to find the angle between $p = 2-2i$ and $q = 1-i\sqrt(3)$. I already got the answer as $\frac{\pi}{12}$ by subtracting the angles of $p$ and $q$ ($\frac{\pi}{3}-\frac{\pi}{4}$). I am trying to do the same using dot product, but Im not sure how to go about it.

A: Here is how to find the angle with the vector dot product. The two vectors are,
$$\vec{p}=(2,-2),\>\>\>\>\>\vec{q}=(1,-\sqrt 3)$$
Their dot product is
$$\vec{p}\cdot\vec{q} = pq\cos\theta$$
Then, $\cos\theta$ can be computed as below,
$$\cos\theta = \frac{\vec{p}\cdot\vec{q}}{pq}
=\frac{2+2\sqrt 3}{\sqrt 8 \sqrt 4}=\frac{1+\sqrt 3}{2\sqrt 2}=\cos 15^\circ$$
Thus,
$$\theta =15^\circ$$

A: These are not complex vectors. They're still really since all the components are real. You may write each of them as $(2,-2),\,(1,-\sqrt 3).$ Then their dot product is $(2)(1)+(-2)(-\sqrt 3)=2+2\sqrt 3.$
Recall that for two vectors $a,b$ with an angular separation of $\phi,$ we have that $a\cdot b=|a||b|\cos\phi.$ Can you now continue?


text:
Q: How to i get my Array to output its random generated values from 0 - 99 I wanted to make a function called fillArray to set up random values to the Array.
Then i wanted the function to output all the values but i kept getting values way above 99.
This is what i have written so far:
#include <ctime>
#include <iostream>

using namespace std;

void fillArray(){
    srand(time(NULL));

    const unsigned int sizeOfArray = 10; // this sets the array to the constant size of 10
    int numberArray[sizeOfArray];  //this sets the array to the size of 'sizeOfArray' which is 10

    for(int i = 0; i < sizeOfArray; i++)
    {
      numberArray[i] = rand() % 100;
      cout << numberArray[i] << endl;
    }
}

int main (){
    void fillArray(int a[10], int randNum);
    cout << numberArray[0] << " , " << numberArray[1] << " , " << numberArray[2] << " , " << numberArray[3] << " , " << numberArray[4] << " , " << numberArray[5] << " , " << numberArray[6] << " , " << numberArray[7] << " , " << numberArray[8] << " , " << numberArray[9] << '\n';

}

I understand the name numberArray hasnt been declared in the main function but just wondered what to do.

A: The fillArray() function is not being called. You declared fillArray as -
void fillArray(). But when you call fillArray it is called as -
fillArray(int a[10], int randNum). This line does not call the function declared earlier as the number of parameters is different. The original fillArray() function does not accept any parameters but it is called with two. Moreover, we never write the return type when we call a function. Call the function as fillArray() and it will work.
Remember that the function call and the function declaration should be exactly same.
Regarding the not declared in scope problem, your array is declared in the fillArray function and thus not accessible in the main method. To solve this either make your array global and declare it outside the function after the namespace line or just don't use it in the main function. Just call fillArray() from the main method and it will populate and print the array for you.

A: So, your error is simple:
You have declared a function in the main function like this:
int main()
{
  void fillArray(int a[10], int random);
}

But it should have been
int main()
{
  fillArray(int a[10], int random);
}

Which is calling the fillArray function
Also there are a few other things that i would like to add,
instead of fillArray taking nothing it should take an array like this
  template<auto Size>
  void fillArray(int (&arr)[Size])
  {
    // Implemenatation
  }

and also, it should not take a random number the function can do that in the function body.
When you are printing your array, you should use a loop or a specialized function to do it like this:
template<auto Size>
auto PrintArray(int (&arr)[Size])
{
  for(int i = 0; i < Size; i++)
  {
    std::cout << arr[i] << ", ";
  }
  std::cout << "\n";
}

So, your final code would be something like the following:
#include <ctime>
#include <iostream>

using namespace std;

template<auto Size>
void fillArray(int (&numberArray)[Size]){
    srand(time(NULL));

    for(int i = 0; i < Size; i++)
    {
      numberArray[i] = rand() % 100;
    }
}

template<auto Size>
auto PrintArray(int (&arr)[Size])
{
  for(int i = 0; i < Size; i++)
  {
    std::cout << arr[i] << ", ";
  }
  std::cout << "\n";
}

int main (){
    int numberArray[10];
    void fillArray<10>(numberArray);
    PrintArray<10>(numberArray);

}


text:
Q: What is the 302 error code that jQuery AJAX is throwing? I'm working with ASP.NET MVC and jQuery and I have a UserControl that is repeated on every page. In every page request, an AJAX callback occurs. So far so good.
But when I'm in localhost and I publish the site, I notice that this AJAX is throwing a 302 error. This only occurs on https pages, and only in FF and Chrome. On IE, the AJAX request works fine.
What is this 302 error? Why does it only occur on https pages, and only in FF and Chrome?

A: See
How to manage a redirect request after a jQuery Ajax call for an in-depth discussion about the 302 issue.
EDIT:
Here are some other stackoverflow posts on the subject.
How to get jQuery.ajax response status?
Catching 302 FOUND in JavaScript
HTTP redirect: 301 (permanent) vs. 302 (temporary)

A: HTTP 302 is used for redirection. My guess is that there is some sort of server error and you are being redirected to an error page using 302. Check the server logs for errors.

A: HTTP code 302 represents a redirection. The server is trying to tell you to redirect somewhere.
http://en.wikipedia.org/wiki/HTTP_302

A: Does the server you accessing has Page Redirection facility? and that the page you access by Ajax was redirected to another page? If that is the case, you'd disable the redirection(at least ignore redirection for that page) then give it a try.
PS: I think Ajax may not support url redirection.


text:
Q: Problem deserializing Google profile response I'm authenticating to google in a Xamarin.Forms app. Once authenticated I want to retrieve user email, and use this code that I adapted from this blog, the code for retrieving the email:
public class GoogleProfile
{
    [Preserve]
    [JsonConstructor]
    public GoogleProfile() { }

    public string sub { get; set; }
    public string name { get; set; }
    public string given_name { get; set; }
    public string profile { get; set; }
    public string picture { get; set; }
    public string email { get; set; }
    public string email_verified { get; set; }
    public string locale { get; set; }
}

public class GoogleService
{
    public async Task<string> GetEmailAsync(string tokenType, string accessToken)
    {
        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
        var json = await httpClient.GetStringAsync("https://www.googleapis.com/oauth2/v3/userinfo");//https://www.googleapis.com/userinfo/email?alt=json");
        var profile = JsonConvert.DeserializeObject<GoogleProfile>(json);
        return profile.email;
    }
}

Now, with a breakpoint in the last line return profile.email I've "seen" the json file that is this way:
{
  "sub": "",
  "name": "",
  "given_name": "",
  "profile": "",
  "picture": "",
  "email": "",
  "email_verified": "",
  "locale": "",
}

Between the quotes are the data, obviously.
I'm not really accustomed to JSon but reading this I thought that the format is simply "nameOfProperty":"ValueOfProperty", so I made GoogleProfile object.
I read too that the attributes [Preserve] and [JsonConstructor] are necessary so the linker doesn't just "remove" empty constructors when compiling.
There are no exceptions and no apparent problems, but if I put a breakpoint in the last return profile.email; line, I can see the json object has all the data and is perfectly fine, but the profile object have only the email property with value null...
I don't understand it: what happened with the other properties? Is it even possible? You know, you code an object with a bunch of properties but the object are created with only one of those properties? If the object had all the properties with a value of null, Ok, but where did the other properties gone?
Just to be sure, I've cleaned and rebuild projects and solution, I've removed bin and obj folders and then clean and rebuild again... I've done the obvious things.
Thing is that as you can see in the blog I mentioned earlier, first I didn't use GoogleProfile object, I just copied the object in the blog... that has only one property called email. Is it possible that visual studio or xamarin or something got bugged and the changes didn't got reflected? I doubt it because I've changed the URI used in the GetStringAsync method and it did got reflected, but well, I don't know.
PD: In the meanwhile I'm parsing the JSON directly as a normal string, it's a simple object and I only really need the email, but well, it would be a shame that I'd have to parse it that way instead of just deserialize it.

Edit:
As suggested by Skin in the comments I've used http://jsonutils.com/
One of the properties was a bool (of course), so I've changed it and the object now is:
public class GoogleProfile
{
    [Preserve]
    [JsonConstructor]
    public GoogleProfile() { }

    public string sub { get; set; }
    public string name { get; set; }
    public string given_name { get; set; }
    public string profile { get; set; }
    public string picture { get; set; }
    public string email { get; set; }
    public bool email_verified { get; set; }
    public string locale { get; set; }
}

But it didn't change the result, still happening the same. Image of the result at the breakpoint:

A: I don't think there is any problem with your code. I used the same code of you and didn't change anything. I use my own tokenType and accessToken.
My steps:

*

*copy your code to my project.

*get my own token by using the project in the blog

*install newtonsoft Nuget package

*run the project and get result

So, is there any problem with your account? Did you account have an e-mail? Any difference with mine?
Here is what I get:

Code:
public partial class MainPage : ContentPage
{
    public MainPage()
    {

        InitializeComponent();

        testAsync();
    }

    public async Task testAsync()
    {

        GoogleService googleS = new GoogleService();
        // use your token here
        var email = await googleS.GetEmailAsync("", "");
        Console.WriteLine(email);
    }

    public class GoogleProfile
    {
        [Preserve]
        [JsonConstructor]
        public GoogleProfile() { }

        public string sub { get; set; }
        public string name { get; set; }
        public string given_name { get; set; }
        public string profile { get; set; }
        public string picture { get; set; }
        public string email { get; set; }
        public string email_verified { get; set; }
        public string locale { get; set; }
    }

    public class GoogleService
    {
        public async Task<string> GetEmailAsync(string tokenType, string accessToken)
        {
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var json = await httpClient.GetStringAsync("https://www.googleapis.com/oauth2/v3/userinfo");//https://www.googleapis.com/userinfo/email?alt=json");
            var profile = JsonConvert.DeserializeObject<GoogleProfile>(json);

            Console.WriteLine(json);
            Console.WriteLine(profile);

            return profile.email;
        }
    }
}


text:
Q: Keras Generator Output vs Direct File Read Produced Drastically Different Model Results In TensorFlow Keras, I have created a generator to feed a model .fit() function in order to supply the contents of a file. I don't get any errors but the model generated is nonsensical if it is fed from the generator while the model is correct when fed the file more directly.
The model is fed a file containing input rows as follows:
0.1,0.2,0.0,0.4,0.0
...

and another file containing output rows as follows:
0.5,0.4,0.7,0.2,0.6
...

in order to create a multi-input to multi-output mapping function.
Any suggestions on how the generator is incorrectly creating the required data?
The code is the following and the use of the generator or direct file read is controlled by the 'is_multifile' variable:
#!/usr/bin/python3

# mlp for multi-output regression
import math
import numpy as np
import pandas as pd
import random
import tensorflow as tf
from numpy import mean
from numpy import std
from tensorflow import keras
from tensorflow.keras import layers

# get the dataset
def get_dataset_from_file():
        X = pd.read_csv("/home/learning/training/Output_00.csv")
        Y = pd.read_csv("/home/learning/training/Input_00.csv")
        return ( X.values,Y.values )

# get the dataset in pieces
def get_dataset_from_files( epoch_count, batch_size ):
        for e in range(0,epoch_count):
                print( "Epoch: "+str(e)+"/"+str(epoch_count) )
                for id in range(0,1):
                        if (id<10):
                                id_text = "0"+str(id)
                        else:
                                id_text = str(id)
                        X = pd.read_csv("/home/learning/training/Output_"+id_text+".csv")
                        Y = pd.read_csv("/home/learning/training/Output_"+id_text+".csv")
                        X_values = X.to_numpy()
                        Y_values = Y.to_numpy()
                        length = math.ceil(len(X_values)/batch_size)
                        X_split = np.array_split( X_values, length )
                        Y_split = np.array_split( Y_values, length )
                        for i in range(0,length):
                                yield( X_split[ i ], Y_split[ i ] )

# get the model
def get_model( node_count, layer_count, input_count, output_count, optimizer ):
        model = keras.Sequential()
        for i in range(0,layer_count):
                model.add( layers.Dense( int(node_count/layer_count), input_dim=input_count, kernel_initializer='he_uniform', activation='relu' ) )
        model.add(layers.Dense( output_count ))
        model.compile(loss='mae', optimizer=optimizer)
        return model

# Configuration
is_multifile=False
batch_size=32
epoch_count=1
optimizer='adam'
node_count=80
layer_count=2
steps_per_epoch=54988

X,Y = get_dataset_from_file()
input_count,output_count = X.shape[1],Y.shape[1]
model = get_model( node_count, layer_count, input_count, output_count, optimizer )

if (is_multifile):
        loss_history = model.fit( get_dataset_from_files( epoch_count, batch_size ), verbose=1, epochs=epoch_count, batch_size=batch_size, steps_per_epoch=steps_per_epoch )
else:
        loss_history = model.fit( X, Y, verbose=1, epochs=epoch_count, batch_size=batch_size )
loss_detail = loss_history.history['loss']
loss_text = "{:1.4f}".format( sum(loss_detail)/len(loss_detail) )

model.save( '/home/learning/model/model_'+str(layer_count)+"x"+str(int(node_count/layer_count))+'node_'+optimizer+"_"+loss_text+"loss" )


text:
Q: How to create a django app that lets you type in small python programs, execute the code and show the result? The app should enable the user to type in small python programs.When click Run the code is executed and output is delivered to the user

A: You can use Sphere Engine as a compiler and execute any code submitted from client side it supports more than 60 Languages and have very good sets of Api which are very easy to Integrate with any website. Ideone ,Codechef and many more are using it. you can try it


text:
Q: Access to fetch has been blocked by CORS policy at Firebase Functions API I'm working on my project which includes Angular 9 application using firebase functions. I deployed some function, which should update some values on the Firebase Realtime Database. Unfortunately, I encountered a problem with CORS policy if I use my API.
After adding middleware to my express server, where I added these code, the problem still occurs.
app.post('/changeQuantity', permit(), (request: any, response: any) => {
   response.status(200).send({ data: { Message: 'Changing order quantity - success.' } });
})

export default function permit() {
    return (req: any, _res: any, next: any) => {
        _res.setHeader('Access-Control-Allow-Origin', '*');
        _res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
        next();
    };
}

I noticed, that I get this error when frequently requesting API.
Here is the error which server returns:

Access to fetch at [here is a link to my API endpoint] from origin [my origin] has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Did anybody have the same issues with the firebase functions API? Could it be related to frequent requests of my API endpoints from the development environment? Thanks in advance.

A: Try using response.header to set the CORS properties, like this
app.use((request, response, next) => {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    next();
});


text:
Q: How comparator and PriorityQueue in Java works? This is the code i used to reverse the normal working of priorityQueue in Java.
But i don't understand what is done by the lambda function i have put inside the parantheses. Can somedy explain that.
PriorityQueue pq = new PriorityQueue<>((a,b) -> b - a);
import java.util.*;
public class Main
{
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> b - a);

        pq.add(2);
        pq.add(4);
        pq.add(1);
        pq.add(100);

        System.out.println(pq);
        System.out.println(pq.remove());
        System.out.println(pq.remove());
        System.out.println(pq.remove());
        System.out.println(pq.remove());

    }
}

A: The comparison function is a function that must return any value less than 0 when the first parameter should be ordered before the second, any value greater than 0 when the second parameter should be ordered before the first and 0 if the two are equivalent for ordering.
It is used in within the PriorityQueue internally to determine relative ordering of elements by comparing its result with 0.


text:
Q: AngularJS/Cordova: How can I get values in my factory after deviceready? I am trying to use the Cordova Device plugin to get info about the device the user is using. The docs say it can only be called AFTER the deviceready function, so in my .run function I have the following:
.run(function($rootScope, $state, $stateParams) {

    document.addEventListener('deviceready', onDeviceReady, false);

    function onDeviceReady() {
        console.log(device);
    }

 //more functions below

This is working great, I see the device object in the console, however what I really want is to use the device object inside a factory that will sometimes get called BEFORE the deviceready event.
So my question is how can I get make device object available to my factory when it becomes available? I want something like the below code
angular.module('myapp.services.myFactory', [])

.factory('MyFactory', function($q) {

    function getDevice () {
        //if the deviceready event happend and I can access the device object set to variable
        return device;
    }

    return {
        getDeviceInfo: function getDeviceInfo() {
            return $q(function(resolve, reject) {
                if (getDevice()) {
                    //do something with the device object
                } else {
                   //do something without device object
                }
            });
        }
    };
});

A: No need to leverage .run here - you should be able to execute everything inside deviceready including your module and factory definitions. Just wrap everything in with this event. I also don't believe you need $q to resolve any promises either. Observe the following simplified pattern...
function onDeviceReady() {
    // guessing your dependency architecture
    angular
        .module('myapp', ['myapp.services'])
        .module('myapp.services', ['myapp.services.myFactory'])
        .module('myapp.services.myFactory', [])
        .factory('MyFactory', function() {

            function withDevice() {
                /*...*/
            }

            function withoutDevice() {
                /*...*/
            }

            return {
                // turnary. device always available to examine at this point
                'getDeviceInfo': device ? withDevice : withoutDevice
            }
        });
}

document.addEventListener('deviceready', onDeviceReady, false);


text:
Q: How to submit OpenSaml response? I'm building a org.opensaml.saml.saml2.core.Response with openSAML v3.2.0. I've the signed the response and would like to submit it.
I tried following openSAML book (A Guide to OpenSAML v3) but it doesn't seem to be of help with my scenario. I have a c# demo project with basically submits the response by HTTPPost. I'm writing the same in java with opensaml. Do I have to build an artifact as the book suggest? The book example suggests that I send the ArtifactResolve using SOAP even though I'm building a Response.
With the response object above, I'd like to post the response object to an idp.
What is the best way to achieve this?
 - Is it a good idea to create an Envelope object? With the response object from the saml2 package, how can I create a org.opensaml.soap.soap11.Envelope?
Any help is much appreciated! Thanks!

A: You don't have to build artifact as the book suggests.
Using Artifacts has some security, privacy, and other benefits.
Look Scott T. answer to understand the benefits of using Artifact binding - https://stackoverflow.com/a/13618537/1163424
Per your question,
You can also pass the Response to the SP using POST binding.
The way to do that is to encode your Response XML (With the signned Assertion) into Base64 string and make the client web-app POST it to the SP ACS (Assertion Consumer Service).
You pass SAMLResponse parameter with base64 string as value and a RelayState parameter which will be used to set the state in the SP web-app, As written in the SAML 2 Bindings specification page 21.
Also, I suggest using the SAML tool to validate your Response message.


text:
Q: iPhone XR returns correct nativeBounds but has wrong screen size on device My project target iOS - 11 and later. It has correct Launch images assets for XR and XS Max with appropriate dimensions. On simulator my app works as expected on both XR and XS Max.
But, users reported UI issues on real devices. After some research it looks like on real device this
[UIScreen mainScreen].nativeBounds.size

returns correct values. But seems like device itself think that it has iPhone X screen size (like when i do not use correct launch screen images). And in my opinion it returns wrong values with
[UIScreen mainScreen].bounds.size

this one i believe returns values like it's not iPhone XR but iPhone X.
Did someone face such an issue too?

A: The iPhone XR does not use the same size in (virtual) points than the iPhone X or iPhone XS does. It uses the same point dimensions like the new iPhone XS Max, but is rendered only with @2x instead of @3x, like the Max does (lower pixel per inch density). You can read more about screen sizes, points, rendered dimensions etc. for each iPhone model here.
The missing templates for launch images in XCAssets also affect the new generation of iPads, as e.g. the new iPad Pro 11" slightly differs from the standard 3/4 aspect ratio, the other iPads have. Diving deeper into the missing templates issue brought me to this radar post from 2015 about missing iPad Pro App Icon and Launch Image templates, where the comment states:
[...] and Developer relations reported in a radar comment that they no longer support launch images and will not be adding the iPad pro launch image size to asset catalogs.
It seems like Apple is discouraging the use of launch images inside XCAssets and proposes to use Launch Screen.storyboard instead. It will "auto-size" to the correct dimensions (and respectively the outputs of UIScreen.main.bounds and UIScreen.main.nativeBounds) depending on the used device or simulator.

A: In my case the trouble was in the specific user device settings.
Settings -> Display & brightness -> Display zoom switch to ON.
This cause to return wrong
[UIScreen mainScreen].bounds.size

values runtime

A: I faced the same question, and I found the reason. You could check the LaunchImage in the assets. Is there an image for the iPhone XR. If you don't have the iPhone XR LaunchImage, the screen size of XR will compute with the the iPhone X. So make a LaunchImage for XR.
Hope this helps.


text:
Q: getting java.lang.ClassNotFoundException: com.install4j.script.I4jScript_Internal_36 while updationg install4j on linux machine Currently I am using version 6.1.5 of install4j on Linux. When i am checking for updates, I am getting following error:
Exception:
java.lang.ClassNotFoundException: com.install4j.script.I4jScript_Internal_36
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at com.install4j.runtime.installer.helper.Install4jClassLoader.loadClass(Install4jClassLoader.java:81)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.install4j.runtime.installer.ContextImpl.runScript(ContextImpl.java:187)
    at com.install4j.runtime.installer.ContextImpl.runScript(ContextImpl.java:182)
    at com.install4j.runtime.installer.ContextImpl.checkGroupCondition(ContextImpl.java:197)
    at com.install4j.runtime.installer.controller.ScreenNavigator.forward(ScreenNavigator.java:154)
    at com.install4j.runtime.installer.controller.ScreenNavigator.findNextScreenConfig(ScreenNavigator.java:60)
    at com.install4j.runtime.installer.controller.Controller.handleCommand(Controller.java:213)
    at com.install4j.runtime.installer.controller.Controller.start(Controller.java:94)
    at com.install4j.runtime.installer.Application.runApplication(Application.java:71)
    at com.install4j.runtime.installer.Application.main(Application.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.exe4j.runtime.LauncherEngine.launch(LauncherEngine.java:65)
    at com.install4j.runtime.launcher.UnixLauncher.main(UnixLauncher.java:57)

A: This compiled script class is contained in the JAR file .install4j\user.jar. From your error message, it would seem that that JAR file has been deleted or replaced with a version that is not compatible with the contents of .install4j\i4jparams.conf.

A: One reason can be that the .jar file is excluded from your build path.
To make sure that's not the case and to correct that, go in install4j:

*

*"Files" (in the left selection bar)

*"Define distribution tree"

*"Content of [your distribution tree]"

*"Excluded files and directories"

*you will see a list of files. The excluded ones are checked. Make sure that the .jar file is unchecked.

image of these five steps


text:
Q: jQuery mobile adds additional scrollbar to page I'm currently working with jQuery mobile (for the first time).
One of my pages contains a very long text. If I view this page on a desktop browser, jquery will add scroll-bar to the page (additional to the one of the browser).
How can I remove the second scroll bar?

<title>Header</title>
<meta name="viewport" id="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
...

        Back

Information

        Refresh

Information

              ....

...large text goes here....

Status

Info

Sorry... I have completely forgotten the code.

A: I had a double scrollbar when I was using a panel.  I had to switch my CSS references from this:
<link rel="stylesheet" href="jquery.mobile.structure-1.3.2.css">
<link rel="stylesheet" href="jquery.mobile.theme-1.3.2.css">

to this:
<link rel="stylesheet" href="jquery.mobile-1.3.2.css">

Otherwise try removing every div from your page and add them back one by one until you see which one is causing the second scroll bar.


text:
Q: Converting from Option to Option<&str> Very often I have obtained an Option<String> from a calculation, and I would like to either use this value or a default hardcoded value.
This would be trivial with an integer:
let opt: Option<i32> = Some(3);
let value = opt.unwrap_or(0); // 0 being the default

But with a String and a &str, the compiler complains about mismatched types:
let opt: Option<String> = Some("some value".to_owned());
let value = opt.unwrap_or("default string");

The exact error here is:
error[E0308]: mismatched types
 --> src/main.rs:4:31
  |
4 |     let value = opt.unwrap_or("default string");
  |                               ^^^^^^^^^^^^^^^^
  |                               |
  |                               expected struct `std::string::String`, found reference
  |                               help: try using a conversion method: `"default string".to_string()`
  |
  = note: expected type `std::string::String`
             found type `&'static str`

One option is to convert the string slice into an owned String, as suggested by rustc:
let value = opt.unwrap_or("default string".to_string());

But this causes an allocation, which is undesirable when I want to immediately convert the result back to a string slice, as in this call to Regex::new():
let rx: Regex = Regex::new(&opt.unwrap_or("default string".to_string()));

I would rather convert the Option<String> to an Option<&str> to avoid this allocation.
What is the idiomatic way to write this?

A: You can use as_ref() and map() to transform an Option<String> into an Option<&str>.
fn main() {
    let opt: Option<String> = Some("some value".to_owned());
    let value = opt.as_ref().map(|x| &**x).unwrap_or("default string");
}

First, as_ref() implicitly takes a reference on opt, giving an &Option<String> (because as_ref() takes &self, i.e. it receives a reference), and turns it into an Option<&String>. Then we use map to convert it to an Option<&str>. Here's what &**x does: the rightmost * (which is evaluated first) simply dereferences the &String, giving a String lvalue. Then, the leftmost * actually invokes the Deref trait, because String implements Deref<Target=str>, giving us a str lvalue. Finally, the & takes the address of the str lvalue, giving us a &str.
You can simplify this a bit further by using map_or to combine map and unwrap_or in a single operation:
fn main() {
    let opt: Option<String> = Some("some value".to_owned());
    let value = opt.as_ref().map_or("default string", |x| &**x);
}

If &**x looks too magical to you, you can write String::as_str instead:
fn main() {
    let opt: Option<String> = Some("some value".to_owned());
    let value = opt.as_ref().map_or("default string", String::as_str);
}

or String::as_ref (from the AsRef trait, which is in the prelude):
fn main() {
    let opt: Option<String> = Some("some value".to_owned());
    let value = opt.as_ref().map_or("default string", String::as_ref);
}

or String::deref (though you need to import the Deref trait too):
use std::ops::Deref;

fn main() {
    let opt: Option<String> = Some("some value".to_owned());
    let value = opt.as_ref().map_or("default string", String::deref);
}

For either of these to work, you need to keep an owner for the Option<String> as long as the Option<&str> or unwrapped &str needs to remain available. If that's too complicated, you could use Cow.
use std::borrow::Cow::{Borrowed, Owned};

fn main() {
    let opt: Option<String> = Some("some value".to_owned());
    let value = opt.map_or(Borrowed("default string"), |x| Owned(x));
}

A: A nicer way could be to implement this generically for T: Deref:
use std::ops::Deref;

trait OptionDeref<T: Deref> {
    fn as_deref(&self) -> Option<&T::Target>;
}

impl<T: Deref> OptionDeref<T> for Option<T> {
    fn as_deref(&self) -> Option<&T::Target> {
        self.as_ref().map(Deref::deref)
    }
}

which effectively generalizes as_ref.

A: As of Rust 1.40, the standard library has Option::as_deref to do this:
fn main() {
    let opt: Option<String> = Some("some value".to_owned());
    let value = opt.as_deref().unwrap_or("default string");
}

See also:

*

*How can I iterate on an Option<Vec<_>>?

A: Although I love Veedrac's answer (I used it), if you need it at just one point and you would like something that is expressive you can use as_ref(), map and String::as_str chain:
let opt: Option<String> = Some("some value".to_string());

assert_eq!(Some("some value"), opt.as_ref().map(String::as_str));

A: Here's one way you can do it. Keep in mind that you have to keep the original String around, otherwise what would the &str be a slice into?
let opt = Some(String::from("test")); // kept around

let unwrapped: &str = match opt.as_ref() {
  Some(s) => s, // deref coercion
  None => "default",
};

playpen


text:
Q: List shifts down on item placement I'm having a hard time fixing the following issue: one of my lists, #cardHolder, moves down whenever I drag an item in it.
I know it's CSS related, but I can't seem to fix it.
Any help is appreciated.

$(document).ready(function () {
    $( "#cardHolder, #hand" ).sortable({
      connectWith: ".connectedSortable",
      receive: function(event, ui) {
      var $this = $(this);
      if ($this.children('li').length > 1 && $this.attr('id') != "hand") {
      console.log('Only one per list!');
      $(ui.sender).sortable('cancel');
            }
      }

    }).disableSelection();
});
#trumpHolder{
    border: 5px solid #ccc;
    padding: 5px;
    height: 250px;
    width: 150px;
    margin-top: 5px;
    margin-bottom: 5px;
    margin-left: auto;
    margin-right: auto;

}
#holderWrapper{
    width: 100%;
    text-align: center;

}
#cardHolder {
    border: 5px solid #ccc;
    padding: 5px;
    height: 250px;
    width: 150px;
    margin: 5px 5px 5px 5px;
    display: inline-block;
}
#cardHolderOther{
    border: 5px solid #ccc;
    padding: 5px;
    height: 250px;
    width: 150px;
    display: inline-block;
    margin: 5px 5px 5px 5px;
}
.table{
    display: table;
    margin: 0 auto;

}
#hand {
    height: 250px;
    border: 5px solid #ccc;
    padding: 0;
    width: 100%;
    clear: both;
    margin-top: 5px;

}

#cardHolder li, #hand li {
    margin: 7px 7px 7px 7px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
    display: inline-block;
}

<link href="http://code.jquery.com/ui/1.8.24/themes/blitzer/jquery-ui.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" type="text/css" href="boerenbridge.css">

Item 1

Item 2

Item 3

Item 4

Item 5

Here is the code:
HTML
<!doctype html>

  <meta charset="utf-8">
  <title>Boerenbridge</title>

<link href="http://code.jquery.com/ui/1.8.24/themes/blitzer/jquery-ui.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" type="text/css" href="boerenbridge.css">

Item 1

Item 2

Item 3

Item 4

Item 5

CSS
#trumpHolder{
    border: 5px solid #ccc;
    padding: 5px;
    height: 250px;
    width: 150px;
    margin-top: 5px;
    margin-bottom: 5px;
    margin-left: auto;
    margin-right: auto;

}
#holderWrapper{
    width: 100%;
    text-align: center;

}
#cardHolder {
    border: 5px solid #ccc;
    padding: 5px;
    height: 250px;
    width: 150px;
    margin: 5px 5px 5px 5px;
    display: inline-block;
}
#cardHolderOther{
    border: 5px solid #ccc;
    padding: 5px;
    height: 250px;
    width: 150px;
    display: inline-block;
    margin: 5px 5px 5px 5px;
}
.table{
    display: table;
    margin: 0 auto;

}
#hand {
    height: 250px;
    border: 5px solid #ccc;
    padding: 0;
    width: 100%;
    clear: both;
    margin-top: 5px;

}

#cardHolder li, #hand li {
    margin: 7px 7px 7px 7px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
    display: inline-block;
}

Javascript/Jquery
$(document).ready(function () {
    $( "#cardHolder, #hand" ).sortable({
      connectWith: ".connectedSortable",
      receive: function(event, ui) {
      var $this = $(this);
      if ($this.children('li').length > 1 && $this.attr('id') != "hand") {
      console.log('Only one per list!');
      $(ui.sender).sortable('cancel');
            }
      }

    }).disableSelection();
});

A: Add vertical-align: top; to #cardHolder when using display: inline-block to make sure it sticks to the top, otherwise it will try to align it to its default value, baseline, see this link for more information on vertical-align and inline elements.
Below, on the left, is an example of vertical-align using the default baseline value, on the right is an example of it using the top value.

.inline-list {
  width: 250px;
  float: left;
}

.inline-list div {
  display: inline-block;
  border: 3px solid #444;
  margin: 0;
  padding: 0;
}

.inline-list .cardholder {
  width: 100px;
  height: 100px;
}

.inline-list.align .cardholder {
  vertical-align: top;
}

Some text

Some text

A: Just add to your css :
#cardHolder {
    vertical-align : top;
    ...

See the working example below !

$(document).ready(function () {
    $( "#cardHolder, #hand" ).sortable({
      connectWith: ".connectedSortable",
      receive: function(event, ui) {
      var $this = $(this);
      if ($this.children('li').length > 1 && $this.attr('id') != "hand") {
      console.log('Only one per list!');
      $(ui.sender).sortable('cancel');
            }
      }

    }).disableSelection();
});
#trumpHolder{
    border: 5px solid #ccc;
    padding: 5px;
    height: 250px;
    width: 150px;
    margin-top: 5px;
    margin-bottom: 5px;
    margin-left: auto;
    margin-right: auto;

}
#holderWrapper{
    width: 100%;
    text-align: center;

}
#cardHolder {

    vertical-align : top; /* <--------------- MODIFICATION */

    border: 5px solid #ccc;
    padding: 5px;
    height: 250px;
    width: 150px;
    margin: 5px 5px 5px 5px;
    display: inline-block;
}
#cardHolderOther{
    border: 5px solid #ccc;
    padding: 5px;
    height: 250px;
    width: 150px;
    display: inline-block;
    margin: 5px 5px 5px 5px;
}
.table{
    display: table;
    margin: 0 auto;

}
#hand {
    height: 250px;
    border: 5px solid #ccc;
    padding: 0;
    width: 100%;
    clear: both;
    margin-top: 5px;

}

#cardHolder li, #hand li {
    margin: 7px 7px 7px 7px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
    display: inline-block;
}

<link href="http://code.jquery.com/ui/1.8.24/themes/blitzer/jquery-ui.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" type="text/css" href="boerenbridge.css">

Item 1

Item 2

Item 3

Item 4

Item 5


text:
Q: Create customized S function blocks and also generate C code using real time workshop for the same I want to create customized S function blocks and also generate C code for them using real time workshop. I could not quite find the correct documents for this task. Could someone please help me by pointing to correct and easy documentation?

A: Assuming you have Simulink Coder (and its documentation) installed, then for a general discussion of how c-mex S-Functions are handled open the doc by doing
docsearch('Insert S-Function Code')

then click on the link that says 'Insert S-Function Code' -- which may not be the first link.
To see info on how to inline an S-Function using a .tlc file look at the following,
docsearch('Inlining C MEX S-Functions')


text:
Q: Can the std::vector range constructor invoke explicit conversions? Is the following program well-formed?
#include <vector>
struct A {
    explicit A(int) {}
};
int main() {
    std::vector<int> vi = {1, 2, 3, 4, 5};
    std::vector<A> va(vi.begin(), vi.end());
}

According to C++17 [sequence.reqmts], the requirement for
X u(i, j);

where X is a sequence container, is:

T shall be EmplaceConstructible into X from *i.

However, in the preceding paragraph it is stated that:

i and j denote iterators satisfying input iterator requirements and refer to elements implicitly convertible to value_type,

Thus it seems to me that both requirements would need to be met: the value type of the range must be implicitly convertible to the value type of the container, and EmplaceConstructible must be satisfied (which means the allocator must be able to perform the required initialization). Since int is not implicitly convertible to A, this program should be ill-formed.
However, surprisingly, it seems to compile under GCC.

A: It is only a requirement for sequence containers to support the construction from iterators that satisfy the criteria of implicit convertibility.
This does not by itself disallow sequence containers to from supporting that construction from iterators that don't satisfy that criteria as far as I can tell1. There is explicit rule about that:

If the constructor ... is called with a type InputIterator that does not qualify as an input iterator, then the constructor shall not participate in overload resolution.

It is unclear what "qualify as an input iterator" means exactly in the context. Is it informal way to express Cpp17InputIterator, or does it attempt to refer to requirements of i and j? I don't know. Whether it is allowed or not, standard doesn't have a strict requirement for detecting it:

[container.requirements.general]
The behavior of certain container member functions and deduction guides depends on whether types qualify as input iterators or allocators.
The extent to which an implementation determines that a type cannot be an input iterator is unspecified, except that as a minimum integral types shall not qualify as input iterators. ...

With the interpretation that any Cpp17InputIterator "qualifies as an input iterator", the example program would not be required to be ill-formed. But it is not guaranteed to be well-formed either.
1In such case, it might be considered a quality of implementation issue to warn when relying on it. On the other hand, this limitation to implicit conversions may be considered a defect.

P.S. This compiles without warnings in Clang (with libc++) and Msvc as well.
P.P.S. This wording seems to have been added in C++11 (which is natural, as then were explicit constructors also introduced).


text:
Q: Are there non-gradable adjectives for comparison? In the last week I asked here on ELL two questions:

*

*How can these two types of adjectives be distinguished terminologically?

*Why can "low" become "lower" and "lowest", while "up" can't?
The answer for the first question is "inflectionally gradable for comparison and analytically gradable for comparison".
The answer for the second question as I understood by reading all the answers there, is that the word "up" is not an adjective and therefore it should not be gradable. But when I see Cambridge dictionary we can see that there is an adjective which is called "up". In addition in the same dictionary the word "upper" is marked as adjective. (and the word "lower" is marked there as a opposite. unlike the most of the answers in the second post). So it confuses me because I'm not sure if the word "up" is gradable or no.
Then my question is: Are there adjectives that are non gradable at all?

A: Sure. For example wooden in wooden spoon.
You can't (at least ordinarily) have a woodener or woodenest spoon.
We can say He divorced her but not He's divorceder.

A: I think your question is basically asking about comparative and superlative adjectives.
While

low, lower, lowest

exists

down, downer, downest

does not.
In the same way

high, higher, highest

exists, but

up, upper, uppest

does not.
Perhaps this might help you: Comparative and Superlative Adjectives


text:
Q: vertically centring relative position + unknown height I have two columns in my WP site. One has text/content the other a background image. Both are relatively positioned and the heights are unknown.
HTML (using twitter - bootstrap 3 markup )

<?php the_title(); ?>

<?php the_category(' '); ?>

CSS
.indx-img {
  position: relative;
  padding: 16% 0;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
}

.text-cell {
  position: relative;
  padding: 0 25px;
  margin: 0;
}

I want the text-cell div to be vertically centered in its column. The height of the column is set by its adjacent column index-img div with the padding: 15% 0

A: you can fiddle around with the transform translate percentage and a margin-top percentage..something like (play with x and y number to get desired result)
.text-cell {
  position: relative;
  padding: 0 25px;
  margin: x% 0 0;
  transform: translateY(y%)
}

or figure out the row height in jquery and then set offsets for that .text-cell div in jquery

A: Add this style :
.text-cell {
     display     : flex;
     align-self  : center;
}


text:
Q: Remove TinyMCE registration message through package import I want to build a TinyMCE React package and have used import { Editor } from '@tinymce/tinymce-react'; However I get this message -

Normally, to get rid of the message, according to https://community.tinymce.com/communityQuestion?id=90661000000IfUVAA0, you add the API key to the .js. in your <script> tag in your html. But I since I'm importing the package, there is no script for me to add the API key to.
Do I have to do something like mce-notification-inner {display:none!important;} or is there another way to get rid of the message?
https://www.tinymce.com/docs/integrations/react/
I also want to test using https://github.com/instructure-react/react-tinymce but don't know how to run the script. I tried this:
  componentWillMount () {
    const script = document.createElement("script");

    script.src = "//tinymce.cachefly.net/4.2/tinymce.min.js";
    // script.async = true;

    document.body.appendChild(script);
  }

but didn't work

A: The API key goes on the tag used to invoke the editor.  From the page you linked to:
<Editor apiKey='YOUR_API_KEY' init={{ /* your other settings */ }} />

Note the apiKey parameter on the tag - that is where you place the key.

A: You can get rid of those messages by including the tinymce.min.js as stated here:
Loading TinyMCE by yourself

To opt out of using TinyMCE cloud you have to make TinyMCE globally
  available yourself. This can be done either by hosting the
  tinymce.min.js file by youself and adding a script tag to you HTML or,
  if you are using a module loader, installing TinyMCE with npm.


text:
Q: C# Console Output of webpage to JSON I am fetching webpage with the following code. (copied from an intelligent programmer. To learn and stop hating MSFT). Now I have two questions.

*

*What is the format of output i.e. is it plain HTML or JSON

*If its not JSON then how to convert the output to JSON and export to CSV.
namespace getre
{
    class Class1
    {
        static void Main(string[] args)
        {
            string sURL;
            sURL = "http://www.tutorialspoint.com/csharp/csharp_basic_syntax.htm";

            WebRequest wrGETURL;
            wrGETURL = WebRequest.Create(sURL);

            WebProxy myProxy = new WebProxy("myproxy", 80);
            myProxy.BypassProxyOnLocal = true;

            wrGETURL.Proxy = WebProxy.GetDefaultProxy();

            Stream objStream;
            objStream = wrGETURL.GetResponse().GetResponseStream();

            StreamReader objReader = new StreamReader(objStream);

            string sLine = "";
            int i = 0;

            while (sLine != null)
            {
                i++;
                sLine = objReader.ReadLine();
                if (sLine != null)
                    Console.WriteLine("{0}:{1}", i, sLine);
            }
            Console.ReadLine();
        }
    }
}

A: The output from the console app is a custom format made up of a line number and the line content (separated by a ':') for each line of the response content (excluded any null lines!?).
If you want to check the content type before processing, then you can insert the lines:
WebResponse response = wrGETURL.GetResponse();

string contentType = response.ContentType;

If you're lucky the server/programmer will have set this in the response on the target website and it might be "text/html" or "application/json".


text:
Q: Stack level too deep when using Rails generate scaffold Getting the below stack error when trying to run the above from the Ruby on Rails Tutorial
rails generate scaffold User name:string email:string

/gems/ruby-2.6.3/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in ': stack level too deep (SystemStackError)
Was having another issue previously which lead me to making the app again from scratch, but now I can't solve this
results should invoke and create what looks like some scaffold files

A: From that error message, you seem to be using Rails 4.2.2 and Ruby 2.6.3. Using those two versions together is not supported.
Rails 4.2 only supports Ruby versions up to 2.4.5. See the travis.yml on the 4.2 branch to see what's supported.
Try either downgrading your Ruby version or upgrading your Rails version so that they're compatible.


text:
Q: How to implement slide to show actions in recyclerview? I have an app with a recyclerview showing some elements, the recyclerview also supports multiple viewtypes that can be changed from the settings. I am now looking to implement a way to show some actions for the recyclerview-items when a user swipes the item. Specifically I was looking for a way to implement a pane sliding out with the actions similar to the relay for reddit app.
The only answer I could find more or less, was to add a viewpager to each row in the recyclerview, but this doesn't seem like a very clean solution, especially with several viewtypes. How can I implement this feature?

A: The correct/recommended way to add actions on RecyclerView items on user swipe is to use a ItemTouchHelper.
You could add a swipe action like this:
        itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback() {
        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            //Perform your action
        }
    });
    itemTouchHelper.attachToRecyclerView(recyclerView);


text:
Q: How to write code for animation in MATLAB? I am trying to display convergence of Bernstein polynomials in MATLAB using the inbuilt function bernstein which is overloaded with symbolic variables.
I wrote the following code which displays all bernstein polynomials in different figure windows.
I searched for animation on MathWorks website, being a beginner to MATLAB, I didn't find some simple function to do this.
Please help me with the code.
Thanks.
          syms x
          axis tight
          for k=1:10
             figure
             ezplot(bernstein(sin(x),k,x))
          end

A: There are two problems in your code:

*

*By calling figure at the start of each iteration, you always open a new figure window, so you end up with 10 figures. Use e.g. figure(1) to always use figure nr. 1, or even better first create a new figure using h=figure; and open that figure by figure(h).

*Now you won't see much, because the plots are generated very fast. Using the pause function, you can specify a delay between iterations, e.g. for 0.5s delay use pause(0.5).
Put together, this gives the following code for your animation:
syms x
h = figure;
for k=1:10
    figure(h);
    ezplot(bernstein(sin(x),k,x));
    pause(0.5);
end

A: There are really good animation tutorials on the mathworks site.
http://nl.mathworks.com/help/matlab/creating_plots/record-animation-for-playback.html
However, to get a head start, you can try copying this code and just pasting your own function inside the loop.
  for k = 1:16
    figure(1);
    axis tight;

    plot(sin(k:0.1:k+(2*pi))); % replace with your function

    M(k) = getframe;
  end

fps = 10; % adjust this to change playback speed

movie(M,1,fps); % run this to play movie

%% Save the animation to avi file
writerObj = VideoWriter('test.avi');
writerObj.FrameRate = fps;
open(writerObj);
writeVideo(writerObj,M);
close(writerObj);

Change the value of fps to adjust the playback speed, and you can rerun the line movie(M,1,fps); anytime to replay the animation without generating all the frames again.  The last block of code saves your resulting animation to an AVI file with the specified framerate.


text:
Q: Unprotected error when calling nested Lua C library function with lua_pcall() I'm writing a C++ library function that takes in two tables and takes the values from the tables and puts them into a vector.
To reduce clutter I've also made a helper function that will read the values in one of the tables and performs some type checking.
However when calling luaL_error()in one of these nested functions I get the following in the terminal output:
PANIC: unprotected error in call to Lua API ()  [1]    18449 IOT instruction (core dumped)  build/bin/run
Where build/bin/run is the executable.
This function is called via lua_pcall()and so any errors should be caught, but that seems to not be the case.
Here is the main function that is added to the library:
    static int newMesh(lua_State* L){
        if(!lua_checkstack(L, 20))
            luaL_error(L, "Not enough stack space");
        if( !lua_istable(L, 1) )
            luaL_error(L, "Expected table of vertecies");
        if( !lua_istable(L, 2) )
            luaL_error(L, "Expected table of vertecies");

        std::vector<float> verticies;
        std::vector<unsigned int> indicies;

        /* Getting vao */
        unsigned int i = 0;

        lua_pushnil(L);
        lua_next(L, 1);
        indicies.push_back(i++);
        verticies = getVerticies(L); /*Here is one of the helper functions*/
        std::pair<unsigned int, GLenum> format = {verticies.size(), GL_FLOAT};

        while(lua_next(L, 1) != 0){
            indicies.push_back(i++);
            auto vertex = getVerticies(L); /* Its called again here*/

            if(vertex.size() != std::get<0>(format))
                luaL_error(L, "Vertex does not follow format %d floats", std::get<0>(format));

            verticies.insert(verticies.end(), vertex.begin(), vertex.end());
        }

        /* Getting materials */
        vector<Modulus::Material> materials;

        lua_pushnil(L);
        while(lua_next(L, 2) !=0){
            materials.emplace_back( getMaterial(L));

            lua_pop(L, 1);
        }

        /* Rough size estimate */
        size_t size =     sizeof(GL_FLOAT) * verticies.size()
                        + sizeof(unsigned int) * indicies.size()
                        + sizeof(Modulus::Material) * materials.size()
                        + sizeof(unsigned int) + sizeof(GLenum)
                        + sizeof(GLenum);

        Modulus::Mesh* newMesh = (Modulus::Mesh*)lua_newuserdata(L, size);
        newMesh= new Mesh(verticies, indicies, materials, vector<pair<unsigned int, GLenum>>{format}, GL_TRIANGLES);
        gLuaMeshes.push_back(newMesh);

        luaL_setmetatable(L, "Modulus.mesh");

        return 1;
    }

And here's the helper function in question:
    static std::vector<float> getVerticies(lua_State* L, int tableIndex = 4){
        std::vector<float> verticies;

        lua_pushnil(L);
        while(lua_next(L, tableIndex) != 0){
            int success;
            verticies.push_back( lua_tonumberx(L, -1, &success));
            if(!success){
                                /* Here is where the error is thrown*/
                luaL_error(L, "Expected number for vertex attribute");
                return std::vector<float>();
            }

            lua_remove(L, -1);
        }

        lua_remove(L, -1);

        return verticies;
    }

And here is where the script that calls the function is run:
bool loadFile(string path){
        int result =  luaL_loadfile(mLuaContext, path.c_str()) | lua_pcall(mLuaContext, 0, LUA_MULTRET, 0);
    if(result != LUA_OK){
        error("%s", lua_tostring(mLuaContext, -1));
            return false;
        }
    return true;
}

I've tried putting the helper function call in a try-catch block where it throws the error string and luaL_error is called in the main function, but the issue still occurs.

A: Okay so i found the issue.
In the function caller theres an error() function that's called if the lua_pcall() returns an error state.
Here's the definition for error():
void error (const char *fmt, ...){
    va_list argp;
    va_start(argp, fmt);
    luaL_error(mLuaContext, fmt, argp); /* Here's the issue.. */
    va_end(argp);
}

The issue is that i call luaL_error() again with the error string.
so i tried printing the error string at the top of the stack instead of calling my error() function, ant it works fine.
    bool loadFile(string path){
        int result =  luaL_loadfile(mLuaContext, path.c_str())
                    | lua_pcall(mLuaContext, 0, LUA_MULTRET, 0);
        if(result != LUA_OK){
            std::cerr << lua_tostring(mLuaContext, -1) << std::endl;
            //error("%s", lua_tostring(mLuaContext, -1));
            return false;
        }
    return true;
}

So having nested function calls was not the issue, it was me not understanding the functions i wrote.. Oh well


text:
Q: QGIS crashes too frequently to work I am running QGIS 2.18.7 on Mac OS (10.11.6).
The application crashes frequently. I usually only manage a few minutes work (while saving all the time) before it crashes.
I recently upgraded to this version as the last version was crashing too often... glad that helped!
There doesn't seem to be any common thing that causes this. Sometimes it crashes when I try to edit a shapefile, sometimes when I open a raster layer, sometimes when I zoom.... endless number of things.
I have tried setting up a new workspace, and keeping it trim and none of my open files are exceptionally large.
I have tried uninstalling all the plugins.
I have also checked other threads and noticed a few people having these issues, and the only thing that helped anybody was to follow the advice on the install page to rename or move the location of 'Qt4 developer components'. However I have no idea what these are.. or where to find them!! I search in finder and look in the usual places but no sign of these items.


text:
Q: Passing two parameters into shell script Im very new shell script. Im ran the below sqoop command in shell script and got the result.
sqoop command in shell script
#!/bin/bash
while read table; do
sqoop eval --connect jdbc:mysql://127.0.0.1/mydb --username root --password cloudera --query "describe $table"
done<tables.txt

Input file: tables.txt has just one word: MYTAB And Im gettting result for that.
But how can I write a script to take two parameters from the file when data in tables.txt looks like this: MYDB:MYTAB and I want to pass dbname and table name  to my sqoop command in the script which looks like below.
#!/bin/bash
while read table; do
sqoop eval --connect jdbc:mysql://127.0.0.1/$dbname --username root --password cloudera --query "describe $table"
done<tables.txt

Can anyone tell me how to extract the values from the file and put them in the file ?

A: Change your read statement after setting the proper field separator IFS to :
while IFS=":" read -r dbname table; do


text:
Q: Need help setting a texture background to a container div I'm trying to set a texture background to a container div. My CSS is below:
.container {
  background-image: url(..img/texture-one.png) repeat;
}

My problem is, the image isn't showing up. If I make an img tag in my HTML, the image shows up using the same path.

A: .container {
    background-image: url("img/texture-one.png");
    background-repeat: repeat-y;
}

A: background-image can have only image path.
background-image: url|none|initial|inherit;
background is shorthand for multiple background properties.
background: bg-color bg-image position/bg-size bg-repeat bg-origin bg-clip bg-attachment initial|inherit;
So you need:
.container {
   background: url(..img/texture-one.png) repeat;
}

A: Perhaps just add quotes around image link?
.container {
  background-image: url("img/texture-one.png");
}

A: Can you show the HTML code too?
If you have floated elements inside the container, then the height of the container is 0, so you can't see a thing. In this case, you should use overflow: auto; on the container.


text:
Q: How to calculate time betwen first and last connection in a Java TCP Server/Client program I am doing a project for the university where they ask me to send messages from different clients to a server. One of the things they ask me is to calculate the time from the first time a client connects to the server and the last time. I can't think of a way to calculate this time and that's where my question comes, I'm a little new to sockets, maybe it's something simple. Appreciate your help.
Server
public class Reportero {

public static void main(String[] args) throws IOException {

    ServerSocket servidor = null;
    Socket sc = null;
    DataInputStream in;
    DataOutputStream out;
    int contador = 0;

    final int PUERTO = 5000;

     try {

         servidor = new ServerSocket(PUERTO);
         System.out.println("Reportero iniciado.");

         while(true) {

             sc = servidor.accept();
             //Cliente conectado

             in = new DataInputStream(sc.getInputStream());
             out = new DataOutputStream(sc.getOutputStream());

             String mensaje = in.readUTF();

             System.out.println(mensaje);

             out.writeUTF("Hola desde el reportero.");

             contador++;
             System.out.println("Cantidad de información recibida: " + contador);

             sc.close();
             //Cliente desconectado
         }

     }catch (IOException ex) {
         Logger.getLogger(Reportero.class.getName()).log(Level.SEVERE, null, ex);
     }
     }
}

Client
public class Consumidor {
   public static void main(String[] args) throws IOException, TimeoutException {

    final String HOST = "127.0.0.1";
    final int PUERTO = 5000;

 try {
        DataInputStream in;
        DataOutputStream out;
        Socket sc = new Socket(HOST, PUERTO);
        in = new DataInputStream(sc.getInputStream());
        out = new DataOutputStream(sc.getOutputStream());

        out.writeUTF(encryptThisString(m));

        //Imprimir mensaje que envía el reportero
        //System.out.println(in.readUTF());

        sc.close();

        }catch (SocketException ex) {
            Logger.getLogger(Consumidor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnknownHostException ex) {
            Logger.getLogger(Consumidor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Consumidor.class.getName()).log(Level.SEVERE, null, ex);
        }

}
}

This is my code, hope you can help me.


text:
Q: JavaScriptSerializer serializes to JSON by default? Isn't this a bit odd?
Looks like private methods actually accept parameter that allows to set JavaScript serialization mode instead of the default (JSON), but it is never exposed... To make this even more odd Serialize() happily accepts string and encodes it as JavaScript string (it escapes quiet a bit more than required by JSON standard), where as DateTime will be encoded as JSON.
I am confused. Is there a derived class somewhere that does actual JavaScript serialization?

A: I don't see anything odd about the string behavior.  The JSON representation of a string is just a string.
You don't really see any JSON notation until you serialize objects with properties as opposed to simple types.
JSON is actual javascript though, so I'm not sure what sort of serialization you're looking for, exactly.
var s = new JavaScriptSerializer();
Console.WriteLine(s.Serialize(DateTime.Now));
Console.WriteLine(s.Serialize("I like things & stuff ' \" ."));
Console.WriteLine(s.Serialize(3.14));
/* Should serialize to JSON object */
Console.WriteLine(s.Serialize(new { String = "I like things & stuff ' \" .", Date = DateTime.Now, PI = 3.14 }));
/* Should serialize to array */
Console.WriteLine(s.Serialize(new object[] { "I like things & stuff ' \" .", DateTime.Now, 3.14 }));

Output:
"\/Date(1316374642273)\/"
"I like things & stuff \u0027 \" ."
3.14
{"String":"I like things & stuff \u0027 \" .","Date":"\/Date(1316374642278)\/","PI":3.14}
["I like things & stuff \u0027 \" .","\/Date(1316374642280)\/",3.14]

There is some backstory to the funny date format.
The 'Javascript' serialization format appears to be code left over from the first attempt at serializing dates into JSON.  The only place that value is actually used is in SerializeDateTime  I would imagine the team just made those methods private after determining that was a bad idea per the linked article:

The first thing we tried was to inject Date constructors in the JSON string. This is a (very) bad idea for a number of reasons. First, it simply does not conform to the JSON specs. Second, any JSON parser that validates its input before parsing it will cough on such a thing. Finally, it establishes a precedent: why would it be allowed for dates and not for arbitrary types? This would just defeat the purpose of JSON.

If you really just need to serialize an individual DateTime to Javascript, there's no reason you can't steal those couple of lines of code, but if you're serializing a complex object there are valid reasons you shouldn't be doing that.
public string SerializeDateTime(DateTime datetime)
{
    DateTime time = new DateTime(0x7b2, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    DatetimeMinTimeTicks = time.Ticks;

    var sb = new StringBuilder();
    sb.Append("new Date(");
    sb.Append((long) ((datetime.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 0x2710L));
    sb.Append(")");
    return sb.ToString();
}

If what you need is to actually use a serialized date from ASP.NET on a webpage, and you aren't using ASP.NET AJAX, that is covered in this question: How do I format a Microsoft JSON date?

A: Serializing data is turning it into a string/stream, usually so it can be stored in a database, or transmitted over a network.  Javascript is a programming language.  JSON is a subset of Javascript that represents objects, arrays, strings, and numbers as literals which can be represented in a string.  All that to say that JSON is Javascript.  If you want to serialize an object graph as Javascript, it is JSON.  What behavior are you expecting?  While the JavaScriptSerializer can be used to escape strings or serialize a DateTime, I think the intended use is to serialize object graphs.  And, if it does escape more characters than JSON requires, I am sure it is still valid JSON.


text:
Q: How to check whether a folder is empty or not using python? Checking Whether A Folder Is Empty Or Not.
How can i ckeck wether a folder is empty or not using python ?
I'm creating a face recognition program in opencv and i need to check wether the folder where the testing image should be is empty ot not. Any help will be appreciated!
Ty

A: I'd do
if len(os.listdir('path/to/your/folder')) == 0:
    print("empty")


text:
Q: Angular i18n - Error: No plural message found for value "0" I am following the development guide of Angular i18n: https://angular.io/guide/i18n
I have defined a plural literal like this:
<span i18n>Updated {minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago}}</span>

I have defined a variable in MyComponent.ts like this:
minutes = 0;

I am running my application like this:
ng serve --port 4300 --configuration=fr

I have defined the messages.fr.xlf like this:
<trans-unit id="5a134dee893586d02bffc9611056b9cadf9abfad" datatype="html">
    <source>{VAR_PLURAL, plural, =0 {just now} =1 {one minute ago} other {<x id="INTERPOLATION" equiv-text="{{minutes}}"/> minutes ago} }</source>
    <context-group purpose="location">
      <context context-type="sourcefile">app/tenants/tenant1/tenant1.module.ts</context>
      <context context-type="linenumber">4</context>
    </context-group>
    <target>{VAR_PLURAL, plural, =0 {à l'instant} =1 {il y a une minute} other {il y a <x id="INTERPOLATION" equiv-text="{{minutes}}"/> minutes} }</target>
  </trans-unit>

But when I load the page I have the following error:
 Error: No plural message found for value "0"

Please, what am I doing wrong?

A: Solution:
I was not importing correctly CommonModule which contains NgPlural & NgSwitch;
import { CommonModule } from '@angular/common';


text:
Q: How to set User's Consent notGranted by default on Flutter HERE SDK? https://github.com/heremaps/here-sdk-examples/tree/master/examples/latest/navigate/flutter/navigation_app
As in this repo here I know HERE SDK needs user permission for Android devices. But I don't want to show it to users. Can I set the content engine as not granted by default when app starting?

A: The ConsentEngine is only necessary when you want to use the LocationEngine. By default, it is not granted. So, there's nothing to do and you can continue to use other parts of your application until you need to grant consent.
This location guide explains this in greater details.