text:
Q: In the following jQuery piece of code, how can I select from the multiSelect I am trying to select elements from multiSelect jQuery plugin
1st try:
$("#id").multiSelect('select', ['1', '8', '14'])

2nd try:
let selectedOptions = ['1', '8', '14'];

$.each(selectedOptions, function (i, v) {
    var optionVal = selectedOptions[i];
    $("#SelectedCities").find("optgroup option[value=" + optionVal + "]").prop("selected", "selected");
})

$("#SelectedCities").multiSelect("refresh");

But it didn't work.
any ideas?
this is how i initializing it iam using after init callback
`
     callbacks: function () {
                    $sel.multiSelect("destroy").multiSelect({
                        afterInit: function () {
                            fetch(`/Area/controller/GetCitys`).then(result => {
                                return result.json();
                            })
                            .then(data => {
                                let Area = data.Area
                                let Cities = data.Cities
                                if (Area.length > 0 && Cities.length > 0) {
                                    $.each(Area, function (i, v) {
                                        html += `<optgroup class="font-weight-bold" label=${v.Text}>`
                                        $.each(Cities, function (ind, val) {
                                            if (v.Value == val.Parent) {
                                                html += `<option value="${val.Value}">${val.Text}</option>`;
                                            }
                                        })
                                        html += "</optgroup>";
                                    })
                                    //       console.log(html)
                                    $sel.append(html);
                                    $sel.multiSelect("destroy").multiSelect("refresh").multiSelect({ selectableOptgroup: true });
                                }
                                else {
                                    $sel.empty().append('<option selected="selected" value="0">empty<option>');
                                }
                            })
                                .catch(error => console.log(error));
                        }
                    })
                },
`


text:
Q: Null Object Exception in MVC Partial View I have a partial view called _News that when called by itself works as expected.
When I call it from another view using the following code:
<div>
  @html.Partial("_News");
</div>

It throws this error:
Object reference not set to an instance of an object

At this line of code in the view:
@foreach (var item in Model) {

Where the view is referencing the model. I realise this means that the view is not being passed the model from the Controller but I am perplexed as to why.
The Controller is called NewsController and is located in Controllers. The View is called _News and is located in Shared Views. The view calling the partial view is the default home/index page.

A: If your partial needs to access data from the model, you need to pass the model into the Partial() method:
@Html.Partial("_News", Model)

MSDN: http://msdn.microsoft.com/en-us/library/system.web.mvc.html.partialextensions.partial%28v=vs.108%29.aspx
EDIT:
Per your comment below, I think you're actually after this: http://haacked.com/archive/2009/11/17/aspnetmvc2-render-action.aspx - this lets you call a controller action and render the result into the current view.

A: Could your partial model be a subset or a property of your main views' model? I say could because, to Tieson's point, you can deal with almost any discrepancy between the model the partial wants and the model the view wants... BUT if the model your partial wants is so far disparate from the model your view wants then I will often take that as a possible smell that my two models are not flushed out thoroughly/correctly (basically: "Am I trying to represent too many things or unrelated things on the same page?") .
Additionally, if you can make the model of your partial be a property of the main view's model such that you can pass the model into the partial like this:
@Html.Partial("_News", Model.SomePropertyThatFulfillsTheDataSourceOfThePartial)

then if and when you need to submit the form, this would make model binding much easier as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Integrate NopCommerce 3.x with existing asp.net web form application I have an existing website developed with ASP.net Webform .net 4.0 version. Now we need to integrate NopCommerce 3.7 version in that same site.  (We do not want SSO OR two different subdomain).
How can we setup this in single existing .net site.
Thanks


text:
Q: Read specific remote line with PHP I'm trying to find a way to load my latest tweet with PHP.
At this URL, I change "Twitter.xml" to my username-".xml."
https://twitter.com/users/show/Twitter.xml
The latest tweet is shown on line 49, but I don't think PHP can read a remote file... I want it to show line 49, but how do I combine it with finding a file on a remote server?
Thanks

A: In PHP you can use file_get_contents() to get the contents of that url. For example
$xml = file_get_contents('https://twitter.com/users/show/Twitter.xml');
This will only work if the config setting for allow_url_fopen is set to On

A: Use curl to fetch a remote resource.
http://www.php.net/manual/en/curl.examples-basic.php
http://www.php.net/manual/en/function.curl-init.php
Then, since it's xml, I would convert it to a native PHP object, using SimpleXML
http://www.php.net/manual/en/simplexml.examples-basic.php


text:
Q: How to display the componentProperties options by the selected option in the dropdown? I'm sure this is very simple but it's proving just a bit beyond me at the moment.
I have made a plugin that I would like to use for displaying galleries which is working fine. However, trying to add the options of the galleries that I have created in my component is proving to be difficult.
When I add the component to a page, I have now got the option to choose all the galleries that I created but displaying the gallery based upon which one I selected is what I have been unsuccessful in doing.
Any help would be greatly appreciated!
I'm sure this is very simple but it's proving just a bit beyond me at the moment.
I have made a plugin that I would like to use for displaying galleries which is working fine. However, trying to add the options of the galleries that I have created in my component is proving to be difficult.
When I add the component to a page, I have now got the option to choose all the galleries that I created but displaying the gallery based upon which one I selected is what I have been unsuccessful in doing.
Any help would be greatly appreciated!
Components/Gallery.php:
use Cms\Classes\ComponentBase;
use MartinSmith\Gallerys\Models\Gallery as GalleryModel;

class gallerys extends ComponentBase
{
public $gallery;

public function componentDetails(){
    return [
        'name' => 'Frontend Gallery',
        'description' => 'A gallery for you webpage'
    ];
}

public function defineProperties() {
    $lists = $this->getLists();
    return [
        'galleryName' => [
            'title' => 'Gallery',
            'type' => 'dropdown',
            'placeholder' => 'Select Gallery',
            'options' => $lists
        ]
    ];
}

public function getLists() {
    $agreements = GalleryModel::all()->pluck('name', 'id');
    return $agreements->toArray();
}

public function getList() {
    $agreement = GalleryModel::where('id', $this->property('galleryName'))->get();
    return $agreement->first();
}

}

Components/gallery/default.htm:
{% set gallerys = __SELF__.gallery %}

{% for gallery in gallerys %}

            {% for image in gallery.fullImage %}

{{ image.title }}

{{ image.description }}

            {% endfor %}

{% endfor %}

See screenshot

A: I solved this for myself by creating a function that returns the "name" and indexed by the 'id' using the laravel pluck method. pluck('name', 'id') The first argument selects the column to use as the value and the second argument selects the column to use as a key. Note* the toArray() method I don't think the options field can take collections.
public function getLists() {
    $agreements = Agreements::all()->pluck('agrnum', 'id');
    return $agreements->toArray();
}
//returns
array:3 [▼
  2 => "DLE-2"
  4 => "DLE-1"
  5 => "DLE-3"
]

Now in my properties area I call the function $list = $this->getList();
public function defineProperties() {
$lists = $this->getLists();
return [
    'getList' => [
        'title' => 'List',
        'type' => 'dropdown',
        'placeholder' => 'Select List',
        'options'     => $lists
       ]
    ];
}

After that you can proceed to do a Lists::where('id', $this->property('getList')); or something of that sort in a function to show the selected list or in your case gallery.
My results:
The CMS Page Backend from component
    public function defineProperties() {
    $lists = $this->getLists();
    return [
        'getList' => [
            'title' => 'List',
            'type' => 'dropdown',
            'placeholder' => 'Select List',
            'options'     => $lists
           ]
        ];
    }

    public function getLists() {
    $agreements = Agreements::all()->pluck('agrnum', 'id');
    return $agreements->toArray();
    }

    public function getList() {
        $agreement = Agreements::where('id', $this->property('getList'))->get();
        return $agreement->first();
    }

The Webpage from default.htm in the component template folder
{{ d(__SELF__.getList) }}

Also if I do {{ d(__SELF__.property('getList')) }} it shows me the value is "5".


text:
Q: Saving a large turtle graphics image from the entire canvas I've been looking around for a few hours, and I couldn't find any solutions for this specific problem. I did see one person who asked the same question, but they didn't provide code, and so didn't get an answer. My problem is this:
I have a program that sends the turtle left and right randomly for a set number of turns. The turning part works, but when I try to save the canvas, it only saves the visible part, which often cuts things off. I have tried increasing the size of the setup canvas, as well as the screen capture, but the saved file always ends up in the top left corner, and so gets cut off. I'm attaching my entire program (it's short, don't worry), because I'm not sure exactly what aspect needs to change.
Any help would be greatly appreciated!
import turtle
import random

'''
Takes a variable, number, of how many random turns the turtle should make and a variable filenumber,
which is used to save multiple different iterations of the program per program execution
'''

def left_or_right(number,filenumber):

    # Counters to make sure the turtle doesn't turn too many times
    count = 0
    subright = 0
    subleft = 0

    #sets up screen
    win_width, win_height, bg_color = 10000, 10000,'white'
    turtle.setup()
    turtle.screensize(win_width, win_height,bg_color)

    # Clears the screen, sets the turtle in the middle of the screen, drops the pen and hides the
    # Turtle. If you want to see the turtles do the drawing, turn turtle.tracer to True, and
    # uncomment out turtle.speed('fastest')

    turtle.clear()
    turtle.home()
    turtle.hideturtle()
    turtle.pendown()
    turtle.speed('fastest')
    turtle.tracer(False)

    # A for loop for the turtle's turns
    for i in range(number):
        # Calls decider to you can get a random direction every time
        decider = random.randint(0, 1)
        # in order to minimize the turtle just going around in circles,
        # if the turtle has made more that 3 of the same turn, turn it the other way
        # the next to if statements deal with the turtle turning right too many times
        if decider == 1 and subright <= 3:
            turtle.right(90)
            turtle.forward(20)
            count += 1
            subright += 1

        elif decider == 1 and subright > 3:
            turtle.left(90)
            turtle.forward(20)
            count += 1
            subright = 0

        # The next two if statements make sure the turtle doesn't turn right too many times
        elif decider == 0 and subleft <= 3:
            turtle.left(90)
            turtle.forward(20)
            count += 1
            subleft += 1

        elif decider == 0 and subleft > 3:
            turtle.right(90)
            turtle.forward(20)
            count += 1
            subleft = 0

    # if the number of turns is equal to what the user inputed, stop making the turns
    # and update the screen
    if count == number:
        turtle.penup()
        turtle.update()

    # Take a screen capture of the screen and saves it to where the python file is
    ts = turtle.getscreen()
    ts.getcanvas().postscript(file=filenumber,height=10000, width=10000)

    # turtle.done() is here as a debugging tool. If you set the number of files you're
    # generating to one, you can keep the turtle window open to check that the file correctly
    # copied the turtle screen
    #turtle.done()

''' Takes a variable, filenumber, which is the number of generated files you want'''

def filegen(filenumber):

    for i in range(filenumber):
        # Calls the left or right function as many times as you told it to
        # Note: this is where the left or right function get's its turn number parameters
        left_or_right(10000,i)

def main():

    # calls filegen as many times as you want it to
    filegen(4)

if __name__ == '__main__':
    main()


text:
Q: "Translate" property names into readable names Currently I'm working on a project where we have a query builder - the user selects what data he wants, what is shown on the final report and a few filters. We are also using Entity Framework (Code First) and we need the name of every string property of some classes. E.g.:

*

*Model Class
public class User {
     public int Id { get; set; }
     public string FullName { get; set; }
     public string FullAddress { get; set; }
}

As of now, I'm getting every property name like so:

*Property Filter
var propertyList = type.GetProperties()
        .Where(prop => prop.PropertyType == typeof(string))
        .Select(prop => prop.Name).ToList();

And it works nicely for any change we make to the database, but it's not easy to read for the user (especially if you consider we need to keep all the code in English, even tough we'll publish it for people who mostly only speak Portuguese).
What I need is to display "FullName" as "Nome Completo", "FullAddress" as "Endereço Completo", etc, and still be able to get the original name somehow.
One solution I thought of was making a static dictionary and update it as needed; it's easy to process with jQuery (two way dictionary made with a simple object) but it'll be a pain to maintain since the database can get really big.
Are there any better options than static dictionaries?

