Unable to create/edit smithing recipes

Question: I would like to edit some smithing recipes in a modpack I am making. I have the following:
<code>{
  "type": "minecraft:smithing_transform",
  "template": {
    "item": "minecraft:air"
  },
  "base": {
    "item": "minecraft:iron_ingot"
  },
  "addition": {
    "tag": "twilightforest:fiery_vial"
  },
  "result": {
    "item": "twilightforest:fiery_ingot"
  }
}
</code>
I assumed "template" was optional, since of course, you may want to smith something without a template, but regardless of whether I have it or not, this recipe still fails to load.
If I have the above (with template section), it gives me: "Missing field template"
if I remove the template section, I get: "Empty ingredient not allowed here"
Answer: Smithing something without a template is not possible using the vanilla smithing mechanics.
The smithing upgrade mechanic was introduced with the intent to allow players to modify their equipment (e.g. tools, weapons, armor) by replacing the base item with a result item while preserving the NBT data (e.g. enchantments, durability usage, prior work penalty). This mechanic requires a template by design (see Smithing: Equipment). If you look at the JSON data format for a smithing upgrade recipe (see Recipe: smithing_transform), you will find that the template component is indeed not optional.
Here are three options to achieve what you seem to be doing, starting from my strongest advice:

If you want to add a recipe that doesn't require a smithing template, maybe you want a crafting recipe instead? To me personally, combining an Iron Ingot and a Fiery Vial sounds more like a crafting recipe, because normally there wouldn't be any NBT data that needs to be preserved when upgrading an Iron Ingot to a Fiery Ingot. After all, the good old Crafting Table has a hammer too, you know. :)

If you really want to add a custom smithing recipe, I advise you to add a template item for that recipe. It doesn't have to be something expensive to make, but it should be an iconic token representing your smithing process. It could be something as simple as a blueprint scribbled on a piece of paper.

If you are absolutely sure that it has to be a smithing recipe without a smithing template, you will have to implement your own smithing mechanics, your own smithing block and likely your own menu for it. This is probably not worth the hassle, but is a way nonetheless. If you're planning to add a lot of templateless custom smithing recipes, this mechanic could be a core feature of your mod.

Unable to create/edit smithing recipes


If $w_1, w_2$ are eigenvectors of $A^TA$ associated with different eigenvalues, then $Aw_1$ is orthogonal to $Aw_2$.

Question:
if $w_1, w_2$ are eigenvectors of $A^TA$ associated with different eigenvalues. How to show $Aw_1$ is orthogonal to $Aw_2$

I would like to use the SVD factorization to prove this statement. Is it correct to say if $w_1,w_2$ are eigenvectors of $A^TA$ then exists a SVD $A=USV^T$ such that $w_1,w_2$ are normalized in any of the columns of $V$ ?
Comment: Does this answer your question? [Prove that the multiples of two orthogonal eigenvectors with a matrix are also orthogonal](https://math.stackexchange.com/questions/2784701/prove-that-the-multiples-of-two-orthogonal-eigenvectors-with-a-matrix-are-also-o) (together with [this wellknown fact](https://math.stackexchange.com/questions/82467/eigenvectors-of-real-symmetric-matrices-are-orthogonal) alluded to by @Anurag)
Comment: Note that $A^TA$ is a symmetric matrix so spectral theorem gives you.....
Comment: If you would consider proving this without using SVD, then a (vague) hint would be to write down the definition of orthogonality between $Aw_1$ and $Aw_2$ and manipulate the expression so you get something involving $(\lambda_1 - \lambda_2)$.
Answer: To spell it out, suppose that $w_1$ and $w_2$ are eigenvectors of $A^T A$, and suppose that the corresponding eigenvalues are $\lambda_1$ and $\lambda_2$, with $\lambda_1 \neq \lambda_2$.
Then
$$ \lambda_1 w_1^T w_2 = \left( A^T A w_1 \right)^T w_2  = w_1^T A^T A w_2 = w_1^T \left( A^T A w_2 \right) = \lambda_2 w_1^T w_2.$$
Since $\lambda_1 \neq \lambda_2$, we must have
$$ w_1^T w_2 = 0.$$
Now
$$ (Aw_1) . (Aw_2) = (Aw_1)^T (Aw_2) = w_1^T A^T A w_2,$$
but by the calculation above, we have
$$ w_1^T A^T A w_2 = \lambda_1 w_1^T w_2 = 0, $$
so
$$ (Aw_1) . (Aw_2)  = 0.$$


Faster mini Arduino board for OLED display

Question: im looking to create a car live-data display gauge.
Such things as Boost, AFR, some temperatures.
For that i want to use this OLED display:
http://www.ebay.com/itm/I2C-2-42-128x64-Graphic-OLED-Yellow-Display-Arduino-PIC-Multi-wii-/201468080188?hash=item2ee86ef03c:g:Rc4AAOSw5ZBWQxoj
But since i need to update it quite frequently, i think i would need a faster Arduino than the Arduino Mini V3 one i have (Or the ATtiny i've used to work with). I was looking at the Cortex M3 arduino board, one like this: http://www.ebay.com/itm/1PCS-Arduino-IDE-kompatibles-Board-STM32-STM32f103C8T6-ST-ARM-32-bit-Cortex-M3-/272501782722?hash=item3f725f38c2:g:li4AAOSw241YZK24
Will it be enough for a real-time data display?
Basically all it will do is read sensors and display data, i just want to eliminate the lagginess and make it more real-time.
Thank you,
Max.
Comment: Why wouldn't an ATTiny work? http://www.instructables.com/id/ATTiny85-connects-to-I2C-OLED-display-Great-Things/
Comment: @gre_gor  OP implies in his post -- then comments -- that he'll need other sensors as well,   Might need more pins and ADCs than that tiny package offers.
Comment: ATtiny, given that it is a very compact and easy to setup chip would have too few I/O pins. It did work perfectly before in projects where i need fewer I/O's, but this time i am more concerned about the refresh rate of the display with the Atmel chips. I am thinking if going ARM Cortex way would be faster for display refresh times.
Answer: You'd be surprised at how fast a well-programmed 16 Mhz microcontroller can be.  In this project you're taking on, which is ambitious, I suspect the least of your problems will be speed or latency of the Arduino.  Pick a micro with the features you need based on the sensors you've selected, after reading their datasheets.
Comment: The sensors are either 0-5V sensors or resistance type ones. So its just a matter of analog-reading all of them. Since the display i have chosen is 128x64 pixels, i had a thought that the old Arduino Nano V3 would be a little slow updating it in real-time. So you are saying that the refresh speed will not be drastically different? If so, i might aswell try it with the Arduino i have :)
Comment: I'm making no predictions -- but I always choose the microcontroller part for a design based on actual needs, including pin count.  What is the interface to your OLED?  That may drive your decision.
Comment: It's I2C, so it does not need a lot of pins to run.
Comment: From I2C.info:  "I2C bus is popular because it is simple to use, there can be more than one master, only upper bus speed is defined and only two wires with pull-up resistors are needed to connect almost unlimited number of I2C devices."  I think you need to review your part datasheets and map your various IO pins to Arduino pins and see.  This is the first step in embedded development -- designing what is connected where on a target device.  Let's say you have three other analog sensors, that's three more analog pins.  Five pins total.  Add a diagnostic LED.  That's six.  Still maybe doable.
Comment: Im ok with the I/O, did design custom circuits with Arduino or a simple ATtiny in them. Just curious if the speed i am aiming at will be enough with the Atmel chips or should i go ARM Cortex from the start.


how can I run HTML5 doc with WebGL canvas on IPython notebook

Question: There is a nice tutorial on WebGL at this link:
http://learningwebgl.com/blog/?p=571
and I am using this example as my starting point for this question:
http://learningwebgl.com/lessons/lesson06/index.html
So it runs nicely on my browser. I copied the source and required libaries:
 - glMatrix.html
 - webgl-utils.js

on my pc. Now I can run them again on my browser nicely.
In the source html, these libaries are referred to as external libraries like this:

They are located in the same directory as my source html, namely, kvBox.html.
Now I want to run this html within from the notebook cell. I enter:
from IPython.core.display import HTML

def putHTML():

    source = open("kvBox.html", "rb").read().decode()
    return HTML(source)

putHTML()

Same screen is there, without the box and the canvas. No error messages on the output line on the notebook.
When I look at the Notebook Server console I see these errors:
[I 21:56:51.077 NotebookApp] 302 GET /notebooks/.%5CglMatrix.js?_=1454010913066
(::1) 15.64ms
[I 21:56:51.077 NotebookApp] Refusing to serve hidden file, via 404 Error
[W 21:56:51.077 NotebookApp] 404 GET /files/.%5CglMatrix.js (::1) 0.00ms referer
=http://localhost:8888/notebooks/Untitled4.ipynb?kernel_name=python3
[I 21:56:51.093 NotebookApp] 302 GET /notebooks/.%5Cwebgl-utils.js?_=14540109130
67 (::1) 0.00ms
[I 21:56:51.093 NotebookApp] Refusing to serve hidden file, via 404 Error
[W 21:56:51.093 NotebookApp] 404 GET /files/.%5Cwebgl-utils.js (::1) 0.00ms refe
rer=http://localhost:8888/notebooks/Untitled4.ipynb?kernel_name=python3

I have googled and looked throgh SO for including external libraries to notebook. Mostly I found noteook extensions given at github. I need a solution for my own additions.
The nearest question was this item:
How to add external javascript file in Ipython notebook
So I tried to use %%html  commands for the above mentioned external libraries. No erro on the output line, but same refusal error on the console.
EDIT:
After reading and trying so many different suggestions which have not worked, I had a workaround. I wrote a simple include routine myself. I merge the library code into my source html, in the "source" string above, and everything works fine.
Comment: I do not know how external JS libs are included, but I added the code by brute force into the html doc as  as normla internal javascript, and it works fine.
Answer: The path separator character in a URL is / not \. See the documentation.
Your browser appears to be performing error recovery while IPython is not.
Hence you are getting 404 errors for /files/.%5CglMatrix.js (%5C is a URL encoded \) instead of 200 OKs for /files/glMatrix.js.
Use the correct URL.
Comment: I must have tried all possible combinations with absolute or relative paths, with backslash or forward slash, with a preeceding dot or not, or without a skas at all, but I will go back and gşve it a try since I will need it in the long run for several others.
Comment: I tried again with forward slash. Now I get: "mat4 not found" error on the Notebook output cell. mat4 lives in glMatrix.js. On the jupyter console I get "302 GET/NOTEBOOKS/glMAtrix.js?_=..." error. I checked nbextensions dir, my notebook starting dir; the lbs are there. I tried again redefining extensions via: "notebook.nbextensions.install_nbextension(path = "C:/...". Same 302 /GET and mat4 not found error.
Comment: I think I found the error, which is related with backslash; but not in my code - in the handler code.
Answer: I think I found the root cause of the error. As Quentin indicated, it has to do with the backslash character. But not in my code. It is in the handler code. I am not sure whether it is on the Tornado side, or the Notebook side, but in the handler code where it gathers the path info, the os.path.join command creates backslashes; normal for python, but not good for Javascript.
Here is piece of trace I had created on my original Tornado application:
WARNING:tornado.access:404 GET /img%5Cbaseball.jpg (127.0.0.1) 0.00ms
handler_path:  ./images\BouncingBallDemo\baseball.jpg
app_path:  ./images\baseball.jpg
img_src:  /img\baseball.jpg

Upon replacing backslashes with forward slashes, my code worked OK on my Tornado application. I believe something similar is happening on my original notebook problem. I am not sure if I myself will be able to have a workaround, I will check.


define custom variables and direct call the variables in view part

Question: What I want to do is creating a file like my_custom_settings.php in config directory and call the defined variable in view part.
let's say in my_custom_settings.php:
define('TEMPLATE_DIR', 'assets/front');

and in view part direct in HTML:
<link href="<?=TEMPLATE_DIR?>/stylesheet/style.css">

or any other alternative solution??
PS: Now I am using base_url() to access the path
Comment: base _url is best way to do it....why you want to do like that.....
Comment: @Venkat i just want to define some images directories, and i saw somewhere in a codeigniter project. Is there any issue with to access the path with `defined variable`??
Comment: so u want use some images in you are application. For that you want to create a directory and you want to call that directory by defining a custom variable.......am i right
Comment: @Venkat yes, something like ``
Comment: do one thing no need to create any variable.......just create a directory in your application_name->application and Images.......Now you can include any name just like this base_url/images/imge.jpg
Answer: personally i extend the /core/helpers/url_helper.php , defaults are site_url() , base_url(), current_url(); etc ... i just extended that for having base_static_url();
so put in core/helpers/url_helper.php:
if ( ! function_exists('base_static_url'))
{
    function base_static_url()
    {
        $CI =& get_instance();
        return $CI->config->slash_item('base_static_url');
    }
}

then in config.php file you just add 1 more line:
$config['base_url'] = "http://mysite.com/";
$config['base_static_url'] = "http://mysite.com/static/"; //path to your static resources folder

then you can call static resources using :
<img src="<?php echo base_static_url();?>img/myimage.png"/>

Comment: thanks for your help, i appreciate with your answer but i already defined `base_url()` in my application, but i just want to know if it's according to my question, cause i saw somewhere in a codeigniter project, i know i don't have specific reason to use defined variable, if it's wrong then please make me correct.
Comment: you can both use a constant or extend the url_helper.php me i preferr extending the url_helper.php cause that is the one is setting the base_url,the current_url, the site_url and so on, so i think is better having all in 1 file
Comment: doesn't matter if you just have base_url() you can set others easly if you do what i told you to do :)
Answer: ok this is might be more then what you are looking for,
but this is a way to put site wide configs in one file, and then easily have them available
in config folder you have file: my_custom_settings.php
in that file you want to set a config value like:
$config['TEMPLATE_DIR'] = 'assets/front' ;
$config['site_slogan'] = 'Laravel? Never heard of it' ;

create another file called: My_custom_settings.php
put that file in: application/library/My_custom_settings.php
that file will contain:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class My_custom_settings
{

function __construct($config = array() )
{
foreach ($config as $key => $value) {
    $data[$key] = $value;
    }
//  makes it possible for CI to use the load method
$CI =& get_instance();
//  load the config variables
$CI->load->vars($data);
}
} // end my custom settings

now in your controller constructor
public function __construct() {
    parent::__construct();

// Load configs for controller and view
    $this->load->library( 'my_custom_settings' );
    $this->config->load( 'my_custom_settings' );

} // end construct

Now for the cool part -- anything you put in that config file, will be available for your controller and views. ( you can load config in a model constructor as well ).
in a controller or model you get the value with $this->config, like
$this->config->item( 'site_slogan' )

a little awkward, but for views, heres the reward, you only need the config name
echo $TEMPLATE_DIR . '/somefile' ;

Comment: +1 like your way. i changed my mind to use something like this `TEMPLATE_DIR` because of no reason. Thanks a lot for your help ;)
Answer: Images, css, javascript, pdfs, xml... anything that is allowed to be accessed directly should not be living in your application directory. You can do it, but you really shouldn't. Create a new folder at the root of your directory for these files, they should not be mixed into your application, for example: in your views folder.