A: You can apply a DisplayAttribute to the properties and link it to a resource file with the friendly names in English and/or Portuguese. This is the same way that MVC works. When you need to get the friendly name you just need to call the GetName() method on the attribute to get the appropriate name in the current Thread Culture.
Model Class
// add reference to System.ComponentModel.DataAnnotations to your project
public class User
{
    public int UserId { get; set; }

    // pass the "key" of the resource entry and the name of the resource file
    [Display(Name = "FullName", ResourceType = typeof(UserResources))]
    public string FullName { get; set; }

    [Display(Name = "FullAddress", ResourceType = typeof(UserResources))]
    public string FullAddress { get; set; }

    public string OtherProp { get; set; }
}

UserResources.resx
Default English version (you could just put the Portuguese in here if the website itself isn't truly "multi-lingual")
FullName       Full Name
FullAddress    Full Address

UserResources.pt-pt.resx
Portuguese translations
FullName       Nome Completo
FullAddress    Endereço Completo

Helper Method
This will retrieve the translated display name if a [DisplayAttribute] is present. If not, just the name of the property.
private static string GetPropertyName(PropertyInfo prop)
{
    var displayAttribute = prop.GetCustomAttribute<DisplayAttribute>();
    if (displayAttribute != null)
    {
        // GetName() fetches from the resource file of the current Thread Culture
        return displayAttribute.GetName();
    }
    else
    {
        return prop.Name;
    }
}

Sample Usage to get list of property names
public static void Main(string[] args)
{
    // Uncomment to get the names in Portuguese
    //Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("pt-PT");

    Type type = typeof(User);
    var propertyList = type.GetProperties()
        .Where(prop => prop.PropertyType == typeof(string))
        .Select(prop => GetPropertyName(prop)).ToList();

    foreach (string propertyName in propertyList)
    {
        Console.WriteLine(propertyName);
    }
}

The only other thing to note is that the resource file class is generated as an internal class by default and you will probably need to make it public. You can do this by setting the Custom Tool in the Properties window in Visual Studio to PublicResXFileCodeGenerator. Otherwise you may get an error saying "no public property FirstName found in resource file".

A: If you right click on a table, or a column, in SQL Server Management Studio, and select properties, you will see that there is an option for Extended Properties. You could add an extended property called Friendly Name for each column, then have a separate query to load your dictionary at the applications start.
Here is a query that will help you pull Extended Properties for columns in your database.
SELECT major_id, minor_id, t.name AS [Table Name], c.name AS [Column Name], value AS [Extended Property], ep.name as [Property Name]
FROM sys.extended_properties AS ep
INNER JOIN sys.tables AS t ON ep.major_id = t.object_id
INNER JOIN sys.columns AS c ON ep.major_id = c.object_id AND ep.minor_id = c.column_id
WHERE class = 1;

Example brazenly stolen from the following url (I make no pretense of having this stuff memorized):
http://technet.microsoft.com/en-us/library/ms186989(v=SQL.105).aspx


text:
Q: Hard drive is detected as USB flash drive My external hard drive (USB 3.0) is detected as a USB flash drive in 'My Computer' and I can't access the device by using Window Explorer and from the command line. Before that happened, it installed its own driver called (NORELSYS 106X USB) automatically. I tried in another PC, but I still got the same result. Nothing was detected when I tried to connect the external hard drive in Linux (Ubuntu).

When I checked in Disk Management, it shows as the below screenshots:

Here is my Device Properties:

Is there any way to recover my hard drive or my data?


text:
Q: Variadic functions on Arduino I am programming in Arduino 022 for the Arduino Mini Pro. I have the following function:
  String join(const String str, ...) {
    Serial.println("join");
    va_list args;
    va_start(args, str);

    Serial.println("result init");
    String result = "";

    for (String strArg = str; strArg != NULL; strArg = va_arg(args, String)) {
      Serial.println(result);
      result += strArg + ARG_DELIMITER;
    }

    result = result.substring(0, result.length() - 1);

    Serial.println("join end");

    return result;
  }

When I call this function, the program halts, and the built in LED in pin 13 turns on. "join" is never printed to the serial monitor. Are variadic functions not permitted on Arduino?

A: You can't pass most class types to a variadic function - only POD types (5.2.2 para 7 in the standard); if you do the behaviour is undefined - which could cause the problems you're getting. I'm pretty sure the Arduino String class is not a POD, so this isn't going to work.
You might be better off using char arrays (at least in some places), eg
String join(char const * const str, ...)

if this doesn't cause too much ugliness at the call site, or perhaps just provide overloads for 1 to N Strings.
Also - can a String object ever be equal to NULL? Your test for strArg != NULL looks dubious.

A: When you call the code, does it look like:
 join( "foo", "bar", NULL );   // ok

or:
 join( "foo", "bar" );        // wrong

You have to provide the NULL terminator yourself - the compiler won't do it.
Edit: This assumes that String is a typedef for char * (because you compare it with NULL), but if it is there is much else wrong with your code. Please clarify what the type of String is.


text:
Q: Проблема с обновлением Scikit-learn до версии 0.20.1 Необходимо обновить Scikit-learn для Anaconda до версии 0.20.1. На данный момент стоит версия 0.19.1. При вводе команды conda update scikit-learnвыводится: #All requested packages already installed.
Уже пробовал conda update conda - обновил, но это проблему не решило. Также попробовал скачать необходимую версию с https://anaconda.org/anaconda/scikit-learn, но при установке выдаёт только ту же 0.19.1. Ещё попробовал написать conda update scikit-learn=0.20.1, но в этом случае Solving environment: \ "крутиться" бесконечно (пол часа точно).
Как же всё-таки обновить эту библиотеку?

A: В общем, я обновил python командой conda update python (версия 3.6.5). Снова попробовал обновить scikit-learn - выдаёт ту же 0.19.1. Снёс к чертям conda remove scikit-learn и снова установил conda install scikit-learn. Алилуя, выдал версию аж 0.20.2


text:
Q: How to convert date-string to float for representation of an x-axis? I'm dealing with a large dataset that has dates in it (in the format "mm/dd/yyyy") and I'm trying to graph a certain metric in relation to that dates. Now since the dates need to be in the x-axis, I know I need to convert them into floats. I currently have two approaches:

*

*Use string parsing to get month/year/dates, convert them to floats, and add them together like so:

def get_date_float(date_str):
    # date_str = something like "01/13/2021"
    m, d, y = float(date_str[:2]), float(date_str[3:5]), float(date_str[6:])
    return y + (m / 12) + (0.01 * d / num_days_in_month(int(m)))

Note: num_days_in_month uses the monthrange function from the calendar module.
However, this results in not-so-accurate floats for the dates. For example, the date "12/15/2020    " becomes the float "2021.004839" which is clearly wrong. I'm not sure why this is happening - I tried different operations on the m/d/y variables from above but there's always some degree of error.

*After reading this answer, I tried using the datetimemodule to convert the string into a float like so:

def date_str_to_datetime_to_float(date_str):
    # date_str = "12/15/2020"
    datetime_obj = datetime.strptime(date_str, "%m/%d/%Y")
    print(datetime_obj.timestamp())

However, the timestamp is a very large number (# of milliseconds since some starting time?). For example, the date "12/15/2020" becomes the timestamp "1608019200.0". However, I want something like "2020.921" or something like that.
All help is appreciated; thanks!

A: Resolved in comments! Apparently datetime objects graph pretty well on the x-axis.


text:
Q: How can we distinguish between audio and video under Android audioflinger
*

*we can make distinguish between audio and video if we use android standard api to implement apk to play music/movie. no matter under libaudioflinger or decoder's lib.

when decode audio/video in awesomeplayer.cpp,we can judge the source data't type,audio? or video?

*we can make distinguish the app's type under libaudioflinger

use getCallingPid()

Question:
how can we make distinguish 3rd's data source type(Audio?video?)under audioflinger?

A: yes audioflinger process the pcm data .
However if you want to set some parameters from Application then you  can use AudioManager's setParametes API and then have a handling for that parameter in AudioFlinger .
AudioManager am = (AudioManager)context.getSystemService(context.AUDIO_SERVICE);
am.setParameters("key_value_pair");


text:
Q: invalid literal for int() with base 10: 'EC180' All that i tried was:
df['buyer_zip']=df['buyer_zip'].replace('-', 0)
df['buyer_zip']=df['buyer_zip'].replace('', 0)
df['buyer_zip']=df['buyer_zip'].str[:5]
df["buyer_zip"].fillna( method ='ffill', inplace = True)
df["buyer_zip"].apply(int)

I have two columns in a pandas dataframe called Buyer_zip and Item_zip which are the zip codes of Buyer and items respectively. These zip codes have 4 formats. One is 5 digit zip code( ex: 12345), one is 5+4 digit zip code( 12345-1234), one is 9 digit zipcode (123456789) and the last one is 'EC180'. So, the last format is alphanumeric. There are 15 Million records in total. I am struck at a point where i have to convert all those alphanumeric values to numeric. When trying to do the same, i encountered the error: invalid literal for int() with base 10: 'EC180'. Could someone help me how to find all the words in my data column and replace it with 00000. Appreciate any help.But none of it gave an answer to how to find the words in that column and replace it with numbers
Sample data:
buyer_zip
97219
11415-3528
EC180
907031234

Expected output
     buyer_zip
0      97219
1  114153528
2          0
3  907031234

A: Pandas has several different "replace" methods. On a DataFrame or a Series, replace is meant to match and replace entire values. For instance, df['buyer_zip'].replace('-', 0) looks for a column value that is literally the single character "-" and replaces it with the integer 0. That's not what you want. The series also has a .str attribute which holds functions for strings, and its replace is closer to what you want.
But, that is what you want when you have a string that starts with a non-digit letter. You want that one to be completely replaced with "00000".
Finally, astype is a faster way to convert the column to an int.
import pandas as pd

df = pd.DataFrame({"buyer_zip":["12345", "123451234", "123456789", "EC180"]})

df["buyer_zip"] = df["buyer_zip"].str.replace("-", "")
df["buyer_zip"] = df["buyer_zip"].replace(r"[^\d].*$", "00000", regex=True)
df["buyer_zip"] = df["buyer_zip"].astype(int)

The operations can be chained. Apply the second operation to the result of the first, etc, and you can condense the conversion
df["buyer_zip"] = df["buyer_zip"].str.replace("-", "").replace(r"[^\d].*$", "00000", regex=True).astype(int)


text:
Q: Associated Model with its primary key as the foreign key in cakephp? I have some user attributes in different areas so I want to separate them into two tables.
One is the users table with user ID. Another table holds location coordinates of the user. It's still one location per user. It's optional value for the user.
Because It seems to me that users table is too important to mess around and it won't change as much as the location table, I want to make location table a new table. Is this good practice?
But then can I associate these 2 tables as one-to-many and belongs-to still? So I can still use them as normal associated models in controllers? Only they are actually in one to one assocation.

A: It is usually more simple to deal only with one table, but you can still doing it if you want to.
You can use the hasOne relation for it.
You should use it in both models.
You can read more about it here:
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone


text:
Q: How to get HTML content using PhantomJS after X seconds? How to get the content of website after 10 seconds using PhantomJS? In my website for example, I have script that do setTimeout then change the DOM. I need to feach the website html with that change.
I can't find any working answers.

A: Try this code:
var page = require('webpage').create();
var fs = require('fs');
page.open('http://example.com', function(status) {
    console.log('Page load status: ' + status);
    if (status === 'success') {
        setTimeout(function(){
            fs.write('example.html', page.content, 'a');
            console.log('Page saved');
            phantom.exit();
        }, 10000);
    }
});


text:
Q: Missing scope error on Google authentication callback using Node.js/Passport This error occurs on Heroku (production) only, not on local.
I have tried both:
passport.authenticate('google', { scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/analytics.readonly' })

And,
passport.authenticate('google', { scope: ['profile', 'email'] })
Whether the scope is an array, or a space-delimited string.
When I go to the Google authentication link, scope IS in the URL. There is no difference in the one generated in my live production app.
But I still get:
Error 400

Error: invalid_request

Missing required parameter: scope

A: I take it you are using the Passport Google OAuth, not just the Passport Google (OpenId) module?
If you are using the OAuth passport, the authentication with Google requires an extra scope parameter.
Pass as a string, you must pass 'openid' as the 1st word, eg:
For example, if you wanted per-file access to a user's Google Drive,
openid profile email https://www.googleapis.com/auth/drive.file

Source(s):
https://developers.google.com/identity/protocols/OpenIDConnect#scope-param
https://developers.google.com/+/api/oauth#login-scopes

A: For error message
Error 400
Error: invalid_request
Missing required parameter: scope

You need to add scopes in your form
<input type="hidden" name="scope" value="https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo#email https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/tasks https://www-opensocial.googleusercontent.com/api/people https://www.googleapis.com/auth/plus.login" />

Please refer spring social login with linkedin,facebook,twitter and google providers example application.


text:
Q: Limit/Throttle per user OpenVPN bandwidth using TC I have a group of users connecting to my server via OpenVPN TCP and UDP (2 services). The two services are operating on tun0 and tun1
I'd like to be able to limit each user's bandwidth to say 5mb/s up and 5mb/s down using the TC command.
This was fairly easy to implement with PPTP as each user got their own interface, so I could just create a new class/filter for that interface limiting it to my desired speed limit using something like this:
IF=<taken from up script, i.e. ppp1>
tc qdisc del dev $IF root
tc qdisc add dev $IF root handle 1: cbq avpkt 1000 bandwidth 100mbit
tc class add dev $IF parent 1: classid 1:1 cbq rate 10mbit allot 1500 prio 5 bounded isolated
tc filter add dev $IF parent 1: protocol ip prio 16 u32 match ip src 0.0.0.0/0 flowid 1:1
tc qdisc add dev $IF parent 1:1 sfq perturb 10

As far as I can tell with OpenVPN users do not get their own interface, all traffic goes through the main tun0 and tun1 interfaces.
So I have 2 problems here.
1) The script above does not seem to work with OpenVPN for some reason (setting the interface name to tun0 or tun1) my test user can still download at their internet's max speed.
2) I need to be able to filter this per source IP and add it in OpenVPN's up script when they connect while maintaining the other filter/classes and remove that filter/class in the down script, again without affecting the other connected user's limits (i.e. I can't simply delete the qdisc for tun0 each time a user connects).
The only help I can find when searching is

"you can use TC for that"

but no explanation of how...
thanks!

A: I once did something like this for individually firewalling each user's connection. I have implemented it using the learn-address script in OpenVPN which is called when a user connects or disconnects. I have adapted it for your use case.
The script looks as follows:
#!/bin/bash

statedir=/tmp/

function bwlimit-enable() {
    ip=$1
    user=$2

    # Disable if already enabled.
    bwlimit-disable $ip

    # Find unique classid.
    if [ -f $statedir/$ip.classid ]; then
        # Reuse this IP's classid
        classid=`cat $statedir/$ip.classid`
    else
        if [ -f $statedir/last_classid ]; then
            classid=`cat $statedir/last_classid`
            classid=$((classid+1))
        else
            classid=1
        fi
        echo $classid > $statedir/last_classid
    fi

    # Find this user's bandwidth limit
    # downrate: from VPN server to the client
    # uprate: from client to the VPN server
    if [ "$user" == "myuser" ]; then
        downrate=10mbit
        uprate=10mbit
    elif [ "$user" == "anotheruser"]; then
        downrate=2mbit
        uprate=2mbit
    else
        downrate=5mbit
        uprate=5mbit
    fi

    # Limit traffic from VPN server to client
    tc class add dev $dev parent 1: classid 1:$classid htb rate $downrate
    tc filter add dev $dev protocol all parent 1:0 prio 1 u32 match ip dst $ip/32 flowid 1:$classid

    # Limit traffic from client to VPN server
    tc filter add dev $dev parent ffff: protocol all prio 1 u32 match ip src $ip/32 police rate $uprate burst 80k drop flowid :$classid

    # Store classid and dev for further use.
    echo $classid > $statedir/$ip.classid
    echo $dev > $statedir/$ip.dev
}

function bwlimit-disable() {
    ip=$1

    if [ ! -f $statedir/$ip.classid ]; then
        return
    fi
    if [ ! -f $statedir/$ip.dev ]; then
        return
    fi

    classid=`cat $statedir/$ip.classid`
    dev=`cat $statedir/$ip.dev`

    tc filter del dev $dev protocol all parent 1:0 prio 1 u32 match ip dst $ip/32
    tc class del dev $dev classid 1:$classid

    tc filter del dev $dev parent ffff: protocol all prio 1 u32 match ip src $ip/32

    # Remove .dev but keep .classid so it can be reused.
    rm $statedir/$ip.dev
}

# Make sure queueing discipline is enabled.
tc qdisc add dev $dev root handle 1: htb 2>/dev/null || /bin/true
tc qdisc add dev $dev handle ffff: ingress 2>/dev/null || /bin/true

case "$1" in
    add|update)
        bwlimit-enable $2 $3
        ;;
    delete)
        bwlimit-disable $2
        ;;
    *)
        echo "$0: unknown operation [$1]" >&2
        exit 1
        ;;