Chances are, you're using an .htaccess file, which is only allowing certain directories to be accessed via http. This is very good for security reasons, you want to stop any attempt to access your controllers and models directly. This is also why we check if BASEPATH is defined at the top of most files, and exit('No direct script access.') if not.
To get the correct path to these resources (js/css/images), you can't use relative paths, because we aren't using a normal directory structure. The url /users/login is not loading files from the directory /users/login, it probably doesn't even exist. These are just uri segments that the bootstrap uses to know which class, method, and params to use.
To get the correct path, either use a forward slash (assuming your app and assets are in the root directory, not a subdirectory) like this:

  Or your best bet, use an absolute url:
// References your $config['base_url']
 " />
 Equivalent to:
http://mydomain.com/images/myimage.jpg
There are helpers built into CI that you can optionally use as well, but this is really all you need to know.
Comment: this is wrong if you need to move static resources to another site domain you get a big refactoring trouble!!
Comment: No need just change the folder to another domain directory and access them again using base_url/iamges/imge.jpg. I am working right now in my application. Few days i worked on my local system where  my base_url is localhost/application_name. After that i shifted my application to server so i just changed my base_url it works like a gem.......
Comment: you didn't catched what i tell you, what if you have your **app** on **site.com** and your **img folder** on **othersite.com** ?
Comment: using codeIgniter u can't access resources outside of your application directory..........
Comment: totally wrong :/ i'm talking about static resources (img,js,css) YOU CAN and not only with CI
Comment: me not sincerily, which was your problem? :)
Comment: check out this link Ispuk and Jogesh for more clarity in what i am saying..........http://stackoverflow.com/questions/5656894/how-can-i-display-images-with-the-codeigniter-php-framework
Comment: ok, but you didn't checked that following what i wrote in answer you totally fix that problem! cause then you'll have separated **base_url()** and **base_static_url()**


Can I make a persona without sociodemographic data, and focusing only on behavior?

Question: I am building a persona for 2 studies. I did qualitative and quantitative research in the studies, and didn't need to collect sociodemographic data.
What are your thoughts on making a persona without having sociodemographic data, and focused only on behaviour?
Comment: Hi @Francis, Welcome to UX-Stackexchange. Can you share more context of the study(s), and why you need a persona for the same? That will give more context to folks who will be able to provide some helpful answers :)
Answer: One of the main purposes of personas is to create a relatable character, one that you can try to empathize with, and which can be easily used in product-related processes in the organization. It will be very difficult to accomplish that using a an abstract construct with just behavior. A persona will need to be given human features - a face, age, gender, name etc., so that a believable character is created.
To what extent this needs to be backed by research data is a good question, especially in cases where this is not very important to the product domain.
In either case in many domains you can accomplish this part post-hoc, e.g. by using social networks to find the sociodemographic characteristics of your personas. Domain-specific networks would be best, although Facebook and Linkedin can also provide great data. It's also common practice to supplement data from professional forums with more personal data from FB, so that you can use a professional forum to find the name for a person who fits your persona, and then form an impression about their sociodemographic details based on their FB profile.
Answer: Things like demographics, age, family, occupation, names, educational levels and job are very important for a complete persona. My advice is to try harder in your research for gaining some information about these.


Specify return type when value of input interface is specific value

Question: I have a function that takes an object as an argument. When a property of that input is a given value, I want to specify the return type as being one or the other. I assume this requires conditional types, but I'm struggling with the syntax to access the property of a given interface.
What I currently have is below:
enum FileAcl {
    private = 'private',
    public = 'public',
}

interface UploadOpts {
    someval: string;
    acl: FileAcl;
}

interface PrivateAclResponse {
    acl: FileAcl.private;
    key: string;
}

interface PublicAclResponse {
    acl: FileAcl.public;
    file: string;
}

const uploadFile = async (opts: UploadOpts):
    Promise<PublicAclResponse | PrivateAclResponse> => {
    const { acl } = opts;

    if (opts.acl === FileAcl.public) return { file: 'file', acl }

    return { key: 'key', acl }

}

I did try the following, but I'm clearly wrong so any guidance would be much appreciated.
enum FileAcl {
    private = 'private',
    public = 'public',
}

interface UploadOpts {
    someval: string;
    acl: FileAcl;
}

interface PrivateAclResponse {
    acl: FileAcl.private;
    key: string;
}

interface PublicAclResponse {
    acl: FileAcl.public;
    file: string;
}

// assuming here that ts can match the common properties
type PublicOrPrivate<T extends UploadOpts> = T extends PublicAclResponse
    ? PublicAclResponse
    : PrivateAclResponse;

const uploadFile = async (
    opts: UploadOpts
): Promise<PublicOrPrivate<UploadOpts>> => {
    const { acl } = opts;

    if (opts.acl === FileAcl.public) return { file: 'file', acl }

    return { key: 'key', acl }

}

TIA
Answer: You can indeed use a Conditional Type. But additionally a generic parameter is needed for the condition. Unfortunately, TypeScript doesn't seem to be able to narrow opts to either PublicAclResponse or PrivateAclResponse which means we need to assert the return type.
const uploadFile = async <
  T extends UploadOpts,
  R = T["acl"] extends FileAcl.public
    ? PublicAclResponse
    : PrivateAclResponse
>(
  opts: T
): Promise<R> => {
  const {acl} = opts;

  if (opts["acl"] === FileAcl.public) return {file: "", acl} as R;

  return {key: "key", acl} as R;
};

const publicResponse = uploadFile({ // Promise<PublicAclResponse>
  acl: FileAcl.public,
  someval: ""
});

const privateResponse = uploadFile({ // Promise<PrivateAclResponse>
  acl: FileAcl.private,
  someval: ""
});

TypeScript Playground
Comment: Thank you very much indeed. This has worked a charm!


How to Vue let input value v-model with v-bind:value operation

Question: Like below code I hope set input2 v-model bind with data-value2,and the value is operationed from value1 * 2, but it does not work and throw error:

[Vue warn]: Error compiling template:
  v-bind:value="value1*2" conflicts with v-model on the same element because the latter already expands to a value binding internally

  <input id="input1" type="number" v-model="value1">
  <input id="input2" type="number" v-model="value2" v-bind:value="value1*2">

What I've tried:
I can create a onchange method to do it, but it need to duplicate adding v-on:change="operateValue" code to input.

  <input type="number" v-model="value1" v-on:change="operateValue">
  <input type="number" v-model="value2" v-on:change="operateValue">
  <input type="number" v-model="value3">

Is it possible? Or I have create a method to custom the operation?
Comment: please use computed properties
Comment: You need to bind the prop to an object, not an expression.
Comment: @halfer thanks , I'll correct my bad habit.
Comment: I've tried it out and it gives me an error
Comment: @PhilipF. yes, it'll throw error,but my expected is like that.
Comment: Ifaruki 、Yom S ,thanks,it's useful for me!
Comment: A quick reminder that posts here need to be written to be as readable as possible, since we try to keep them forever. We want them to be as useful as possible to future readers. With that in mind, please try to observe the rules of English writing, which is that sentences start with a capital letter, and the personal pronoun "I" is always a capital letter. If you are posting on a mobile device, such as a tablet or phone, capital letters can still be produced on an English keyboard.
Comment: Thank you, I appreciate it.
Answer: You cannot use v-model and v-bind:value on the same element because it gives you an error.
You can however use a computed property instead:

var myObject = new Vue({
    el: '#app',
    data: {
        value1: 1
    },
    computed: {
        value2: function() {
            return this.value1 * 2;
        }
    }
})

    <input id="input1" type="number" v-model="value1">
    <input id="input2" type="number" v-bind:value="value2">

You can then also access 'value2' by using:
console.log(myObject.value2);

For more infos refer to https://v2.vuejs.org/v2/guide/computed.html
Answer: You cannot do that since v-model is just shorthand for :value="someVar" and@update="setSomeVar"` what you can do is split them then you should have no problem.
So just write something like above:
<input id="input1" type="number" v-model="value1" @input="value2 = $event*2">
<input id="input2" type="number" :value="value2">


How to offload geography operation to SQL Server in Entity Framework Core 1.0

Question: How to consume geography data stored in SQL Server using Entity Framework Core if geography data type is not yet supported and stored procedures too?
Comment: For the moment, you should use EF6 if you plan to release your application. There is no date for a final release....
Comment: @Thomas not always an option, for example if targeting UWP
Comment: ohh... sorry ^^ did you see this issue https://github.com/aspnet/EntityFramework/issues/1100?
Comment: Yes, actually, the last post with such question there was written by me
Answer: This is how i've done it. Obviously you don't get the features of the DbGeography type, but for simple queries it should suffice.
<code>  public async Task<List<PointOfInterest>> Execute(double latitude, double longitude, int radius)
        {
            return await this.context.PointsOfInterest.FromSql(

            "DECLARE @point geography = geography::Point(@p0, @p1, 4326); " +

            "SELECT Id, DateAdded, Latitude, Longitude " +
            "FROM dbo.PointsOfInterest " +
            "WHERE @point.STDistance(Location) <= @p2",
            longitude,
             latitude,
            radius).ToListAsync();
        }
</code>
Comment: How do you map your property 'Location'?
Location is a sys.geography in your database right, but how did you declare it in your model / fluent api?
I have a similar problem : https://stackoverflow.com/questions/44873740/entity-framework-core-type-udt-is-not-supported-on-this-platform/
Comment: I think i just had it mapped in my model as a string, and then added a migration to Alter the column to a Geography type using the builder.Sql() method. Any query/command that you do with that field will need to be in Raw SQL.
Comment: @Eli See https://stackoverflow.com/questions/40765439/efcore-spatial-query-a-number-is-expected-at-position-9-of-the-input-the-input/40877869#40877869


get object from multidimensional array php

Question: I have multidimensional array like this
array:2 [
  0 => array:2 [
    "worker_id" => "1"
    "salary" => "100000"
  ]
  1 => array:2 [
    "worker_id" => "2"
    "salary" => "80000"
  ]
]

i try get the object but didn't work
foreach ($request->salary as $data)
{
    ($data->worker_id);
}

Thanks a lot.
Comment: Did you tried $data['worker_id']? What kind of error did you get?
Comment: @WannyMiarelli yes i get error Trying to get property 'worker_id' of non-object
Comment: yes this is because it is an array and not an object, the -> accessor is only for objects, with arrays you should use the index $data['index'].
Answer: <?php

function arr2Object($arr) {
    if (is_array($arr)) {
        return (object) array_map(__FUNCTION__, $arr);
    }
    else {
        return $arr;
    }
}

$request = [ ["worker_id" => "1", "salary" => "100000"], ["worker_id" => "2", "salary" => "80000"]];

$obj = arr2Object($request);

foreach ($obj as $data) {
    echo $data->worker_id;
    echo $data->salary;
}

Comment: you can badge my answer.
Comment: you can vote and check it. and click on answer button.
Comment: done, i'm so embarrassed don't see the check button
Answer: While He Zhi Yong answer may work to me it is more correct to access it as an array instead of an object.
$request = [ ["worker_id" => "1", "salary" => "100000"], ["worker_id" => "2", "salary" => "80000"]];

foreach ($request as $data)
{
    echo $data['worker_id'];
}


Understanding an application of the Cauchy–Schwarz inequality

Question: Here is the link to the solution:
Why should we use the uniform boundedness principle here?
And here is the solution:
First let's show a simpler version (1-dimensional): If $\sum_i a_i x_i < \infty$ all for $x\in\ell^2$, then $a\in \ell^2$.
You can prove this claim using uniform boundedness principle, or you can just use Riesz Representation Theorem. See [this post][1].
Now, let's go back to your problem. It follows from the claim above that each row of $A$ is in $\ell_2$. Define $T_N$ to be the restriction of $A$ onto the first $N$ rows, that is,
$$T_N x = \left(\sum_j a_{1j}x_j,\sum_j a_{2j}x_j,\dots,\sum_j a_{Nj}x_j,0,0,\dots,\right).$$
We claim that $\|T_N\| < \infty$. Note that
$$\|T_Nx\|_2^2 = \sum_{i=1}^N \left|\sum_j a_{ij}x_j\right|^2 \leq \sum_{i=1}^N\left(\sum_j |a_{ij}|^2 \right)\left(\sum_j |x_j|^2 \right) \leq \|x\|_2^2\cdot \sum_{i=1}^N\sum_{j=1}^\infty |a_{ij}|^2,$$
thus
$$\|T_N\| \leq \left(\sum_{i=1}^N\sum_{j=1}^\infty |a_{ij}|^2\right)^{1/2}.$$
(Note that the infinite sum over $j$ is finite because of the claim at the beginning.)
Now, for each fixed $x$, observe that $\|T_Nx\|_2$ is uniformly bounded by $\|Ax\|_2$ (since $\|T_Nx\|_2$ is just part of the sum for $\|Ax\|_2<\infty$). It follows from the uniform boundedness principle that $\sup_N \|T_N\|<\infty$. Note that $\|Ax\|_2 = \lim_{N\to\infty} \|T_Nx\|_2 \leq (\sup_N \|T_N\|)\|x\|$, which implies that $A$ is bounded and $\|A\| \leq \sup_N \|T_N\|$.
But I do not understand this step:
$\sum_{i=1}^N \left|\sum_j a_{ij}x_j\right|^2 \leq \sum_{i=1}^N\left(\sum_j |a_{ij}|^2 \right)\left(\sum_j |x_j|^2 \right)$
I know that this is by Cauchy-Schwartz, but should not $a_{ij}x_j$ be inside an absolute value to apply Cauchy Schwartz?
Answer: It is the entire inner product on the LHS that lies inside the absolute value for Cauchy–Schwarz, not the individual products. The following, which corresponds to what you think is true, is not Cauchy–Schwarz:
$$\langle|\mathbf u|,|\mathbf v|\rangle^2\le\langle\mathbf u,\mathbf u\rangle\langle\mathbf v,\mathbf v\rangle$$
This is the real Cauchy–Schwarz:
$$|\langle\mathbf u,\mathbf v\rangle|^2\le\langle\mathbf u,\mathbf u\rangle\langle\mathbf v,\mathbf v\rangle$$
Comment: I am unable to get your point of view …. could you please explain it in terms of the terms given in our problem?
Comment: @Mathstupid Here $\mathbf u$ is the vector of $a_{ij}$ for a fixed $i$, and $\mathbf v$ is the vector of $x_j$.


Sets, Functors and Eq confusion

Question: A discussion came up at work recently about Sets, which in Scala support the zip method and how this can lead to bugs, e.g.
scala> val words = Set("one", "two", "three")
scala> words zip (words map (_.length))
res1: Set[(java.lang.String, Int)] = Set((one,3), (two,5))

I think it's pretty clear that Sets  shouldn't support a zip operation, since the elements are not ordered. However, it was suggested that the problem is that Set isn't really a functor, and shouldn't have a map method. Certainly, you can get yourself into trouble by mapping over a set. Switching to Haskell now,
data AlwaysEqual a = Wrap { unWrap :: a }

instance Eq (AlwaysEqual a) where
    _ == _ = True

instance Ord (AlwaysEqual a) where
    compare _ _ = EQ

and now in ghci
ghci> import Data.Set as Set
ghci> let nums = Set.fromList [1, 2, 3]
ghci> Set.map unWrap $ Set.map Wrap $ nums
fromList [3]
ghci> Set.map (unWrap . Wrap) nums
fromList [1, 2, 3]

So Set fails to satisfy the functor law
    fmap f . fmap g = fmap (f . g)

It can be argued that this is not a failing of the map operation on Sets, but a failing of the Eq instance that we defined, because it doesn't respect the substitution law, namely that for two instances of Eq on A and B  and a mapping f : A -> B then
    if x == y (on A) then f x == f y (on B)

which doesn't hold for AlwaysEqual (e.g. consider f = unWrap).
Is the substition law a sensible law for the Eq type that we should try to respect? Certainly, other equality laws are respected by our AlwaysEqual type (symmetry, transitivity and reflexivity are trivially satisfied) so substitution is the only place that we can get into trouble.
To me, substition seems like a very desirable property for the Eq class. On the other hand, some comments on a recent Reddit discussion include

"Substitution seems stronger than necessary, and is basically quotienting the type, putting requirements on every function using the type."
-- godofpumpkins
"I also really don't want substitution/congruence since there are many legitimate uses for values which we want to equate but are somehow distinguishable."
-- sclv
"Substitution only holds for structural equality, but nothing insists Eq is structural."
-- edwardkmett

These three are all pretty well known in the Haskell community, so I'd be hesitant to go against them and insist on substitability for my Eq types!
Another argument against Set being a Functor - it is widely accepted that being a Functor allows you to transform the "elements" of a "collection" while preserving the shape. For example, this quote on the Haskell wiki (note that Traversable is a generalization of Functor)

"Where Foldable gives you the ability to go through the structure processing the elements but throwing away the shape, Traversable allows you to do that whilst preserving the shape and, e.g., putting new values in."
"Traversable is about preserving the structure exactly as-is."

and in Real World Haskell

"...[A] functor must preserve shape. The structure of a collection should not be affected by a functor; only the values that it contains should change."

Clearly, any functor instance for Set has the possibility to change the shape, by reducing the number of elements in the set.
But it seems as though Sets really should be functors (ignoring the Ord requirement for the moment - I see that as an artificial restriction imposed by our desire to work efficiently with sets, not an absolute requirement for any set. For example, sets of functions are a perfectly sensible thing to consider. In any case, Oleg has shown how to write efficient Functor and Monad instances for Set that don't require an Ord constraint). There are just too many nice uses for them (the same is true for the non-existant Monad instance).
Can anyone clear up this mess? Should Set be a Functor? If so, what does one do about the potential for breaking the Functor laws? What should the laws for Eq be, and how do they interact with the laws for Functor and the Set instance in particular?
Comment: Maybe i'm wrong, but i don't think that collections in Scala are meant to be functors, actually there are no such things in Scala as Functors, Monads, Applicatives and other stuff in the standard library, cause prof. Odersky didn't want to have them. Maybe in Haskell it's essential for the language, but in Scala, i think, Set is just a Set and if you need Functors, Monads, etc.. use Scalaz
Comment: @levy Rather than "Functor" you can just read "the set of types that supports a `map` operation". That's all that `Functor` is (well, that plus some laws).
Comment: I think we can say `Set` is a functor on the subcategory whose objects are types with a sane `Eq`/`Ord` instance (here "sane" includes substitutability).
Comment: @ChrisTaylor I agree with you, but the idea behind map in Scala, and behind map in Haskell are different. In Haskell map is related to Functors, Arrows and all that mathematical stuff from CatThreory, but in Scala map is just "take this `addOne` function and apply it to each `Int`". I doubt that biggest part of Scala Devs thinks about `flatMap/bind` in terms of Monads and some abstraction over computation flow with context, it's just call function and from `List[List[A]]` make `List[A]`.
Comment: The `map` for `Set` is not the `Functor` map!
Comment: It would be a nice point for [ML](https://groups.google.com/forum/#!forum/scala-language) rather than stackoverflow Q/A, at least a *Set zip is harmful* part.
Comment: Feel free to cross-post it there. I agree that this question may be a bit too subjective, or a bit too broad, for SO, but I thought I'd toss it out there anyway and see if it sticks.
Comment: Do have any example to show the usefulness of Set being a `Functor`. IMHO Set doesn't fit to be `Functor`.
Comment: @Ankur Certainly. Say you are writing a library for doing certain AI calculations, which require you to "score" some collection of possible actions. You don't know if you'll get a list of actions, or a set, or a queue - you just know that you'll get a collection with some elements, so you write your `score` function to accept any `Functor`. If `Set` is a `Functor`, you can get more efficient code since actions with identical scores are discarded as you go. If you used a list, you would have to manually discard identical scores at the end (using `List.nub` for example).
Comment: @ChrisTaylor: I don't think I will generalize `get a collection with some elements` to a `Functor`. `IO`, `Maybe` and other types which are not collection are `Functor` and I am not sure if `Functor` has anything to do with collection of elements. In this case I will probably use some other generalization to represent a collection of elements.
Comment: @ChrisTaylor Similar situation with map in Set, it doesn't matter wether it is a functor or not, i just want to add 1 to each number in the this Set, that's all
Comment: I've always been mystified by the fact that `Eq` is Haskell is not necessarily structural, so for other people like me, this other answer helped me to understand that: http://stackoverflow.com/a/12504423/293735

Once you accept that, it's relatively obvious how the useful (for algebraic reasoning and optimizations) Functor laws cannot be relied upon for `Set`s. Another `RestrictedFunctor` typeclass could be defined for such Functors that don't have such guarantees, but the Haskell Functor is a different beast. (or at least this is my rationalization)
Answer:
Another argument against Set being a Functor - it is widely accepted that being a Functor allows you to transform the "elements" of a "collection" while preserving the shape. [...] Clearly, any functor instance for Set has the possibility to change the shape, by reducing the number of elements in the set.

I'm afraid that this is a case of taking the "shape" analogy as a defining condition when it is not.  Mathematically speaking, there is such a thing as the power set functor.  From Wikipedia:

Power sets: The power set functor P : Set → Set maps each set to its power set and each function f : X → Y to the map which sends U ⊆ X to its image f(U) ⊆ Y.

The function P(f) (fmap f in the power set functor) does not preserve the size of its argument set, yet this is nonetheless a functor.
If you want an ill-considered intuitive analogy, we could say this: in a structure like a list, each element "cares" about its relationship to the other elements, and would be "offended" if a false functor were to break that relationship.  But a set is the limiting case: a structure whose elements are indifferent to each other, so there is very little you can do to "offend" them; the only thing is if a false functor were to map a set that contains that element to a result that doesn't include its "voice."
(Ok, I'll shut up now...)

EDIT: I truncated the following bits when I quoted you at the top of my answer:

For example, this quote on the Haskell wiki (note that Traversable is a generalization of Functor)

"Where Foldable gives you the ability to go through the structure processing the elements but throwing away the shape, Traversable allows you to do that whilst preserving the shape and, e.g., putting new values in."
"Traversable is about preserving the structure exactly as-is."

Here's I'd remark that Traversable is a kind of specialized Functor, not a "generalization" of it.  One of the key facts about any Traversable (or, actually, about Foldable, which Traversable extends) is that it requires that the elements of any structure have a linear order—you can turn any Traversable into a list of its elements (with Foldable.toList).
Another, less obvious fact about Traversable is that the following functions exist (adapted from Gibbons & Oliveira, "The Essence of the Iterator Pattern"):
-- | A "shape" is a Traversable structure with "no content,"
-- i.e., () at all locations.
type Shape t = t ()

-- | "Contents" without a shape are lists of elements.
type Contents a = [a]

shape :: Traversable t => t a -> Shape t
shape = fmap (const ())

contents :: Traversable t => t a -> Contents a
contents = Foldable.toList

-- | This function reconstructs any Traversable from its Shape and
-- Contents.  Law:
--
-- > reassemble (shape xs) (contents xs) == Just xs
--
-- See Gibbons & Oliveira for implementation.  Or do it as an exercise.
-- Hint: use the State monad...
--
reassemble :: Traversable t => Shape t -> Contents a -> Maybe (t a)

A Traversable instance for sets would violate the proposed law, because all non-empty sets would have the same Shape—the set whose Contents is [()].  From this it should be easy to prove that whenever you try to reassemble a set you would only ever get the empty set or a singleton back.
Lesson?  Traversable "preserves shape" in a very specific, stronger sense than Functor does.
Comment: This is interesting, but so is `Set` a `Functor`, according to your answer?
1. The only difference between `Set` and powerset is that powerset does not use `Eq` but actual equality, which is guaranteed to be substitutive.
2. "`Functor` preserves shape" in the sense given by functor laws — it just applies the function to the elements. As observed, `Set` is only a functor assuming substitutivity of `Eq`.
Answer: Set is "just" a functor (not a Functor) from the subcategory of Hask where Eq is "nice" (i.e. the subcategory where congruence, substitution, holds). If constraint kinds were around from way back then perhaps set would be a Functor of some kind.
Comment: @Blaisorblade surprise!  As of 7.10, `MonadPlus` is an empty typeclass (well, empty save for with redundant operations that are only aliases of their equivalent generalizations) that only provides laws :)
Comment: Thanks - I think this is a nice way of looking at it. I tend to get too hung up on functors from Hask to Hask and forget  about the rest of them...
Comment: At the very least `Contravariant` functors are nice to have in your toolbox, as they have a very nice Haskell representation. The subcategory ones are good thinking tools, though.
Comment: IMHO, `instance SubstitutiveEq e => Functor (Set e)` would be enough, if `SubstitutiveEq` were an operationless typeclass with only laws (something I've never seen in Haskell).
Answer: Well, Set can be treated as a covariant functor, and as a contravariant functor; usually it's a covariant functor. And for it to behave regarding equality one has to make sure that whatever the implementation, it does.
Regarding Set.zip - it is nonsense. As well as Set.head (you have it in Scala). It should not exist.
Comment: `Set.head` is actually useful if you have a non-empty set and you want to get an arbitrary element of that set, doesn't matter which. In case of the one-element set, it's the only element of that set.
Of course, the name `head` isn't the most fortunate. It should be called `Set.arbitrary` or something.

Sets, Functors and Eq confusion


Brokers for Celery Executor in Airflow

Question: Is it possible to use the following brokers instead of Redis or RabbitMQ:

Zookeeper
IBM MQ
Kafka
Megacache

If so, how would I be able to use it ?
Thanks
Answer: As per Celery documentation in a part of transport brokers support, RabbitMQ and Redis are fully featured and qualified as a stable solutions.
According to the list you've provided for any alternatives around, Zookeper might be also adopted as an Celery executor in Airflow but only as an experimental option with some functional limitations.
Installation details for Zookeper broker implementation you can find here.
Using Python package:
 $ pip install "celery[zookeeper]"

You can check out all the available extensions in the source setup.py code.
Referencing Airflow documentation:

CeleryExecutor is one of the ways you can scale out the number of workers. For this to work, you need to setup a Celery backend
  (RabbitMQ, Redis, …) and change your airflow.cfg to point the executor parameter to CeleryExecutor and provide the related Celery
  settings.

After particular Celery backend being prepared, adjust appropriate settings in airflow.cfg file, for any incoming doubts refer to this example.

Brokers for Celery Executor in Airflow


"private" variable in c

Question: Embedded Software where I can just use C.
I am reading the current revision of the circuit board out of an EEPROM.
Based on that revision-number the maximum supported current to the load can be defined.
Now I need that information on plenty of locations in the code (but read-only).
Only the function that reads the EEPROM should be allowed to write the value.
All other functions etc. must not change this value, an error could result in
damaging the load or board.
Is there a way in c to do this? (NOT C++)
Comment: How about "programming discipline"?
Comment: How about making it a global `static` variable in a source file, and have one function to set it, and one to get it? Then at least the variable can't be accessed and written to directly.
Comment: It would be useful if you were to include some existing code - not least so we can know what data type is used to represent the board revision.
Comment: I want to write good code, where you can't damage things if you don't know what you are doing
Comment: You don't really want to let people who don't know what they are doing to have too much freedom to code for you. If they don't know what they are doing and you let them do it, they will damage things sooner or later.
Answer: For a simple single-core embedded system, this is done by declaring the variable static at file scope in the EEPROM driver, such as:
static uint16_t max_current;

The driver can then access this directly, but static prevents any other module from doing so. You give them read-only access by providing a getter function in the same driver:
uint16_t get_max_current (void)
{
  return max_current;
}

Comment: It should be noted that this doesn't actually prevent other code from changing it; what it does is make it hard for other code to *find* the value in memory to change.  Assuming you are not talking about malicious code that searches for it, the key distinction would be that something that does out of bound memory access could still *accidentally* corrupt the value in memory, likely along with many other values.  There's no actual memory protection involved here, just declining to provide a ready path to locate it for direct reading or writing.
Comment: @Lundin - I specifically said "assuming you are **not** talking about malicious code" and gave the example of buggy code accidental overwriting data memory.  That said, flash memory is not ultimately protection against malicious code.  Many modern MCUs (with a few notable exceptions like AVR) can execute from RAM, even those that cannot may be vulnerable to "return oriented programing" and pretty much any hardware is vulnerable to sleeper code inserted by a corrupted build process or toolchain.
Comment: why is static needed
Comment: If you don't use the `static` keyword then a other file could still access the variable. The `static` makes that variable local to the file it's in. (Not to be confused to when it's used inside a function.)
Comment: @Muperman :  Note that whatever causes `max_current` to be initialised (not shown here) _must_ be called before `get_max_current()` is ever called, otherwise you will get zero, which may or may not be a valid revision, and acting on it may cause incorrect behaviour.  Given that I would suggest that the solution may not provide the robustness you asked for.
Comment: TBH it's a bit worrying that you don't know what a static variable is :-o
Comment: @ChrisStratton That's a non-issue since modern microcontrollers execute code from flash and don't allow flash to be reprogrammed before getting erased first. So there is no way to get malicious code into the MCU to begin with, unless someone implemented a backdoor through a bootloader. Hence "eeprom" and "embedded"; we aren't talking about your PC here.
Answer: If you use a function with a static local and assign it on first use directly from the EEPROM, thereafter the previously initialised value will be returned without re-reading the EEPROM.
Something like (modify the EEPROM read to suit your actual interface):
int getBoardRevsion( void )
{
    static int board_revision = -1 ;
    if( board_revision == -1 )
    {
        board_revision = (int)readEeprom( BOARD_REVISION_OFFSET, 1) ;
    }

    return board_revision ;
}

board_revision is entirely private to all except getBoardRevsion(), while strict read-only access is enforced through the function.
Comment: Glad to see you didn't permanently delete it. Was just about to suggest you do what you just did, came to me as an afterthought :)
Answer: Use get/set functions. They are a good convention as well. For example (not including header files):
eeprom.c:
static uint16_t value = 0;

void eeprom_init(void){
    value = ...;
}

uint16_t get_EEPROM_value(void){return value;}

something_else.c:
#include "eeprom.h"

int main(void){
    if(get_EEPROM_value() == ...){...}
}

Comment: `import` -> `#include`.
Comment: The `import`, probably just a typo?
Comment: Which language is this, Java?
Comment: It's very minimal C. But my guess is that you found some syntax error to prove otherwise?
Comment: If understood correctly, you want to define a global variable inside eeprom.c and not show that variable inside the header eeprom.h. Now you implement the get-"method" and expose that in the eeprom.h?