esac

exit 0

The script needs to be installed in your OpenVPN's server.conf as follows:
learn-address <path-to-script>
script-security 3

script-security 3 is necessary so OpenVPN actually calls the script.
When a user connects, the script is called as <path-to-script> add <ip> <username>, furthermore the network interface is placed in the environment variable $dev (e.g. tun0).
The script configures the network interface for queueing discipline and attaches the necessary filters and classes to it. It keeps track of the IPs for which it installed filters and classes so it can later remove them if the user disconnects. That state is kept in the directory /tmp, this should probably be changed.
Note that I'm not sure I have gotten the traffic control stuff 100% right. Download traffic shaping (i.e. from OpenVPN to the user) works fine, but limiting the upload isn't very precise, which is somewhat normal from what I have understood. Maybe you can find a better way and integrate it in the script.


text:
Q: Programmatically add Button to ConstrainLayout with ConstraintSet GoodDay everyone.
Im trying to add a button programmatically to a ConstraintLayout and set ConstraintSet to such button.
The problem comes when I try to close the constraintSet from the layout as the button I've added has no ID.
Button button = new Button(this);

ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(250, ConstraintLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(15,15,15,15);

button.setLayoutParams(params);
button.setText(returnObject.getFunction());
button.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
button.setTextColor(R.drawable.custom_button_color);
button.setBackgroundResource(R.drawable.custom_button);

ConstraintLayout container = findViewById(R.id.highLevelContainer);
container.addView(button);

ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(container); // Here I get the error
constraintSet.connect(button.getId(), ConstraintSet.END , container.getId(), ConstraintSet.END,0);
constraintSet.connect(button.getId(), ConstraintSet.START, container.getId(),ConstraintSet.START,0);
constraintSet.connect(button.getId(), ConstraintSet.TOP, container.getId(), ConstraintSet.TOP);
constraintSet.applyTo(container);

This is the generated error on the console:
java.lang.RuntimeException: All children of ConstraintLayout must have ids to use ConstraintSet
    at android.support.constraint.ConstraintSet.clone

I would like to avoid assigning a random number to the button as ID as it's created in a loop.
Any idea how to fix this?

A: You should simply add the id to your button:
Button button = new Button(this);

ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(250, ConstraintLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(15,15,15,15);

button.setLayoutParams(params);
button.setText(returnObject.getFunction());

button.setId(View.generateViewId());   <----HERE

button.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
button.setTextColor(R.drawable.custom_button_color);
button.setBackgroundResource(R.drawable.custom_button);

ConstraintLayout container = findViewById(R.id.highLevelContainer);
container.addView(button);

ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(container);
constraintSet.connect(button.getId(), ConstraintSet.END , container.getId(), ConstraintSet.END,0);
constraintSet.connect(button.getId(), ConstraintSet.START, container.getId(),ConstraintSet.START,0);
constraintSet.connect(button.getId(), ConstraintSet.TOP, container.getId(), ConstraintSet.TOP);
constraintSet.applyTo(container);


text:
Q: java.lang.NoClassDefFoundError: org.opencv.face.Sample3Native$1 I am developing an Android based app in OpenCV. When I build the code in Eclipse I don't get any errors, but when I run it it just says "unfortunately FaceRecognition has stopped" and stops. Here is what I get in the Log cat.
    06-05 11:05:51.346: E/AndroidRuntime(10238): FATAL EXCEPTION: main
06-05 11:05:51.346: E/AndroidRuntime(10238): Process: org.opencv.face, PID: 10238
06-05 11:05:51.346: E/AndroidRuntime(10238): java.lang.NoClassDefFoundError: org.opencv.face.Sample3Native$1
06-05 11:05:51.346: E/AndroidRuntime(10238):    at org.opencv.face.Sample3Native.<init>(Sample3Native.java:73)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at java.lang.Class.newInstanceImpl(Native Method)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at java.lang.Class.newInstance(Class.java:1215)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2276)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2422)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at android.app.ActivityThread.access$800(ActivityThread.java:151)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at android.os.Handler.dispatchMessage(Handler.java:110)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at android.os.Looper.loop(Looper.java:193)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at android.app.ActivityThread.main(ActivityThread.java:5330)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at java.lang.reflect.Method.invokeNative(Native Method)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at java.lang.reflect.Method.invoke(Method.java:515)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
06-05 11:05:51.346: E/AndroidRuntime(10238):    at dalvik.system.NativeStart.main(Native Method)

Manifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.opencv.face"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="org.opencv.face.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
        android:name="org.opencv.face.Sample3Native"
        android:label="@string/app_name">
    </activity>
    </application>

</manifest>

How can I solve this problem ?

A: Go to your AndroidManifest.xml in you project
and add your activity class named  ActivityThread.class like this
    <activity
        android:name=".ActivityThread"
        android:label="@string/title_activity_thread">
    </activity>

A: In manifest.xml you use android:name="org.opencv.face.Sample3Native".
From your log it seems that your package name is not correct.
That means Sample3Native class is not in org.opencv.face package
May be another package.
Please check it. I hope your problem will solve...
You can simply solve it by creating another activity and move code to the new class. this time
1. Right click on project
2. click new
3 . Click others
4. Android.
5. Android Activity
and create an activity using wizard.
Then move your code to new class


text:
Q: Adding a space in javascript? // If given "George", "Washington" as arguments, it should return "Washington, George"
function formatName(firstName, lastName) {
  return [lastName, firstName];
}

Please see the link.  I can't figure out how to put a simple space between the first and last name.  I have been at this for hours please help!

A: Use String concatenation
return lastName +', '+ firstName;

function formatName(firstName, lastName) {
  return lastName +', '+ firstName;
}

console.log(formatName("George","Washington"))

if your task is really to handle the given array than use the Array.prototype.join() method with the desired separator argument ', '

function formatName(firstName, lastName) {
  return [lastName, firstName].join(', ');
}

console.log(formatName("George","Washington"))

A: You should return a string that concatenates the first name and last name. Try this:
return lastName +", "+ firstName;

A: try with join(', ')
function formatName(firstName, lastName) {
  return [lastName, firstName].join(', ');
}


text:
Q: Can Garageband Loops be removed after removing Garageband? I have just removed Garageband Loops via System Information > Manage; these remained after I'd uninstalled Garageband using AppCleaner.
Can I remove them manually or will this impact other functionality in the system?

A: You can safely remove the GarageBand loops. Note: These loops can also be used by Logic.
Remember - should you want to use GarageBand in the future, the loops can be re-downloaded any time.
Edit in light of benwiggy's comment.


text:
Q: Memory Mapping the same file multiple times? What are the performance characteristics of memory mapping the same file multiple times? Will the OS reuse/cache between the mappings or will it read in the file multiple times into different parts of the memory?
i.e. if I read and write to a memory mapped file from two different processes will it go through the disk or will they communicate in memory? If I read from a memory mapped file from two different process alternatively thread, will they read from the same memory?

A: You can use MAP_PRIVATE in order to get a private copy-on-write mapping of the underlying file.  You can use MAP_SHARED in order to get a view of the underlying file.  I do not know what happens if you have the same region mapped in  MAP_PRIVATE mappings and MAP_SHARED mappings at the same time, but I suspect writes to either mapping cause a copy.
In order to sync with disk, you want to use msync.  On most systems, multiple MAP_SHARED mappings will give you a piece of memory, nominally backed by disk, that is shared among processes.  I'm not sure whether this behaviour is specified or merely a happy consequence of the typical implementation.

A: It will use the file-cache, so assuming there is ENOUGH RAM in the machine, it should cache the two processes' writes. Of course also assuming the reads and writes actually hit the same area of the file...


text:
Q: unable to execute query using phpmyadmin SELECT email, record_id
  FROM ( SELECT email, record_id
           FROM record_data
          WHERE email NOT REGEXP ( SELECT GROUP_CONCAT( pattern SEPARATOR  '|' )
                                     FROM blockedcompanies ) tmp
                )
 WHERE email NOT REGEXP(SELECT GROUP_CONCAT(email SEPARATOR  '|' )
                          FROM unsubscribed );

Whats wrong with this query? I am getting the following syntax error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'tmp) WHERE email NOT REGEXP(SELECT GROUP_CONCAT(email SEPARATOR '|' ) FROM un' at line 4

A: I believe :
    SELECT email,record_id FROM
    (
          SELECT email,record_id FROM record_data WHERE email NOT REGEXP
          (
               SELECT GROUP_CONCAT( pattern SEPARATOR  '|' ) FROM blockedcompanies
          )   tmp <--ROMOVE THIS HERE
    ) <-- and put it here.
    WHERE email NOT REGEXP(
          SELECT GROUP_CONCAT(email SEPARATOR  '|' ) FROM unsubscribed
    );


text:
Q: error when sort fields in gridview I had Grid view and I added property allow sorting in it and I converted all fields in grid view to item template and after that this error appeared (The GridView 'GridView1' fired event sorting which wasn't handled)
Please anyone help me
.

                                                                '>

                                                                '>

                                                                '>

                                                                '>

                                                                '>

                                                                '>

                                                                '>

                                                                '>

                                                                '>

                                                                '>

                                                                '>

                                                                '>

                                                                '>

                                                                '>

A: If you are not binding your GridView to SqlDataSource and you are setting its AllowSorting to true, you need to do sorting manually. You need to assign sorting event to the GridView, and write your own code to implement the sorting. You can refer to the code below, and modify accordingly.

On aspx page:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
    onsorting="GridView1_Sorting">
</asp:GridView>

On codebehind:
public partial class GridViewSort : System.Web.UI.Page
{
    private const string ASCENDING = " ASC";
    private const string DESCENDING = " DESC";

    public SortDirection GridViewSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;

            return (SortDirection)ViewState["sortDirection"];
        }
        set { ViewState["sortDirection"] = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
            return;

        GridView1.DataSource = GetStaff();
        GridView1.DataBind();
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {

        string sortExpression = e.SortExpression;

        if (GridViewSortDirection == SortDirection.Ascending)
        {
            GridViewSortDirection = SortDirection.Descending;
            SortGridView(sortExpression, DESCENDING);
        }
        else
        {
            GridViewSortDirection = SortDirection.Ascending;
            SortGridView(sortExpression, ASCENDING);
        }
    }

    private void SortGridView(string sortExpression, string direction)
    {
        DataTable dt = GetStaff();

        DataView dv = new DataView(dt);
        dv.Sort = sortExpression + direction;

        GridView1.DataSource = dv;
        GridView1.DataBind();
    }

    /// <summary>
    /// Dummy data
    /// </summary>
    /// <returns></returns>
    private DataTable GetStaff()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Age", typeof(int));

        for (int i = 1; i <= 20; i++)
        {
            dt.Rows.Add(i, "Staff - " + i, 20 );
        }

        return dt;
    }
}