I think this will do, thanks.
Comment: Exactly so Muperman. You effectively control how other module has access to the variable. @Lundin Seem I did make that mistake yes. Thanks! :)

"private" variable in c


Predicate Logic: Factoring of Quantifiers (Clarification of Concept)

Question: Suppose we have, $\exists x\, P(x) \rightarrow \exists x\,Q(x)$
I know this is logically equivalent to $\exists x\, P(x) \rightarrow \exists y\,Q(y)$
Now, suppose we factor the quantifiers:
$\forall x (P(x) \rightarrow \exists y\,Q(y))$
$\exists \, y\,\forall x\,\, (P(x) \rightarrow Q(y))$
Now, suppose we change the order of the factoring:
$\exists\, y(\exists x P(x) \rightarrow Q(y))$
$\exists \, y\,(\exists x\,\, (P(x) \rightarrow Q(y))$
$\forall\,x\,\exists y(\,(P(x) \rightarrow Q(y))$
My understanding is that where the quantifiers are of different types, the order matters. In this case, depending the order of the factoring, the final order of the quantifiers is different. So, it looks like my understanding of the factoring rules is incorrect. Could someone clarify?
Answer: It is true that you can't arbitrarily swap quantifiers; for instance, you can't in $\forall x\exists y(xRy)$. What you've found is that you can swap around the quantifiers in a formula that's equivalent to one in which neither quantifier is in the scope of the other. Essentially, the quantifiers in your formula don't "interact" at all, while in my example the values of $y$ that satisfy $xRy$ will in general depend on the particular value for $x$.
Answer: In this precise case, the order of factoring does not matter. (I asked the very same question to my logic professor last year). Since every application of a transformation rule results in an equivalent proposition, the order of the application of equivalence rules does not matter, even though it seems surprising that a sentence beginning with $\forall x\exists y$ should be equivalent to a proposition beginning with $\exists x \forall y$.
Answer: Suppose we have $\exists x P(x) \Rightarrow \exists y Q(y)$. This can be viewed as a function which given an $x$ and a proof of $P(x)$ gives you an $y$ with a proof of $Q(y)$.
So the proposition is a function $(x:X, P(x)) \rightarrow (y:X, Q(y))$. You then can use currification which gives you a function which looks like this $(x : X) \rightarrow P(x) \rightarrow ((y:X), Q(y))$ or like $\forall x \left(P(x) \rightarrow \exists y Q(y)\right)$. At loud, you can say

given an $x$ and given a proof of $P(x)$ the proposition gives you an $y$ with a proof of $Q(y)$

But then you're stuck. You can't factor out the $y$ because it depends on the proof you give for $P(x)$ and on $x$. If you don't give every argument (aka the proof that $P(x)$ holds), the function (implication) can't give you the result as it can't evaluate.


CSS Flex Box: varying the number of items on each row

Question: As an exercise, I am working on using Flex Box to implement the following layout:
┌───────────────────────────────┐
│ header                        │
└───────────────────────────────┘
┌─────┐ ┌───────────────────────┐
│ nav │ │ main                  │
│     │ │                       │
└─────┘ └───────────────────────┘
┌───────────────────────────────┐
│ footer                        │
└───────────────────────────────┘

My initial thought was to use:
body {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}

but I'm not sure what to do about the rest. Currently I use:
header,footer {
    width: 100%;
}
nav {
    flex-basis: 0;
    flex-grow: 1;
}
main {
    flex-basis: 0;
    flex-grow: 4;
}

with a bit of extra fine tuning.
This works, but it seems contrived.
An alternative solution would be to wrap the nav and main element inside a div, but I am trying to avoid that as it reduces flexibility.
The question is, what is the most appropriate way to have a layout with one element on some rows, and multiple elements on others?
Answer: The point is in flex-basis which needs to be defined, i.e. different from the initial value of auto, in order to enable wrapping of additional elements, if the prefered way is doing it without the additional parent element, which is perfectly fine:

$('button:first-of-type').click(function(){
  $('
3
').insertAfter('.insertAfter');
});

$('button:last-of-type').click(function(){
  $('div:not(.first)').toggleClass('flexBasis');
});
body {
  display: flex;
  flex-wrap: wrap;
}

body > * {text-align: center}

header, footer {
  flex-basis: 100%;
  background: #f88;
}

nav {
  flex-basis: 20%;
  background: lightgreen;
}

main {
  flex-basis: 80%;
  background: lightblue;
}

.first {
  flex-basis: 33.33%;
  background: lightgray;
}

div {
  flex: 1; /* not enough */
  background: gray;
}

.flexBasis {
  flex: 1 25%; /* enough */
}

.insertAfter ~ div {color: #fff; background: #000}

<button>Add</button>
<button>Toggle flex-basis</button>

Header
Nav
Main

1

1

1

2

2

2

2

Footer
Answer: Two thing you should add:
1) Make the body display:flex to turn it into a flex container
2) Use the flex shorthand to indicate the flex grow and basis to the header and footer. By making the basis 100vw, you make does flex items 100% of the viewport width
flex: 1 100vw;

Hope this helps :)

body {
    display:flex;
    flex-direction: row;
    flex-wrap: wrap;
    background: red;
    margin:0;
}

header,footer {
    width: 100%;
    background: blue;
    flex: 1 100vw;
}
nav {
    flex-basis: 0;
    flex-grow: 1;
     background: green;
}
main {
    flex-basis: 0;
    flex-grow: 4;
     background: pink;
}

&nbsp
&nbsp
&nbsp
&nbsp

Comment: Sorry, I have already added the `display: flex` property. I hadn't mentioned it in my code as it was not part of the question. I'll add it to the question, though. As regards the width, I plan to use a different width. Thanks for your suggestions.
Comment: The width i mention are only for the header and footer. Is there something in my answer that wasn't as you asked. I asked this so i can fix it


No sound after boot

Question: Whenever I start Ubuntu, the sound is missing and I have to key in the command alsamixer (where the third slider is zero) and increase the volume manually. How can I fix this?
PS : i don't mean startup sound i mean that the sound is missing altogather from  the songs/ movies everything.
Comment: Is [this](http://askubuntu.com/questions/6162/sound-broadcast-icons-missing) the problem you're having?
Comment: no my problem is that i am not getting any sound
Comment: Was this answer helpful for you ? Did it solve your problem ?
Answer: Please check System -> Preferences -> Sound.
Check if 'alert volume' in sound effects tab and output volume in 'output' tab is not in mute or near to 0%.
Answer: I have had this problem too. In 11.04 and 11.10. No icons are missing, and all volume sliders are up and not muted. Sometimes if I switch to a different hardware profile and then switch back, it works again. Is there a log file I could check to see what might exactly be causing this? Or a command I could execute in Terminal to diagnose the problem?
Answer: I'm not having this problem on my main PC, but I have it on several of the PCs I have setup for others
It is the same issue as discussed here:
How can I automatically mute the volume at every boot?
Somewhere between  "lightdm"  and  "alsactl restore"  (which happens on startup), some PCs are set to inbuilt speaker mute.  This happens on boot, and any settings saved from previous session are lost.
STILL WORKING TO RESOLVE ..

No sound after boot


Random string generation php

Question: Below is the code for random string generation, it is working but there is some problem here which I at the moment cant figure out what happens here is that it always returns me value of length 1 ,I am expecting a random string of length 10. Also I am passing 10 as length. Kindly guide me what am I doing wrong here.
<?php
function random_string($length) {
    $len = $length;
    $base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";
    $max = strlen($base) - 1;
    $activatecode = '';
    mt_srand((double) microtime() * 1000000);

    while (strlen($activatecode) < $len + 1) {
        $activatecode.=$base{mt_rand(0, $max)};

        return $activatecode;
    }
}

?>

Answer: you return from within the while, causing the while-loop to only be run once and returning the result at that point (which is only 1 character)
Move your return-line 1 down (out of the while-loop) and it should work.
Comment: /facepalm that worked lol sopme time copy pastes are worst then you think THx for answering
Answer: Seem to work fie for me.
Fix you code up a bit:
function random_string($length) {
 $len = $length;
 $base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";
 $max = strlen($base) - 1;
 $activatecode = '';
 mt_srand((double) microtime() * 1000000);

 while (strlen($activatecode) < $len + 1) {
    $activatecode.=$base[mt_rand(0, $max)];
 }

    return $activatecode;
}

Demo: http://codepad.org/gq0lqmB3
Answer: Your return statement is inside of the while loop.
Move it outside to be after the end of the while loop.
Answer: Your return statement is inside of the while loop making it to exit the function immediately, move it to the end of the function.
Some additional remarks:

No need for mt_srand((double) microtime() * 1000000); nowadays.
Don't use strlen, you don't need it.
{} substring syntax is outdated.

Example:
<?php
function random_string($length)
{
    $length = (int) $length;
    if ($length < 1) return '';

    $base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";
    $max = strlen($base) - 1;

    $string = '';
    while ($len--)
    {
        $string .= $base[mt_rand(0, $max)];
    }
    return $string;
}
?>

I suggest you add a maximum length as well, just in case.
Answer: Just curious, whats the point of multiplying microtime() * 1000000?
each time microtime() is called it will produce a different seed!

Random string generation php


Can skylanders mess up my laptop?

Question: my daughter put all her skylanders on top of my perfectly wonderful laptop and it crashed the next morning. Coincidence or not?
Comment: I say coincidence. all the Skylanders contain are NFC chips. I bet a cellphone can do more damage than that when placed on a laptop...
Comment: Completely coincidental.  You're stretching for a reason, since most crashes don't tell you what went wrong.
Answer: So you mean she physically put the toys on top of the laptop, correct? The Skylanders toys work on RFID chips, and wouldn't have any effect on your laptop. Though you didn't explain in what way the laptop crashed, or really anything about the laptop itself, this would be purely coincidental.

Can skylanders mess up my laptop?


Probability of winning the world series (Giants vs Yankees)

Question:
What is the probability that the Giants will win the World Series against the Yankees if the probability that they win a given game is 0.6?  Winning 4 games means you win the series (7 total games).

I'm thinking binomial probability given they have to win "at least 4 games":
$P(x) = {7\choose4}(0.6)^4(0.4)^3 + {7\choose5}(0.6)^5(0.4)^2 + {7\choose6}(0.6)^6(0.4)^1 + {7\choose7}(0.6)^7(0.4)^0$
Am I on the right track?
Comment: You are correct. Another way of thinking this is if Giant wins in first 4 games, it's $(0.6)^4$. If wins in first $5$ games, it's ${4\choose 1}(0.6)^4(0.4)^1$. If wins in first $6$ games, it's ${5\choose 2}(0.6)^4(0.4)^2$. If wins in first $7$ games, it's ${6\choose 3}(0.6)^4(0.4)^3$. This sum matches the result of your answer as well.
Answer: Yes, you are correct, and the method you used is the simplest for such problems.
The logic is that once the Giants win $4$ games at any stage, they win, whatever happens later.


SOAP PHP Request

Question: I am trying to turn this example request into PHP SOAP functions. This is what support told me for this soap server that I needed. I barely have any SOAP experience and I can't figure out how to structure this in PHP.
<CreateCustomerRequest xmlns="http://schemas.datacontract.org/2004/07/BillingTree.ApiService.Contract" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <MerchantCredentials>
        <CertId></CertId>
        <Password></Password>
        <UserName></UserName>
        <Zid></Zid>
    </MerchantCredentials>
    <Customer>
        <Address>
            <AddressLine1></AddressLine1>
            <AddressLine2 i:nil="true"/>
            <AddressLine3 i:nil="true"/>
            <City>Los Angeles</City>
            <Country>USA</Country>
            <Province i:nil="true"/>
            <State>CA</State>
            <ZipCode>85284</ZipCode>
        </Address>
        <Department></Department>
        <Email></Email>
        <Fax i:nil="true"/>
        <FirstName></FirstName>
        <Id></Id>
        <LastName></LastName>
        <Phone></Phone>
        <Status>Active</Status>
        <Title></Title>
    </Customer>
</CreateCustomerRequest>

Comment: You should really make some attempt before asking for help. If you _have_ made an attempt, show what you tried.
Comment: I have tried all kinds of things. Nothing has really gotten close.
Answer: If you're new to SOAP, then you should try using a WSDL to PHP generator that will ease you the SOAP request construction. You can try the project PackageGenerator so you'll end up with a full PHP SDK of the SOAP Web Service and a tutorial file as a starting guide.
Answer: < ? php
// $client = new SoapClient('http://localhost/php/soap/math.wsdl');
$client = new SoapClient("http://localhost/php/soap/soap_server.php? WSDL");
try{
  $result = $client->div(8, 2);
  print "The answer is: $result";
}catch(SoapFault $e){
  print "Sorry an error was caught executing your request: {$e->getMessage()}";
}
?>

you can use like this ,a very basic example

SOAP PHP Request


Go get private bitbucket repo giving 403 forbidden

Question: On execution of
go get bitbucket.org/../..
I get this error
yash.jain projectname % go get bitbucket.org/../..
go: bitbucket.org/../..
https://api.bitbucket.org/2.0/repositories/../..?fields=scm: 403 Forbidden
go: error loading module requirements

What I tried

Setup the ssh key (Working as expected, tested by pushing and pulling the code)

Set the go env variables to this:
 GOPRIVATE=""
 GOPROXY="direct"
 GOSUMDB="off"

.gitconfig looks like this
 [url "email@example.com:"]
     insteadOf = https://bitbucket.org/
 [user]
     email = firstname.lastname@example.com
     name = yashjain

Added keys to ssh-agent
 ssh-add -l
 ssh-add -k

.ssh/config file looks like this
 Host bitbucket.org
   HostName bitbucket.org
   User git
   IdentityFile ~/.ssh/id_rsa
   UseKeychain yes
   StrictHostKeyChecking no

Still, I get the same error.
Please let me know If I'm doing something wrong.
Comment: Have you tried use `GOPRIVATE=*.bitbucket.org` ?
Comment: @ArunaHerath That would apply to https URLs, but this configuration is made to use SSH URLs only.
Comment: Yes I tried this as well. But get same error.
Comment: I still belive its misconfiguration, try `git config --global url."git@bitbucket.".insteadOf "https://bitbucket.org/"` and `export GOPRIVATE=bitbucket.org/`
Comment: This is also not working
Comment: does your project name have space or some special characters? As I remember it caused some problems
Comment: No, the project name does not have any space or special character. It's just a single work project name @Vrangz
Comment: I'm also using external repo and in my config there is `[url "https://:@/_git/]" \n insteadOf = `
Maybe go this way using https using sshKey after `:` and before `@`
Comment: Did you resolve this issue? @yashjain12yj
Comment: Check if you have a .netrc file with wrong password at home directory
Comment: Oh, yeah. Thanks.
Comment: Also try https://community.atlassian.com/t5/Bitbucket-questions/How-do-I-run-go-get-on-a-private-repo/qaq-p/1385040 (did you restart ssh-agent)?
Answer: These are the steps I tried to make it work.

Setup SSH key and connect to bitbucket. I used sourcetree gui by bitbucket to connect using ssh.
Set the GOPRIVATE=bitbucket.org/<orgname>/*

* is to allow all the repo of the org.
After these 2 steps I am able to import the package.

Note: Sourcetree is only available to Mac and Windows.

Using Commnd Line: For Linux/Mac/Windows:

git config --global url."firstname.lastname@example.com:".insteadOf "https://bitbucket.org/"
Set the GOPRIVATE=bitbucket.org/<orgname>/*

Update
You might receive the 404 error even after above configuration.
Error
reading https://api.bitbucket.org/2.0/repositories/xyz/privaterepo?fields=scm: 404 Not Found

Bitbucket recently update their APIs for private repository and due to which certain golang version breaks.

Users who do not have access to a private repository will receive 404 (not found) response codes instead of 403 (forbidden) response codes to mask the existence of a private repository at a given URL path.
Rolling out these changes will break previous versions of Go due to the fact that the go command relies on a 403 response to fetch repositories hosted on Bitbucket Cloud.
To ensure that you will not run into any issues, update GoLang to the latest version.

Ensure you are on a supported version of GoLang: 1.18, 1.17, or 1.16.
If you are using 1.17 or 1.16, ensure you are on the latest patch (1.17.7 or 1.16.14)

This will be in effect from June 1st 2022.
Changes to Bitbucket API Requires Latest Version of Go
Answer: There are Two ways I normally resolve this. But, for this you need to configure bitbucket with SSH.
1. Edit git.config
edit the global .gitconfig
nano /home/user/.gitconfig
add following lines
[url "firstname.lastname@example.com:"] insteadOf = https://bitbucket.org/

2. Export GOPRIVATE
export GOPRIVATE=bitbucket.org/<your repo>

Comment: Thanks @nipuna for the answer. It worked but there are a few more things needs to be done. git config is not required in my case.
Answer: Check first what ssh -Tv firstname.lastname@example.com returns, specifically the user mentioned in the Welcome message: it could be an account, which does not have access to the private repository.
As mentioned in "What's the proper way to "go get" a private repository?", try also with a private ssh key not protected by a passphrase, to make sure there is no prompt for said passphrase in the middle of the go get process.
Comment: The `ssh` already configured and yet was unable to get it.
Comment: @ShubhamChadokar Is the private key protected by a passphrase?
Comment: Yes it is protected.
Comment: @ShubhamChadokar Can you try, for testing, with a non-protected private key?
Comment: I tried but it is not working for that also.
Comment: The another answer by nipona worked. I have to set GOPRIVATE variable
Comment: @ShubhamChadokar Great! What other things needed to be done in addition of setting `GOPRIVATE` ?
Comment: Yes. Just added a new answer. Check it out. I added the steps I took.
Answer: you can do it via Sourcetree as well. follow the steps below:

Download and install Sourcetree
configure your bitbucket ssh key in Sourcetree inside connection
You will be able to see your account in accounts section. Something like below

Next step is to add your GOPRIVATE env variable
for that run this command

go env -w GOPRIVATE="bitbucket.org/<repo>/*"


Socket comunication Between External Server, Own Server and React Client

Question: I have a server running on express. On this server I connect with an external socket server "wss://..."
I can get the data from this external websocket, but the question is how i send that data to my front end on realtime?
What is the best option?
Comment: is your react client static or ssr?
Answer: I think the best solution is to establish a connection server - external ws and then I created another connection between my server and the front end.
This works fine.


(Spoiler) Valiant Hearts, did Emile know about Karl?

Question: Alright, the title is spoiler free and shows a bit what I'm on about.
Now the actual question, which contains major spoilers (Really, if you haven't played the game yet, close this page now and go do so):

When Emile died, did he know Karl was still alive? He thought Karl got killed at the POW camp. As far as I know Emile never got to know Karl was still alive. Maybe I just missed something in the story though. It would be pretty sad if Emile did die with the thought of Karl being dead...

It seems like this is the first question about this game on this site, which is a shame. It really is a masterpiece.
Comment: There really isn't too much need to ask any questions about this game. It's fairly straight forward (in regards to your 'first question' comment).
Comment: @deutschZuid I have to agree on that, but I'm amazed by the simple things people will still have questions about.
Answer: I have to think so, if you listen to his last words he says that he let Karl down, but that his sacrifice was not in vain because blah blah blah honor or something (too lazy to write it all you get the point). So he thinks that Karl is still dead which is really just insanely depressing, but that's such a central theme of the game that war is loss


Debugging with VS2013 & IIS 8

Question: I'm sorry if this seems a very basic question but its something I've not struggled with in the past but seem to be having massive problems with now.
I have recently got a new dev laptop running Windows 8, I have installed IIS 8 as well as upgrading to Visual Studio 2013 from VS2010. I've been working on a new project using MVC5 and EF6 which sits in the inetpub/wwwroot/mynewproject folder.
The problem Im having though it attaching a debugger to IIS (w3wp.exe) in VS2010 it was simple the w3wp process showed in the available processes list I selected it and away we went. In VS2013 it doesn't show in the list by default I have to tick the Show processes from all users checkbox and when I try to attach I get a error stating the following:
Unable to attach to the process. The microsoft visual studio remote debugging monitor (MSVSMON.exe) does not appear to be running on the remote computer. This may be caused beacuse a firewall is preventing communication to the remote computer. blah blah....
All I want to do is debug my project by attaching to the w3wp process, is there some basic configuration I'm missing here?
Any help would be appreciated.
Comment: alternative:see project properties. Web Tab. Set the project to use Local IIS instead of Express. You can then Launch IIS using the debug run option. It attaches for you.
Comment: Are you attaching to a remote computer, or the local one? Are you running Visual Studio as an administrator?
Answer: You need to run Visual Studio as Administrator in order to attach to the w3wp.exe process.
Comment: this answer saved me a lot of time

Debugging with VS2013 & IIS 8


Rails 2 + SQLite 3 - can ID field be zero?

Question: My problem: I'm writing a flex frontend to a rails app, and I'm having problems in managing NULL database values.. so to avoid problems I just don't allow NULL.
Now, for foreign keys, would 0 be fine? No chance that a record be assigned ID 0, right?
Maybe I could somehow tell rails to skip foreign key updates if input is 0..
Answer: If there's no matching row with a foreign key value of 0, it should work fine, because then there's nothing to update.


Unable to install Flash Builder 4 plugin - Configuration Error 6

Question: I'm trying to install the Flash Builder 4 plugin for eclipse on my Mac.
The installation completes but when i launch eclipse i get the following pop-up message, after which eclipse quits unexpectedly.

I'm using the eclipse-jee-galileo-SR2-macosx-carbon version of eclipse.
Answer: I ran into the same issue.  The solution on this site worked for me:
http://www.webappsolution.com/wordpress/2010/10/08/mac-flash-builder-plugin-install-error-6-fix/


How to select (copy) an output in terminal without mouse

Question: It seems like a typical way that you have some output in the terminal and if you want to select certain phrase you use your mouse to copy it, but is there any way to select without using mouse? For example, I input ls, and get a list of files, and I want to select the second file (second row), is there a way to copy the name without using mouse?
Comment: https://unix.stackexchange.com/questions/91863/terminal-copy-from-cli-without-using-mouse
Answer: Using tmux:
I use tmux in vi mode:

Go to copy mode (in my config Prefix+escape, Default Prefix is Ctrl+b)

In config file (~/.tmux.conf): bind Escape copy-mode

Move around (Using arrows)
Select your desire output (Start selection with Space)

In my config v: bind-key -T copy-mode-vi y send-keys -X begin-selection

Press Enter to copy the text.

In my config y: bind-key -T copy-mode-vi y send-keys -X copy-selection

Press Prefix+p to Paste.

Also create a key binding like this:
bind C-c run "tmux save-buffer - | xsel -bi"

So you can save the buffer into system clipboard by pressing Prefix+Ctrl+c.
I have add my configuration cause it's more like vim than default config.

Using commands:
Here is what I do:

Run the command (eg: ls -1)
Process the output to get my desired result
Pip it to xsel -bi

In your example:
$ ls -1 | sed -n 2p | xsel -bi

ls -1 prints the outputs each in one line
sed -n 2p get the second line
xsel has been used to copy the final result in clipboard.

If the command takes too long to run, first save the output to a file the process the output:
command > output
head -10 output | whatever | xsel -bi

Answer: The most common Linux terminals emulators cannot do this directly. There a 2 ones I am aware of, though.
One which exists for quite some time is Termite. It is rather spartanic, though (keyboard shortcuts not configurable, no multiple tabs).
Now there is a second one, which has these features named Mantid (which I' shamelessly advertising here :) ):
https://github.com/omgold/mantid-term
There isn't an Ubuntu build, yet, though, one Arch and RPM. You might try to build an RPM and convert to to deb using Alien, though.
Comment: I would like to try `mantid`, but I can not find any tutorial or manual. Is there any documentation out there? It would be good to know at least how it accomplishes the functionality requested in the question.
Comment: There is a manpage ('man mantid') and there are example configuration files in /usr/share/mantid. The manpage mostly documents the configuration options, and the active keybindings can be looked up in the config file.


How can I summon an ender dragon so it won't break blocks?

Question: I've been wanting to summon an Ender Dragon in the Overworld. But I don't want it to destroy my map. And I'm not going to turn the entire map into end stone and obsidian.
I have been using the <code>/summon EnderDragon</code> command. It will summon the dragon, but it just destroys everything.
Comment: Do you need the Ender Dragon to be able to move?
Comment: yes. it won't really be there to fight. but it will be there to look like a cool thing. it would be amazing for a map.
Answer: Summon a EnderDragon with no AI:
<code>/summon EnderDragon ~ ~ ~ {NoAI:1}
</code>
Mobs with no AI will not move and will not be animated.
Answer: If you don't need other mobs to be able to break stuff, then you can just do this before you summon the dragon:
<code>/gamerule mobGriefing false
</code>
But try using tab to autocomplete those words to make sure the capitalization is correct.
Answer: If you want the Ender Dragon to not do anything, summon it with this command:
<code>/summon EnderDragon ~ ~ ~ {NoAI:1}
</code>
But, then it is not animated and is pretty much just a statue. If you want the ender dragon to fly around, hurt people, but not damage blocks, use this gamerule and then summon a regular enderdragon:
<code>/gamerule mobGriefing false
</code>
You may want to use tab to make sure capitalization and spelling is correct.


I want to make just 1 api call every 5 minutes. How can I achieve this using gatling?

Question: I want to make only 1 api call every 5 minutes for "ConsumerApi.RunConsumer". The 'Flow1' should run continuously.
I hava a scenario class:
object ConsumerApi {
 //Defines the Consumer API call
   val PostConsumerApi = http("Consumer API")
     .post("http://abc.abc.com/v1/execute")
     .headers(Headers.applicationJson)
     .check(status is 200)

   val RunConsumer = scenario("Run the Consumer")
     .pace(5 minutes)
     .exitBlockOnFail {
      exec(PostConsumerApi)
   }
   }

Then I have the simulation class:
class TestFlow extends Simulation {
val httpConfTest = http.baseURL(Environment.apiHost)
val Scenarios = List(
Flow1.Flow1
   .inject(constantUsersPerSec(10) during (30 minutes))
   // Has to run for 30 minutes continuously.
,
ConsumerApi.RunConsumer
  .inject(constantUsersPerSec(1) during (30 minutes))
  // has to make only 1 api call every 5 minutes for duration of 30 minutes
 )
 setUp(Scenarios)
.protocols(httpConfTest).maxDuration(40 minutes)              .assertions(global.responseTime.max.lessThan(Environment.maxResponseTime.toInt))
.assertions(global.failedRequests.percent.lessThan(70))          .assertions(global.responseTime.percentile2.lessThan(Environment.maxResponseTime.toInt))

}
Answer: What about the following:
ConsumerApi.RunConsumer
  .inject(atOnceUsers(1),
          nothingFor(5 minutes),
          atOnceUsers(1),
          nothingFor(5 minutes),
          //And so on...
    )
 )

You might want to take a look at the injection documentation for a detailed description of the available injection building blocks.


google place autocomplete country restriction on change

Question: i am using places autocomplete to find routes in map and is working fine.
I have a select box with 2 countries US and AU.When the select box change
 i clear the autocomplete inputs and set the autocomplete
componentRestrictions = {country: iso_country} with the new country value form select box.
When i first load the script the default country is US and the autocomplete is not suggesting any place from AU. (so far so good)
When i first load the script and directly change the country to AU the autocomplete is suggesting and places from US. (which in not what i want)
Here is my code
/*
 * When initialize
 * i apply autocomplete to the inputs
 */

if($("#from_place").length)
{
        apply_autocomplete($("#from_place")[0],default_iso_code);
    }
    if($("#to_place").length)
{
        apply_autocomplete($("#to_place")[0],default_iso_code);
}

/*
 * When the Select Box change
 * i apply autocomplete to the inputs again with new iso_country
 */

$(document).on('change','#map_country_id',function()
{
    var iso_country = $(this).val();

    //clear from/to
    $("#from_place").val('');
    $("#to_place").val('');

    //autocomplete from/to with new country
    if($("#from_place").length)
    {
        apply_autocomplete($("#from_place")[0],iso_country);
    }
    if($("#to_place").length)
    {
            apply_autocomplete($("#to_place")[0],iso_country);
        }
});

/*
 * the function that applies the autocomplete
 *
 */

function apply_autocomplete(input,iso_country)
{
    var options = {
        componentRestrictions: {country: iso_country}
    };
    var autocomplete = new google.maps.places.Autocomplete(input, options);
    autocomplete.bindTo('bounds', map);
}

Can anyone help me fix this issue.
Answer: I believe the issue that you experience is because you try to create a new instance of Autocomplete on each change event of the select box. I would suggest not calling a new operator, but update the existing autocomplete instance properties using setOptions() method of Autocomplete class.
https://developers.google.com/maps/documentation/javascript/reference#Autocomplete
Have a look at the following example. I created two functions:

initAutocomplete() that is executed after loading Maps JavaScript API and sets the initial state of autocomplete elements
updateAutocomplete(countryCode) function that is called on each change event of select box

var default_iso_code = 'US';
var autocomplete_from, autocomplete_to;

function initAutocomplete() {
  var options = {
      componentRestrictions: {country: default_iso_code}
  };
  if($("#from_place").length) {
    autocomplete_from = new google.maps.places.Autocomplete($("#from_place")[0], options);
  }
  if($("#to_place").length) {
    autocomplete_to = new google.maps.places.Autocomplete($("#to_place")[0], options);
  }

  $(document).on('change','#map_country_id',function() {
    var iso_country = $(this).val();

    //clear from/to
    $("#from_place").val('');
    $("#to_place").val('');

    updateAutocomplete(iso_country);
  });
}

function updateAutocomplete(countryCode) {
  var options = {
      componentRestrictions: {country: countryCode}
  };
  if (autocomplete_from) {
    autocomplete_from.setOptions(options);
  }
  if (autocomplete_to) {
    autocomplete_to.setOptions(options);
  }
}
#from_place, #to_place {
  position: relative;
  width: 480px;
}
#autocomplete {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 99%;
}

      <select id="map_country_id">
        <option value="US">United States</option>
        <option value="AU">Australia</option>
      </select>

      <input id="from_place" placeholder="From place" type="text"></input>
      <input id="to_place" placeholder="To place" type="text"></input>