text:
Q: Prolog ERROR: is/2 If I try
logPower(X, N, REZ) :-
    N mod 2 =:= 0,
    !,
    N1 is N/2,
    logPower(X, N1, REZ1),
    REZ is REZ1*REZ.

it doesn't work and I get
ERROR: is/2: Arguments are not sufficiently instantiated
but instead if I try
logPower(X, N, REZ) :-
    N mod 2 =:= 0,
    !,
    N1 is N-1,
    logPower(X, N1, REZ1),
    REZ is REZ1*REZ.

it works.
How may I edit the first one to work ?

A: The answer has already been given in a comment, but I'll expand it a little to explain exactly what's going on.
The problem lies in the line REZ is REZ1*REZ. The predicate is/2 needs to have all arguments on the right hand side to be instantiated, like the error message tells you. But you're trying to use REZ as a variable, which it isn't.
Now I'm assuming you have another clause that servers as a stopping point (or starting point, depending how you look at it) for logPower/3, or otherwise you would have an infinite loop, but the question remains, why does the first version produce an error but not the second one, since they both contain the same line REZ is REZ1*REZ?
Well, your second version replaced the line N1 is N/2 with N1 is N-1, after which you "call" logPower/3 again. You checked if N is even, then you either divided by 2 or subtracted 1. In the former case, if N was dividable by 4, N1 will still be even, giving you a chance to hit the starting point for logPower/3 and reach the line with the problem.
But in the latter case, N1 will not be even and you will fail, without hitting the error, except for an N that will make you hit the starting point before failing because of the even/odd-check.


text:
Q: Save HTML table on server side in JSP I have a JSP where I can create a dynamic HTML table. In that table, I can create the rows, edit the rows, and delete the rows. There's only one thing that I am unable to do, which is that I want to save this HTML table as comma separated text file if the user desires to do so. Please note that this save has to be done on Server side, not client side.
The answer that I have followed on Stack Overflow cover the client side, where I can use JavaScript and/or jQuery to perform that, but I don't want that.
Here is the complete minimal code of my JSP.
<%@page import="java.io.FileReader"%>
<%@page import="java.io.File"%>
<%@ page import="javax.script.*"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

EAN
DS_BRAND
DS_RANGE
DS_LIV_3
DS_LIV_1
DS_EAN

<input type="text" id="new_name">
<input type="text" id="new_country">
<input type="text" id="new_age">
<input type="text" id="new_dsliv3">
<input type="text" id="new_dsliv1">
<input type="text" id="new_dsean">
<input type="button" class="add" onclick="add_row();"
value="Add Row">

<input type="button" class="add" onclick="add_row_from_table();"
                value="Load CSV">
<input type="button" class="add" onclick="save_csv();"
                value="Save CSV">

The only thing I'm interested in here is that I want to save the content of this table in text file (comma separated) on server side.
Some other information that I'd like to share is that I'm using JDK 1.8, on Eclipse Oxygen with Tomcat 8.0 as the runtime environment. To add to that, the OS is Windows 7.


text:
Q: References that start with " I use BibTex to manage my references. Now I have a small problem. The title of one of my references starts with "I don't ... ". When I generate the bibliography it looks like this:
""i don' ...

Why is the I here not in capital letters? All other of my references start with a capital letter.

A: Many BibTeX bibliography styles -- including, it would appear to be the case, the one you're using -- are set to automatically lowercase all letters in an entry's title field (except if the letter is at the very start of the title field string) if the entry is of type article, techreport, misc, or unpublished. This lower-casing setting, however, generally doesn't apply if the entry is of, say, type book.
Since the title of one of your references starts with ``I don't ... rather than with I don't ..., the I is not the very first character of the title field and hence is converted to lowercase. To keep this from happening, you must surround it by braces, as in
title = "``{I} don't ... ''",


text:
Q: My keyboard layout keeps getting set to French? I have both XFCE and i3wm installed on my computer. Running Ubuntu 16.04 LTS 64-bit.
My mouse stopped working and I was too lazy to get another one, so I was trying to mash my keyboard to find the shortcut to change the desktop environment. Somehow in this process I managed to change my keyboard layout to French.
I have already tried checking the settings in /etc/default/keyboard and running sudo dpkg-reconfigure keyboard-configuration but the file already contains US 105-key and the command didn't fix the problem. I can change it back to English in XFCE but it resets on the login screen.
What key could I have hit to change my keyboard layout to French? How do I change it back?


text:
Q: How can I get skrollr.js to "snap" to certain vertical locations? I'm using skrollr in an attempt to create a fullpage.js-like effect plus parallax.
The issue is that when I skroll --er, scroll through each "slide" of content, sometimes the scroll interval is offset by an amount that makes it impossible to align the top of each section with the top of the viewport, which looks less polished than I'd like.
I'd love to be able to disable scrolling through each section and have it just advance through each slide when the user scrolls faster than a certain mousewheel threshold (eg, not just on one tick), but after pursuing that for awhile, I haven't gotten very far.
Would anyone like to enlighten me on how to do that with Skrollr (or suggest a different jQuery plugin, if it's too difficult to achieve with Skrollr)?
(So far I've tried having it animateTo() the next slide when the window-top is aligned with the top of a slide, but apparently the fact that sometimes it doesn't line up perfectly throws that off. Also, I have yet to find a way to disable [even if only temporarily] the normal scroll-through behavior. [It has occurred to me that I may be countered by Skrollr itself while trying to figure this out.])


text:
Q: swift : Can't set variable in imagePickerController result In my class, after I have saved the picked image, i'm trying to set a variable value, but it doesn't change.
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
    let imageName = Util.generateFilename(activityId.integerValue)
    var localPath = Util.getExpensePath(activityId.stringValue)
    localPath = localPath?.URLByAppendingPathComponent(imageName, isDirectory: false)

    let image = Util.reduceImageSize(info[UIImagePickerControllerOriginalImage] as! UIImage, compressionQuality: 0.5)
    let data = UIImagePNGRepresentation(image)
    data!.writeToFile(localPath!.path!, atomically: true)

    picker.dismissViewControllerAnimated(true, completion: nil)
    imagePickedPath = localPath!.path!
}

@IBAction func viewButtonClick(sender: UIButton)
{
     showImage(imagePickedPath!)
}

Debugging, imagePickedPath seems to change value after execution of last line in first method but when i click to view button, imagePickedPath continue to has the old value. What's wrong?


text:
Q: Convert formatted email (HTML) to plain Text? I have this code that implements ParserCallback and converts HTML emails to Plain text. This code works fine when I parse email body like this =
  "DO NOT REPLY TO THIS EMAIL MESSAGE.
---------------------------------------
\n" +
                "nix
---------------------------------------
 Esfghjdfkj\n" +
                "

--

Regards
Nisj
Software Engineer

Bingo

\n" +
                "
"

but when I parse this kinda email body, it returns null,
 email = "<meta http-equiv=\"Content-Type\" content=\"text/html charset=us-ascii\">Got it...so pls send to customer now.

On Nov 8, 2013, at 12:31 PM, xxxxxxx.com wrote:

Forwarding test.
---------------------------------------
 ABCD.

";

Code :
import java.io.IOException;
import java.io.StringReader;

import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML.Attribute;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit.Parser;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.swing.text.html.parser.ParserDelegator;

public class EmailBody {
    public static void main(String[] args) throws IOException
    {
        String email = "";

        class EmailCallback extends ParserCallback
        {
            private String body_;
            private boolean divStarted_;

            public String getBody()
            {
                return body_;
            }

            @Override
            public void handleStartTag(Tag t, MutableAttributeSet a, int pos)
            {
                if (t.equals(Tag.DIV) && "ltr".equals(a.getAttribute(Attribute.DIR)))
                {
                    divStarted_ = true;
                }
            }

            @Override
            public void handleEndTag(Tag t, int pos)
            {
                if (t.equals(Tag.DIV))
                {
                    divStarted_ = false;
                }
            }

            @Override
            public void handleText(char[] data, int pos)
            {
                if (divStarted_)
                {
                    body_ = new String(data);
                }
            }
        }
        EmailCallback callback = new EmailCallback();
        Parser parser = new ParserDelegator();
        StringReader reader = new StringReader(email);
        parser.parse(reader, callback, true);
        reader.close();
        System.out.println(callback.getBody());
    }
}

Can you tell the reason, why this is happening ?

A: You code will only take the element text from DIV elements which have a dir attribute with an ltr value. The handleText method will only handle the element text if the divStarted_ flag is true, which happens only if the handleStartTag set this flag to true.
In the first email example you have such elements, in the second one you do not have them.


text:
Q: Windows Server 2008 - Give my ASP.NET website write permission to a folder I have a folder "foo" which resides under the root folder of my ASP.NET website.
My ASP.NET website has a file browser control which enables (authenticated) users to upload files, create folders, move folders, delete file/folders etc. in the "foo" folder.
What permissions should the "foo" folder have?
It is a Windows Server 2008 / IIS 7 box.
Many thanks.

A: Depending on the authentication method you are using, either the end user or the Application Pool Identity user will need Modify privileges to the foo folder.
UPDATED:
It sounds like you are using Anonymous Authentication, but are authenticating the user in your DB via your application.
Check your IIS to determine which identity Anonymous Authentication is using. The default is IUSR, but you can also decide to use the application pool identity, in which case, you will need to check your Application Pool Identity.
If you have stuck with the defaults, you will likely only need to add Modify permissions to the built-in IUSR user.
Additional backround info: Understanding Built-In User and Group Accounts in IIS 7


text:
Q: Iterating through a dict, list in python Now that I know how to iterate through a dict, I need to know how to iterate through a list and be able to print each customer, account and transaction. I have 3 classes Customer, Account, and Transaction. Within the Customer class, I put a list to hold Account objects and within the Account class, I have a list to hold Transaction objects. Near the end of this code, I have a for loop iterating through the map, but when I try to iterate through the list, it doesn't seem to work. It is most likely through my own error.
class Customer(object):
'''Main Constructor'''
def__init__(self,CNumber=1,CName="A",CAddress="A",CCity="A",CState="A",CZipCode=1,CPhone="1",Account=[]):
    self.CNumber = CNumber
    self.CName = CName
    self.CAddress = CAddress
    self.CCity = CCity
    self.CState = CState
    self.CZipCode = CZipCode
    self.CPhone = CPhone
    self.Account = Account

dict = {}
c = Customer.Customer("1111","Jake","Main St","Happy Valley","CA","96687","8976098765")
dict[c.getCNumber()] = c
c = Customer.Customer("2222","Paul","3342 CherrySt","Seatle","WA","98673","9646745678")
dict[c.getCNumber()] = c

a = Account.Account("1111",True,0.00,500.00)
dict[c.getCNumber()].AddAccount(a)
a = Account.Account("2222",True,0.00,500.00)
dict[c.getCNumber()].AddAccount(a)
a = Account.Account("3333",False,0.02,10000.00)
dict[c.getCNumber()].AddAccount(a)
a = Account.Account("4444",False,0.02,10000.00)
dict[c.getCNumber()].AddAccount(a)

for key in sorted(dict.keys()):
    print("***Customer***")
    print("Customer Number: " + dict[key].getCNumber())
    print(dict[key].getCName())
    print(dict[key].getCAddress())
    print(dict[key].getCCity() + ", " + dict[key].getCState() + " " + dict[key].getCZipCode())
    for key1 in dict[key].getAccount()[key1]:
        print("\t***Account***")
        print("\tAccount Number: " + a.getANumber())
        print("\t" + a.getAType())
        print("\t" + a.getAInterestRate())

If you need more info, let me know. I need it to print each customer (which is within the dict) and every Account associated with that customer. In the future I will need every transaction associated with that account. I did it in Java (and it works) as follows:
        for (Customer c : customerMap.values()) {
        // Print the customer name, address, etc.
        System.out.println("\n**********Customer**********");
        System.out.println("Customer Number: " + c.getCustomerNumber());
        System.out.println(c.getCustomerName());
        System.out.println(c.getCustomerAddress());
        System.out.println(c.getCustomerCity() + ", "
                + c.getCustomerState() + " " + c.getCustomerZipCode());
        System.out.println(c.getCustomerPhone());
        for (Account a : c.getAllAccounts()) {
            // Print the account balance, id, type
            System.out.println("\t**********Account**********");
            System.out.println("\tAccount Number: " + a.getAccountNumber());
            if (a.getAccountType() == true) {
                System.out.println("\tAccount Type: Checking");
            } else {
                System.out.println("\tAccount Type: Savings");
            }
            System.out.println("\tAccount Balance: " + a.getBalance());
            System.out.println("\tInterest Rate: " + a.getInterestRate());
            for (Transaction t : a.getAllTransactions()) {
                // Go through the transactions of this account
                System.out.println("\t\t**********Transactions**********");
                System.out.println("\t\tTransaction Date: " + t.getDate());
                System.out.println("\t\tTransaction Amount: "
                        + t.getAmount());
                if (t.getDebitOrCredit() == true) {
                    System.out.println("\t\tDebit or Credit: Credit");
                } else {
                    System.out.println("\t\tDebit or Credit: Debit");
                }
                System.out.println("\t\tMemo: " + t.getMemo());

            }// for
        }// for
    }// for

Your help is much appreciated

A: Iterating over a dict's items:
>>> d = {"a": 1, "b": 2, "c": 3}
>>> for k, v in d.items():
...     print "{}={}".format(k, v)
...
a=1
c=3
b=2

Iterating over a dict's keys:
>>> for k in d.keys():
...     print k
...
a
c
b

Iterating over a dict's values:
>>> for v in d.values():
...     print v
...
1
3
2

Iterating over a list:
>>> xs = [1, 2, 3]
>>> for x in xs:
...     print x
...
1
2
3
>>>

Note(s):

*

*DO NOT name your variables dict or list as they shadow the builtins and could cause you problems.

A: Check out this line of code:
    for key1 in dict[key].getAccount()[key1]:

You can't define key1 with a reference tokey1

A: To iterate through a list, you can do the following:
a = [1,2,3,4,5]

for item in a:
    print item

1
2
3
4
5

the word 'item' above was arbitrary, I could have used pretty much anything:
for i in a:
    print i+1

2
3
4
5
6

but essentially, it's:
for element in listname:
    do something

There are other ways, but here are some docs: http://www.diveintopython.net/file_handling/for_loops.html
To iterate over a dict
you can do:
for key in d.keys(): # iterates through a list of the dict d's keys
    some code..

for value in d.values(): #iterates through a list of dict d's values
    some code..

for key, value in d.items(): #iterates through a list of key/value pairs from d
    code code...


text:
Q: Implementing "in portions" writable stream in node.js Here's some code
const fs = require('fs');
const stream = require('stream');
const db = require('some-db-engine');

const readStream = fs.createReadStream('file.dat');
const transformStream = new stream.Transform({
    objectMode: true,
    highWaterMark: 1000,
    transform(chunk, encoding, callback) {
        const obj = { /* somehow transform input chunk to object */ };
        this.push(obj);
        callback();
    }
});
const writableStream = new stream.Writable({
    objectMode: true,
    highWaterMark: 1000,
    writev(chunks, callback) {
        /* chunks should be a buffered array of objects no more than 1000 items */
        db.query('dump all chunks () in one move', callback);
    }
});

stream.pipeline(
    readStream,
    transformStream,
    writableStream,
    (error) => {
        if (error) {
            console.error(error);
        } else {
            console.log('Success!');
        }
    }
);

What I want is writableStream to temporarily buffer incoming objects in portions by 1000 items, so the data is written to db in large portions at once. Instead writev method always recieves the array of exactly one element.
Of cource, I could implement my own internal buffer, just wondering am I missing something and if it's doable using native api: highWaterMark or writable.cork() or other?
UPDATE
While waiting I've come up with this solution so far:
const createChunkedStream = (size) => {

    const queue = [];

    const process = (stream, end, chunk, callback) => {
        end || queue.push(chunk);
        if (queue.length >= (end ? 1 : size)) {
            stream.push(queue.splice(0));
        }
        callback();
    };

    return stream.Transform({
        transform(chunk, encoding, callback) {
            process(this, false, chunk, callback);
        },
        flush(callback) {
            process(this, true, null, callback);
        }
    });

};

That can be used as
stream.pipeline(
    readStream,
    transformStream,
    createChunkedStream(1000),
    writableStream,
    (error) => { /* ... */ }
);


text:
Q: Set multiple keys on firebase database using js So I need to create a more complex DB on my firebase project, and while I can create this DB on firebase console I cant do that using js.
database.ref('fcmTokens8').child('Users').child(firebaseUser.uid).set(
                        {
                            TIME: timeDate,
                            SUB: false
                        }
                    );

This is my code and works fine as it is but I need the "SUB" to have some additional IDs like "TOKEN" and "STATUS". How should I implement that?

A: database.ref('fcmTokens8').child('Users').child(firebaseUser.uid).set(
                        {
                            TIME: timeDate,
                            SUB: {
                                    TEMP: "1",
                                    TEMP2: "2"
                                 }
                        }
                    );


text:
Q: Node Exporter shows Wrong Idle CPU time I have set up a monitoring system using prometheus, with AWS EC2 Auto discovery, and node exporter. Using the following formula to get CPU Utilization:
100 - (avg by (instance) (irate(node_cpu_seconds_total{instance="instancexyz" ,mode="idle"}[5m])) * 100)
However, in one particular ASG, I am getting CPU percentage in large negative values. I opened the instance:9100/metrics link and found the idle values to be large exponential values. Here is one value I got:
node_cpu_seconds_total{cpu="0",mode="idle"} 4.25766215e+06
The metrics are working fine on all my instances except for few ones. Any idea what is happening?

A: Those "large exponential values" you are seeing are cumulative. I.e. the CPU (or all CPU cores?) have been idle for 1000+ hours (4.25e6 / 3600) since the VM was started, so they look very reasonable.
The reason you are getting negative values is because of sampling. In theory all samples are exactly scrape_interval seconds apart to the millisecond and the network latency and exporter processing time for each scrape is exactly the same. In practice, scrapes may be delayed or even skipped, network latency varies and your target VM can have its CPU pegged every now and then (or hang for any reason).
Meaning that e.g. it's perfectly possible for one sample of node_cpu_seconds_total to have value V at (nominally) time T and value V + 1 at (nominally) time T + 10s, resulting in an idle ratio of 110%. Or whatever values you care to come up with. irate exacerbates this problem because it always looks at two successive samples, increasing the relative measurement error (the error relative to the time between the samples).
There's nothing you can do about this except accept it's not a perfect measurement and slap a clamp_min(<your_expression>, 0) on top of it. Using rate instead of irate might also reduce the error and is generally a good idea unless you're looking at your data at full resolution.


text:
Q: Open links to application from Chrome The thing I would like to achieve is that I have an Intranet portal which uses links
like
<a href=" /files/x.docx"> x.docx < /a >

to open an MS-Word application.
When I'm in firefox I use customize options in

tools-> options -> application-> microsoft-word-2007: use microsoft word 2007

This does work and the link opens directly in MS-word without any question, but chrome does not have this option in settings.
In Chrome it asks "download or open this link". I need to cancel this step like "chrome download page" that open directly links.