I hope this helps!


VCCodeModel not in VCCodeModel namespace?

Question: I am working with VCCodeModel in both C# and C++ CLR and I am having trouble getting the VCCodeModel type in to the CLR project.  I have added Microsoft.VisualStudio.VCCodemodel as a reference, but when I type:
Microsoft::VisualStudio::VCCodeModel::VCCodeModel

Visual Studio cannot see the code model.  All the other objects in the namespace like VCCodeFunction and VCFileCodeModel all work, but this one fails.
VCCodeModel Namespace
Is there some error that could cause this? I am using the default add-in project with C++ CLR as the chosen language and have added Microsoft.VisualStudio.VCCodeModel as a reference, and can successfully reference the other members in the space.  What could the issue be here?
Answer: You're running into a bug/quirk with the IDE's Intellisense for C++.  Even if you fully-qualify a class name, if the class name is the same as the namespace name, it will not show up in intellisense.  Nor will the IDE recognize it as a class-- the color of the class name stays black, not light blue like other classes.
Luckily, this is a purely cosmetic IDE problem. The class will still work fine in your code, will still compile, etc. You just have to type the name of the class yourself. :-)
Furthermore, the problem only extends to the class name, not the class's members. If you create a managed reference to VCCodeModel in your code, you'll be able to see intellisense for its members.
Here's a repro illustrating the intellisense issue in a plain unmanaged class :
namespace Foo
{
    public class Bar
    {
        public:
            static int x();
    };
    public class Foo
    {
        public:
            static int x();
    };
    public class Test
    {
        void ThisIsATest()
        {
            ::Foo::        // intellisense will show Bar and Test, but not Foo
            ::Foo::Foo::   // you will see "x" in intellisense
        }
    };
};