A: You cannot force which application opens the file; HTML only transmit the data, the browser is free to display it the way it wants. HTML content will be showed directly, and other documents will be forwarded usually to the default application configured on that computer.
You could though redirect to an online service like "OnlineOffice" or Google Docs with the url  of the file to open.


text:
Q: Почему некорректно работает компонент Navs (Bootstrap 4) в связке с Vue.js? Во Vue компоненте есть массив pages, каждый элемент которого представляет из себя хеш.
Список табов отображаю так:

        Page #{{index + 1}}

На этом этапе все работает.
Следующим шагом необходимо реализовать соответствующий каждому табу контент. Я это делаю так:

    {{index + 1}}

И это работает неправильно.
Например, у меня 3 страницы, то есть три таба и три соответствующих контента. При нормальном раскладе я должен получить следующее:

*

*Вкладка Page #1 имеет в контенте цифру 1

*Вкладка Page #2 имеет в контенте цифру 2

*Вкладка Page #3 имеет в контенте цифру 3

В результате же  каждый таб имеет список всех index + 1. Притом каждая цифра на новой строке, так как она "упакована" в:

2

Вообще сгенерированный код выглядит так:

Page #1

Page #2

Page #3

                1

                2

                3

При смене таба класс active у контента меняется.
Притом если заменить Vue цикл у контента на простой HTML код:

1

2

3

То все будет работать.
Предполагаю, что моя реализация - асинхронна. И JS библиотека от Bootstrap 4 просто не видит список контента, которому судя по всему этой библиотеке нужно что-то "подцепить".
Как это исправить подскажите, пожалуйста?

A: Нужно было разделить class в этой строке:

На:
class="tab-pane" :class="{ 'active': index == 0 }"

Не знаю почему так, но это помогло.


text:
Q: How to remove any utf8mb4 characters in string Using C# how can utf8mb4 characters (emoji, etc.) be removed from a string, so that the result is full utf8 compliant.
Most of the solutions involve changing the database configuration, but unfortunately I don't have that possibility.

A: This should replace surrogate characters with a replacementCharacter (that could even be string.Empty)
This is a MySql problem, given the utf8mb4. Here there is the difference between utf8 and utf8mb4 in MySql. The difference is that utf8 doesn't support 4 byte utf8 sequences. By looking at the wiki, 4 byte utf8 sequences are those > 0xFFFF, so that in utf16 require two char (that are named surrogate pairs). This method remove surrogate pairs characters. When found "coupled" (a high + a low surrogate pair), then a single replacementCharacter is substituted, otherwise a orphan (wrong) high or a low surrogate pair is replaced by a replacementCharacte.
public static string RemoveSurrogatePairs(string str, string replacementCharacter = "?")
{
    if (str == null)
    {
        return null;
    }

    StringBuilder sb = null;

    for (int i = 0; i < str.Length; i++)
    {
        char ch = str[i];

        if (char.IsSurrogate(ch))
        {
            if (sb == null)
            {
                sb = new StringBuilder(str, 0, i, str.Length);
            }

            sb.Append(replacementCharacter);

            // If there is a high+low surrogate, skip the low surrogate
            if (i + 1 < str.Length && char.IsHighSurrogate(ch) && char.IsLowSurrogate(str[i + 1]))
            {
                i++;
            }
        }
        else if (sb != null)
        {
            sb.Append(ch);
        }
    }

    return sb == null ? str : sb.ToString();
}


text:
Q: Can WPF Controls be re-used? For example, I have created a button with a check mark drawn on it.  I need to use it in a couple places in my window.
<Button Width="25">
    <!-- Draw a Green checkmark -->
    <Polyline Points="2,5,6,10,13,1" Stroke="Green" StrokeThickness="4" StrokeLineJoin="Round" StrokeStartLineCap="Round" StrokeEndLineCap="Round" />
</Button>

Since I only want to change the content, I'm not sure if Styles or Templates apply.  Do I need to create a UserControl?
Edit: This can be accomplished with a style.  But, I only want to change the content and I don't want to override the current style.

A: Create a UserControl with the contents of the button you created if you want to have some sort of dynamic capability to it i.e. add new properties.  If you just have a button that just has the visual appearance to have a check then I'd use a style.

A: This is crying out for a style.  Add the following Style to your Window.Resources:
<style TargetType="Button" x:Key="tick">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <Polyline Points="2,5,6,10,13,1" Stroke="Green" StrokeThickness="4" StrokeLineJoin="Round" StrokeStartLineCap="Round" StrokeEndLineCap="Round" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

and you can then define your button as:
<Button Width="25" Style="{StaticResource tick}" />

A: Create a UserControl with the contents of the button you created. The easiest option to create the user control is to use Expression Blend. Select all of our controls to whom u want to make UserControl. Right Click and Select "make into Usercontrol". Thats it. U can use this control anywhere in your project just by drag and drop.
Hope it will help u,
Saghar Ayyaz


text:
Q: How to update a mailchimp template automatically using node.js How do I update a mailchimp template automatically using node.js.
So if I changed the index.html from the github email repo, it would update the mailhimp template inside mailchimp itself.

A: Unfortunately, you won't be able to update a MailChimp template from Node.js just by editing a html file in a github repo.
You'll have to use the MailChimp API. You can access the API's directly or you can use one of the MailChimp API wrappers for Node.js. mailchimp-api-node is the official MailChimp wrapper, but I use node-mailchimp
Depending on what you're updating, the two API's you should look into are:
/campaigns/template-content to just update the content portion of the template https://apidocs.mailchimp.com/api/2.0/campaigns/template-content.php
/templates/update to update your user templates (not campaign content) to be used in campaigns https://apidocs.mailchimp.com/api/2.0/templates/update.php
Note: These are version 2.0 API's. I haven't had a chance to work with the new version 3.0 API's yet so there may be changes. Version 2.0 API's still work but they just aren't being updated anymore.


text:
Q: Mutablestateof - State hoisting What to do to manage one state in two functions? (openDialog)
How to transfer openDialog state from ProductDialog() to AppBar()?
I know I can make a separate class per state but I don't want to.
@Composable
fun ProductDialog() {
    val openDialog = rememberSaveable() { mutableStateOf(true) }
    val productNameState = remember { mutableStateOf("") }

    AlertDialog(
        onDismissRequest = { openDialog.value = false },
        title = { Text(
            modifier = Modifier.padding(bottom = 8.dp),
            text = "Add new product",
            fontSize = 20.sp,
            fontWeight = FontWeight.Bold
        ) },
        confirmButton = { Button(onClick = { openDialog.value = false }) {
            Text(text = "Add") }
        },
        dismissButton = { Button(onClick = { openDialog.value = false }) {
            Text(text = "Cancel")
            }
        },
        text = {
            Column() {
                TextField(value = productNameState.value, onValueChange = {
                })
                TextField(value = productNameState.value, onValueChange = {})
            }
        }
    )
}

@Composable
fun AppBar() {
    val openDialog = rememberSaveable() { mutableStateOf(false) }

    if (openDialog.value) ProductDialog()

    Scaffold(
        topBar = {
                TopAppBar(
                    actions = { Icon(imageVector = Icons.Default.Menu, contentDescription = null) },
                    title = { Text(text = "Shopping List Compose") })
                },
        floatingActionButton = {
            FloatingActionButton(modifier = Modifier.padding(10.dp), onClick = { openDialog.value = true }) {
            Icon(Icons.Default.Add, contentDescription = null)
        }}
    ) {
        ListItems()
    }
}

What to do to manage one state in two functions? (openDialog)

A: From the example you shared, it seems that the only use of openDialog in ProductDialog is to close the dialog. You can instead paas a lambda to ProductDialog to close the dialog.
@Composable
fun ProductDialog(closeDialog: () -> Unit) {
    AlertDialog(
        onDismissRequest = closeDialog,
        title = { ... },
        confirmButton = {
            Button(onClick = closeDialog) {
                Text(text = "Add")
            }
        },
        dismissButton = {
            Button(onClick = closeDialog) {
                Text(text = "Cancel")
            }
        },
        text = { ... }
    )
}

@Composable
fun AppBar() {
    val openDialog by rememberSaveable() { mutableStateOf(false) }

    if (openDialog) ProductDialog { openDialog = false}

   ...
}


text:
Q: Dynamically binding title tag in vuejs I'm new to vuejs.
I try to bind data on the title tag dynamically. I used vue-head to do this on a simple html page. I do not use webpack and npm.
This is how I bind the title tag :
var app = new Vue({
            el: 'html',
            head: {
              title: function () {
                return {
                    inner: this.remaining + ' Tâches',
                    separator: ' ',
                    complement: ' '
                }
              }
            }

In the vue-head documentation, they suggest to do this :
methods: {
  getAsyncData: function () {
    var self = this
    window.setTimeout(function () {
    self.title = 'My async title'
    self.$emit('updateHead')
    }, 3000)
  }
},

I also tried to set it in the watch prop, but it didn't work.
Here is my entire code : https://jsfiddle.net/5d70s0s6/1/
Thanks

A: Use a computed property.
computed: {
  title: {
    get() {
      document.title = this.remaining
      return this.remaining
    },
    set(val) {
      document.title = val
    }
  }
}

You don't need to use <title>{{title}}</title>. If you change title in your Vue, it will be applied automatically to the page.
Also, you should not bind a Vue instance to html, head or body tags. Use regular elements only like

 and set your Vue el: '#app'
Or you could use this:
data: {
  title: '',
},
watch: {
  title(val) {
    document.title = val
  }
}

Update:
While the code above can solve your problem. I created this tiny vue-title component that can be used in your project easily.
Example:
<vue-title>{{title}}</vue-title>


text:
Q: TTS Discord Bot I'm coding a discord bot but in TTS command I tried to run it but it doesn't work with this code (I have installed  npm i discord-tts ) so I tried everything to make it work but it doesn't, I wanted to know that did I missed something?
const discordTTS = require("discord-tts");
const Command = require('../Command.js');

module.exports = class SpeakCommand extends Command {
    constructor(client) {
        super(client, {
            name: 'speak',
            usage: 'speak <message>',
            description: 'Speaks TTS message.',
            type: client.types.FUN
        });
    }

    async run(message, args) {

        function tts(voiceChannel, text) {
            const broadcast = bot.voice.createBroadcast();
            var channelId = message.member.voice.channelID;
            var channel = bot.channels.cache.get(channelId);
            channel.join().then(connection => {
            broadcast.play(discordTTS.getVoiceStream(args));
            const dispatcher = connection.play(broadcast);

            });

        };
    }
}

A: You only wrote the function.
Call the function and fill the params.


text:
Q: Use Jenkins variable in Dockerfile command I am new to Docker and Jenkins. I have to build and deploy Nest Js app in jenkins. When I run the Jenkins job I have to select the 'DEPLOY_PROFILE' which is equals to 'dev' and 'qa' as follows.

This is my Dockerfile,
    FROM node:16-alpine
    WORKDIR /app
    ADD package.json /app/package.json
    RUN npm config set registry http://registry.npmjs.org
    RUN npm install
    ADD . /app
    EXPOSE 3000
    CMD ["npm", "run", "start"]

I need to pass the 'DEPLOY_PROFILE' variable which is equals to 'dev' or 'qa' to the Dockerfile. Then final docker command should be look like npm run start:dev or npm run start:qa
I have tried using
CMD ["npm", "run", "start", `:${DEPLOY_PROFILE}`]

and
CMD ["npm", "run", "start", `:${env.DEPLOY_PROFILE}`]

But nothing gave me the luck. Any help may highly appreciated!

A: You can use an environment variable for that. In your dockerfile, declare an argument (passed into docker build) and an environment variable like this:
ARG DEPLOY_PROFILE
ENV PROFILE=${deploy_profile}

Then use the environment variable like this:
CMD npm run start $PROFILE

Then call buildah (or whatever you are using) like this:
 buildah bud --format=docker --build-arg deploy_profile="$DEPLOY_PROFILE"


text:
Q: Memory not freed by Application until GC is explicitly called I am launching many threads simultaneously, each one writing / reading data into/from a queue; Data is dequeued progressively while it is processed and stored to DB. For some reason the memory is not freed although the Queues are empty and I made sure all event subscription between the data reader and the data processor are unsubscribed at the end of the threads.The amount of squatted RAM is Exactly the amount of the data that is read by binary readers and put into queues.
In order to isolate the problem, I have bypassed the Processing and the DB Storing step.
Why would be the RAM still squatted long after all threads are finished, until I explicitly call GC.Collect() or terminate the program? I manually nullified the Queue after it is emptied, and also nullified the Binary Reader that read the data. I thought that would be enough for the GC to wake up and do its housekeeping at least after a few minutes.

EDIT :
The (reformulated after deletion) QUESTION :
In short, I was always told that the default GC behaviour managed the memory properly and that I shall almost never call the GC explicitly and let the framework do the job.
I would like to know why in this case memory usage drops down only when an explicit Call is made to GC.Collect
EDIT : Without GC Collect

With GC Collect (Called on a regular basis)

A: There are three conditions when a Garbage collection might occur (see MSDN):

1.) The system has low physical memory.
2.) The memory that is used by allocated objects on the managed heap
  surpasses an acceptable threshold. This means that a threshold of
  acceptable memory usage has been exceeded on the managed heap. This
  threshold is continuously adjusted as the process runs.
3.) The GC.Collect method is called. In almost all cases, you do not have
  to call this method, because the garbage collector runs continuously.
  This method is primarily used for unique situations and testing.

From your description it sounds like the framework decided neither 1.) nor 2.) are the case hence it will only collect when you call GC.Collect()

A: Based on the screenshot, it appears that your memory usage never goes over 50% during the entire run of the application.  It's much faster for the .NET framework to leave that memory alone than to stop your application (or at least take up a lot of CPU time in checking for liveness) in order to collect the garbage.  If you cut your machine's RAM to 2 GB or so, I'm sure that the garbage collector would step up and keep memory usage within the hardware limits.

A: It seems you are leaking objects you should use windbg to create a dump then use sos.dll to track root for your objects.
You can follow this explanation on how to track "roots" for your objects and see what is causing these leaks.


text:
Q: Updating env file from command line in laravel I want to update database password inside the env file. I want to update the db_password variable.
I am trying the following command after navigation to /var/www/html
php artisan env:set db_password=myPassWordHere
And I am getting error.
PHP Fatal error:  Uncaught UnexpectedValueException: The stream or file "/var/www/html/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied in /var/www/html/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:107

Full error
PHP Fatal error:  Uncaught UnexpectedValueException: The stream or file "/var/www/html/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied in /var/www/html/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:107
Stack trace:
#0 /var/www/html/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(37): Monolog\Handler\StreamHandler->write(Array)
#1 /var/www/html/vendor/monolog/monolog/src/Monolog/Logger.php(337): Monolog\Handler\AbstractProcessingHandler->handle(Array)
#2 /var/www/html/vendor/monolog/monolog/src/Monolog/Logger.php(616): Monolog\Logger->addRecord(400, Object(UnexpectedValueException), Array)
#3 /var/www/html/vendor/laravel/framework/src/Illuminate/Log/Writer.php(202): Monolog\Logger->error(Object(UnexpectedValueException), Array)
#4 /var/www/html/vendor/laravel/framework/src/Illuminate/Log/Writer.php(113): Illuminate\Log\Writer->writeLog('error', Object(UnexpectedValueException), Array)
#5 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundati in /var/www/html/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php on line 107
PHP Fatal error:  Uncaught UnexpectedValueException: The stream or file "/var/www/html/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied in /var/www/html/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:107

How can I update db_password variable inside env file, using command line?

A: Check that the log file exists and that it has write permissions:
ls -l /var/www/html/storage/logs/laravel.log

If it's not writable, run:
chmod 755 /var/www/html/storage/logs/laravel.log

A: You can use the Github Package https://github.com/svenluijten/flex-env
After the Successful Package Installation
For Example
If you want to add new constant to .env File
Maybe if you want to add ADMIN_EMAIL with the value admin@app.com
php artisan env:set ADMIN_EMAIL admin@app.com

A: I had a similar issue and was able to resolve it by running the following set of commands.
php artisan route:clear
php artisan config:clear
php artisan cache:clear

(In that order)


text:
Q: MVVM like wizard I am currently building an MVVM based application. The application should also have a wizard in MVVM style. The wizard is not a normal wizard, its a particular kind of a wizard. My goal is to implement a wizard with
1.) has also multiple branches. The wizard can guide you in other direction. So the wizard must not be straightforward.
2.) can also have short cuts. You can skip some pages where default values are setted.
3.) is also normal - straightforward.
Note, some information in the wizrad pages are on-the-fly. That means, that the information can be passed between each step and processed.
Are there any approaches like patterns to solve my problem? How do I implement it the best way?

A: Did you read this good article in Code Project about Wizard in MVVM and written by two MVVM guru:
http://www.codeproject.com/KB/WPF/InternationalizedWizard.aspx?display=Print

A: You might have a look at the ViewModel sample application of the WPF Application Framework (WAF). It shows how to implement a Wizard in a MVVM way.

A: If your wizard has a single VM that stores the state/results of each step and sits behind a view that is a user control...
You could have a Frame on the wizard view that requires 2 events in the code behind (This obviously depends on if your MVVM architecture can live with this?).
Event 1) When the binding of your wizards step raises its NotifyPropertyChanged: tell your frame to "Navigate" to the appropriate page (as described in a property in your wizard VM).
Event 2) On the frames "Navigated" event so that you can point the current pages data-context at your VM.
This way the wizard viewmodel controls the state of the wizard from start to finish and it also can describe the steps, which can easily be added to, edited, etc.
Obviously this may not sit well with everyone's view of MVVM.


text:
Q: Why do we implement adders via serial full adders as opposed to an optimized logic circuit? In my little time studying digital systems, it seems that textbooks immediately jump to the fact that we implement adders via serial (i.e. the chaining together of) full adders. It's not a priori clear to me why we do this. In particular, since this is still a combinational circuit, why can't we write out the truth table (obviously, for large numbers we'd let CAD systems do this) and derive an optimized set of logic functions for each sum bit and the final carry out bit? Is this intractable? Is this equivalent to the serial full adder implementation? Any references discussing why we don't do this would be greatly appreciated!
EDIT to the above: I am familiar with lookahead adders and the like. The fact remains that these "begin" with chaining together one-bit adders, admittedly with some slick optimizations. Again, it's not a priori clear to me why we don't implement the "full" n-bit adder with combinational logic optimization techniques.

A: For the smallest circuit, the truth table would be best satisfied by the chain of full adders with ripple carry.
Or it could be done by a look-up table (a ROM), which would use vastly more gates and therefore either be slower or a waste of gates or both, for nearly all adder applications. The latter is weighing up the huge number of small counters in logic designs as well as the fewer large CPU ALU adders.

A: For volume production the one bit full adder is implemented in silicon as a highly optimised cell, optimised for speed and silicon area).
It is usually better in terms of silicon area to use this optimised cell for multiple adders rather than breaking down the adders into their resulting logic functions, which get very complex very quickly, and then implementing them as gates that do not have this optimisation.

A: Adder structure is inherently sequential because of the carry propagation. Think about how we add numbers together. If you have 1001 + 9999, you'll need to wait for the carry to propagate all the way through from the least significant digits to the most significant digit.
All the look ahead adders are attempting to shorten the carry propagation delay by adding more gates. For example, the Kogge-Stone Adder has logarithmic carry propagation delay instead of the linear delay of a ripple adder.
In fact, this is a big problem when fast counters are required. When you have a large pipeline that runs as fast as the technology would allow you need to count the number of cycles until it is filled. However, a counter comprising an adder cannot propagate as fast. To avoid this we use linear-feedback shift registers. Instead of counting from 0 to 99, they produce a seemingly random sequence of length 100, e.g. 256, 147, 5 etc. However, the propagation delay is one logic gate.