Comment: Feel embarassed that this is what the problem was, but thanks, it was simply not showing up in intellisense.


What is the minecraft command to kill all mobs except players and villagers?

Question: I want to make a command block to make sure that anything that spawns in a village, dies, except players and villagers. Please help me.
Answer: Since 1.13 you can use multiple of the same argument in one selector:
<code>/kill @e[type=!player,type=!villager]
</code>


Perl warning locale while I call psql

Question: I try to run postgresql on my Ubuntu server
myname@myserver:/home$ sudo -i -u postgres
postgres@myserver:~$ psql

perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
    LANGUAGE = "en_US:",
    LC_ALL = (unset),
    LC_CTYPE = "UTF-8",
    LANG = "en_US.UTF-8"
    are supported and installed on your system.
perl: warning: Falling back to a fallback locale ("en_US.UTF-8").

psql (9.5.14)
Type "help" for help.

postgres=# \q

I can have access to postgres but I have that perl warning.
Comment: @GunnarHjalmarsson I did it but I still get the same
Comment: Yeah, I typed too fast. ;) The problem is that `UTF-8` value for `LC_CTYPE`. No such locale name exists on Ubuntu. Do you possibly access the server remotely from a Mac machine?
Comment: @GunnarHjalmarsson yes exactly
Answer: A workaround which may work is to edit the ~/.profile file and add the line:
unset LC_CTYPE

That would prevent the invalid UTF-8 locale name from being present in the environment of the user session.
Comment: Where is the location of ` ~/.profile`
Comment: @emax: `/home/[username]/.profile`
Comment: the problem is that it does not recognize my keyboard anymore and I can not type properly.
Comment: @emax: That's another and probably unrelated problem. Maybe you want to ask a new question.

Perl warning locale while I call psql


'remote-server-timeout' exception as I try to connect to the server

Question: While trying to connect to openfire server through the following code :
Connection connection = new XMPPConnection("https://192.168.0.101:5222");
connection.connect();

I get an exception which says :
https://192.168.0.101:5222:5222 Exception: Could not connect
to https://192.168.0.101:5222:5222.; : remote-server-timeout(504)

What could be the reason for this ?
Note : I have allowed openfire fire server through the firewall.I also tried putting off the firewall, but the same result.Server is my own machine. The same machine on which I am trying to run the program.
Comment: @SuhailGupta you need not enter the port.`new XMPPConnection("192.168.0.101")` is fine
Comment: is your internet working... have checked it in the code..
Comment: @karan421 123 123..yeah it is working
Comment: ping the ip address and see the response time and also see whats coming using wireshark
Comment: which os your are using
Comment: @simmant `windows 7`.
Answer: You can use
Connection connection = new XMPPConnection("192.168.0.101");
connection.connect();

or if you want to specify the port
ConnectionConfiguration config = new ConnectionConfiguration("192.168.0.101", 5222);
Connection connection = new XMPPConnection(config);
connection.connect();

or similar, defaulting to port 5222
ConnectionConfiguration config = new ConnectionConfiguration("192.168.0.101");
Connection connection = new XMPPConnection(config);
connection.connect();

Answer: try this:
Connection connection = new XMPPConnection("localhost:5222");
connection.connect();

Answer: You can refer to this:
public XMPPConnection(String serviceName, CallbackHandler callbackHandler) {
    // Create the configuration for this new connection
    super(new ConnectionConfiguration(serviceName));
    config.setCompressionEnabled(false);
    config.setSASLAuthenticationEnabled(true);
    config.setDebuggerEnabled(DEBUG_ENABLED);
    config.setCallbackHandler(callbackHandler);
}

or with no callback handler for password prompting of the keystore:
public XMPPConnection(String serviceName) {
    // Create the configuration for this new connection
    super(new ConnectionConfiguration(serviceName));
    config.setCompressionEnabled(false);
    config.setSASLAuthenticationEnabled(true);
    config.setDebuggerEnabled(DEBUG_ENABLED);
}

or:
public XMPPConnection(ConnectionConfiguration config) {
    super(config);
}


How to fix or remove skylight on metal roof that was installed over shingles?

Question: The previous owners installed a metal roof over existing shingles less then 10 years ago so we were told the roof should last at least 20 more years. A heavy rain revealed a leak from our skylight. Once on the roof it became obviously that the metal roof was installed over the skylight and caulked off. No proper flanging was done (see pictures).
The ceiling with the leak is showing significant mold damage and likely encompasses a much larger area from the leak going on so long.
We know how to replace the ceiling, but the roof is another matter. The skylight probably needs to be either replaced or removed entirely, but we aren't sure if mold has also damaged the shingled portion of the roof. Since there is mold, we are hesitant to start poking around until we are ready to make repairs.
At this point would it be better to remove the skylight or is that not an option because the metal roof is resting on infrastructure of the shingles roof? Can we even replace a skylight on a roof like this?
Comment: Keep in mind that if the skylight is deleted, the "patch" of new roofing will be rather obvious. Even the same brand and same color code will look different because the existing steel has faded somewhat over 10 years and the new stuff won't have faded at all. If you're _really_ picky and it bothers you, you may be in for a replacement of the whole roof to make the color match. That's totally _your_ decision, though - just something to consider before deciding to scrap the skylight.
Answer: I am surprised this was not caught by the home inspection company when you purchased the home. And, if you did have an inspection there might be some liability on their part that could recover some of your repair costs.
Choices are to either remove roofing and install the skylite properly with correct flashings etc. And yes, this can be done properly. Another option is to remove the skylight and roofing around it and inspect/ and repair any damage to structure then close the hole and add roofing to cover where the skylite was. You will also need to repair/ match the ceiling finish inside.
Either of these options are pretty extensive and probably not DIY projects.
The only other (short term) option is more/ better caulking.
Comment: It's rare, but I'll agree that this may be a good time to call in a pro for this work. Skylights are notorious for leaking when not installed properly, plus the added "fun" of working with steel roofing. The good news is that unlike shingles, I'm betting that the steel can simply be unscrewed, then after replacement/repair of the skylight, most if not all can be screwed right back down without any new material being needed.
Comment: TBH, though, I'm not at all surprised that this wasn't caught by the pre-sale home inspection. My inspector looked at the roof (2 story farm house) from the ground, and had me look inside the attic because the attic access is tiny (I barely fit at the time) and the inspector, umm, wasn't tiny.
Answer:
A heavy rain revealed a leak from our skylight.

Yeah, that's just a universal problem with skylights.  They are very hard to seal, and the seals need a lot of maintenance, and they never get it.  Of course by the time the leak is bad enough to notice, the damage is done.

At this point would it be better to remove the skylight or is that not an option because the metal roof is resting on infrastructure of the shingles roof?

Well I'm no fan of skylights, so I'm biased toward removing it. You would need to fill the hole with framing and OSB/plywood so that it is level with the framing and OSB of the rest of the roof.  (so that when you finally remove those shingles, the OSB on the patch is level with the adjacent OSB; or if the OSB is rotted and needs to go, the framing on the patch is level with the original framing so the new OSB can go down without drama.)
The choice to lay it over the old bed of shingles is unfortunate. For the patch, you will need to come up with a spacer the same thickness as the old shingles, that is also removable for when the shingles go away. But that could be a long time.  Metal roofs last a really long time.
But the trick will be finding the same exact stamping of metal roof so that the new sheets just key right in.  Then only the 2 sheets need to be replaced.
Color match will be a problem, so painting the roof will be necessary if you don't like the stripe. Follow manufacturer advice for painting. By the way, if you like to save money on air conditioning and have a cooler attic, white is fantastic.


wxWebView Page Load Fails with no Internet Connection

Question: I am writing a windows application that uses a wxWebView (Trident) to display pages served from an internal server that binds to the localhost interface on an ephemeral port.  I have run into a problem where, if the host computer does not have any active external IP interfaces enabled (such as a laptop in airplane mode), the wxWebView instance refuses to load the page and sends a page load failure event with a string of "INET_E_DOWNLOAD_FAILURE".  When this happens, I can make an external browser (including internet explorer) load the page from my web server so I know that the loopback interface(s) are working.  Is there any way to configure the wxWebView instance so that it WILL load the page?
When I try this in the webview sample application, i can see the following in the log window:
<code>13:33:33: Navigation request to 'res://ieframe.dll/navcancl.htm#http://www.wxwidgets.org/' (target='')
13:33:33: Title changed; title='http://www.wxwidgets.org/'
13:33:33: Navigation complete; url='http://www.wxwidgets.org/'
13:33:33: Title changed; title='Navigation Canceled'
13:33:33: Document loaded; url='http://www.wxwidgets.org/'
13:34:12: Navigation request to 'http://localhost:57588/stations.html' (target='')
13:34:12: Error; url='http://localhost:57588/stations.html', error='wxWEBVIEW_NAV_ERR_CONNECTION (INET_E_DOWNLOAD_FAILURE)'
</code>
Comment: can you reproduce it the webview sample? Also, what version of the library you are using? What compiler? What OS you test it on?
Comment: @Igor I am using wxWidgets 3.1.0 with Visual Studio 2015.  I am seeing the same behaviour in the sample.  I am testing on windows 10.
Comment: Have you by any chance tried `EVT_WEBVIEW_ERROR` event to redirect to your web server when the error happens.
Comment: @macroland I am processing the error event.  That's how I know the type of error.  Unfortunately, there is nothing to redirect to.  All services in the application are local.  Despite this, the web view refuses to even try to load the page.
Comment: @JonTrauntvein, did you try to debug it? Is failing function something from the WinAPI?
Comment: @Igor Yes, I did try to debug it until it reached the ActiveX invocation on the component.  I didn't see any problems.
Answer: After searching in vain for methods that could be used to configure the iWebBrowser2 instance, I have decided to dump the Trident engine altogether and managed to get wxWebViewChromium to work.  If anyone faces something similar to this, they need to be aware that the current version of wxWebViewChromium do not appear to work with the latest version of CEF.
Answer: Note: not an answer, but a comment/question to @Jon Trauntvein, because I don't have enough reputation to comment
I too decided to drop the wxWebView IE engine because it does not render Google Maps polygons.
discussed here, if you want to know
https://forums.wxwidgets.org/viewtopic.php?f=1&t=43186
so, I am trying to build a current CEF build
https://bitbucket.org/chromiumembedded/cef
into wxWebViewChromium
https://github.com/sjlamerton/wxWebViewChromium
but this project is 4 years old and the CEF API changed.
Would you care to post here the changes you made to wxWebViewChromium ?
thanks
Comment: I didn't know enough to get wxWebViewChromium to work with the current build of cef.  Instead, I found an older version that is compatible: cef_binary_3.1180.823.