text:
Q: ¿Como puedo tomar el valor de un textarea y que al almacenarlo en una variable, respete los saltos de lineas y espacios del textarea? Tengo un apartado para notas rápidas pero al guardarlas en un archivo (.txt) me guarda el valor del textarea en una sola linea y quiero que se respete los saltos de linea y los espacios;
Ejemplo:
Valor o texto que ingreso al textarea:

HOLA MUNDO
  HOLA MUNDO
  HOLA MUNDO
  HOLA MUNDO

Valor que guarda en el archivo (.txt):

HOLAMUNDOHOLAMUNDOHOLAMUNDOHOLAMUNDO

Código HTML
<textarea placeholder="Escribir..."
          id="input_textarea"
          style="width: 370px;
                 height: 150px;
                 margin-top: 25px;
                 margin-left: 16px;
                 margin-right: 16px;">
</textarea>

Código JavaScript
function guardar_notas_txt()
    {
        var textToWrite = input_textarea.value;
        var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
        var file_name = nombre_guardado_notas.value;
        var fileNameToSaveAs = file_name+".txt";
        var downloadLink = document.createElement("a");
        downloadLink.download = fileNameToSaveAs;
        downloadLink.innerHTML = "My Hidden Link";
        window.URL = window.URL || window.webkitURL;
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
        downloadLink.click();
    }

function destroyClickedElement(event)
    {
        document.body.removeChild(event.target);
    }

A: Intenta con esta función regex al momento de capturar el valor de tu textarea:
var textToWrite = input_textarea.value.replace(/\n/g, "\r\n");

Demo:

function guardar_notas_txt() {

  var textToWrite = input_textarea.value.replace(/\n/g, "\r\n");
  var textFileAsBlob = new Blob([textToWrite], {
    type: 'text/plain'
  });
  var file_name = "archivo";
  var fileNameToSaveAs = file_name + ".txt";
  var downloadLink = document.createElement("a");
  downloadLink.download = fileNameToSaveAs;
  downloadLink.innerHTML = "My Hidden Link";
  window.URL = window.URL || window.webkitURL;
  downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
  downloadLink.onclick = destroyClickedElement;
  downloadLink.style.display = "none";
  document.body.appendChild(downloadLink);
  downloadLink.click();
}

function destroyClickedElement(event) {
  document.body.removeChild(event.target);
}
<textarea placeholder="Escribir..." id="input_textarea" style="width: 370px;
                 height: 150px;
                 margin-top: 25px;
                 margin-left: 16px;
                 margin-right: 16px;">
</textarea>
<br>
<button onclick="guardar_notas_txt();">Guardar</button>


text:
Q: Model Binding in mvc core Issue I have a POCO class with this definition
public class IndOff
{
    public int Id { get; set; }

    [Display(Name = "Member Name")]
    [Required]
    public int MemberID { get; set; }
    public OfferingType OfferingType { get; set; }
    [Display(Name = "Offering Type")]
    [Required]
    public int OfferingTypeID { get; set; }

    public Currency Currency { get; set; }
    [Display(Name = "Currency")]
    [Required]
    public int CurrencyID { get; set; }
    public Member Member { get; set; }

    public double Amount { get; set; }
    public DateTime Date { get; set; }

}

Then i defined a View Model on this class as
public class IndOffViewModel
{
    public IndOffViewModel()
    {

    }
    public IEnumerable<Currency> Currencies { get; set; }
    public IEnumerable<OfferingType> OfferingTypes { get; set; }
    public Member Member { get; set; }
    public IndOff IndOff { get; set; }
}

From my controller, the view to capture data is rendered correctly, the problem occurs when i post data.
My post action is
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Save(IndOff model, int memberId)
    {
        model.Date = DateTime.Today;
        if (!ModelState.IsValid)
        {
            var member = _context.Members.Single(m => m.Id == memberId);
            var viewModel = new IndOffViewModel
            {
                Member = member,
                Currencies = _context.Currencies.ToList(),
                OfferingTypes = _context.OfferingTypes.ToList()
            };
            return View("IndForm", viewModel);
        }
        if (model.Id == 0)
            _context.IndOffs.Add(model);
        else
        {
            var dbIndOff = _context.IndOffs.Single(c => c.Id == model.Id);
            dbIndOff.Amount = model.Amount;
            dbIndOff.CurrencyID = model.CurrencyID;
            dbIndOff.OfferingTypeID = model.OfferingTypeID;
            //dbIndOff.WorshipCenterID = weekOff.WorshipCenterID;
        }
        _context.SaveChanges();
        return RedirectToAction("New", new { id = model.Id});
    }

However, the IndOff model object passed is always empty with nulls for the properties. Though when i use chrome inspector, i see that the values has been passed to the controller.
What's the problem or what am i doing wrong? This is how the View page looks like
@model ViewModels.IndOffViewModel
@{
    ViewBag.Title = "Offering";
}
<form asp-action="Save" method="post">

    <select asp-for="IndOff.OfferingTypeID" asp-items="@(new SelectList(Model.OfferingTypes,"ID","Name"))" class="form-control">
        <option value="">-Select-</option>
    </select>

    <select asp-for="IndOff.CurrencyID" asp-items="@(new SelectList(Model.Currencies,"Id","Name"))" class="form-control">
        <option value="">-Select-</option>
    </select>

    <input asp-for="IndOff.Amount" class="form-control" />

@*

        <input asp-for="Member.Baptised" />
        Baptised ?

*@
<input type="hidden" asp-for="IndOff.Id" />
<input type="hidden" asp-for="Member.Id" name="memberId" />
<input type="submit" value="Submit" class="btn btn-primary" />
</form>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

A: Do you use your ViewModel to generate your form?
In that case, the binding won't work because the path to the propertis doesn't match.
The html input tag's id will be "IndOff.{fieldName}".
But your controller take IndOff and not IndOffViewModel as parameter.
The path to IndOff's properties is then "{fieldnName}".
To solve this binding issue, your ViewModel could extend IndOff instead of containing the IndOff property.

A: Because the IndOff class in contained inside of the IndOffViewModel, you need to give the action a "hint" about where to start looking using the Bind attribute. Like so:
public ActionResult Save([Bind(Prefix="IndOff")]IndOff model, int memberId)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get correct infromation with params? I added column information to model User, that was generated by devise. I don't want to make user to fill field Information by registration. I created controller for other pages like profile
class PagesController < ApplicationController

  def myprofile
    @currentUser = User.find_by_id(current_user.id)
  end

  def userinfo
    @currentUser = User.find_by_id(current_user.id)

    if request.post?
      if @currentUser.update(params[:userinfo].permit(:information))
        redirect_to myprofile_path
      else
        render 'userinfo'
      end
    end
  end

end

On page userinfo user should be able to edit his information.
Here is view:

Hey, <%= @currentUser.username %>, add some information about you:

  <%= form_for @currentUser.information do |f| %>

      <%= f.label :information %>

      <%= f.text_area :information, autofocus: true %>

      <%= f.submit "Save" %>

  <% end %>

Application Controller:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :information, :email, :password, :password_confirmation, :remember_me) }
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :information, :email, :password, :remember_me) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :information, :email, :password, :password_confirmation, :current_password) }
  end
end

When I try to save it, I get

undefined method `permit' for nil:NilClass

How can I fix it? Maybe there is  better way to do this job? I don't want to show whole form to edit password, username etc. Only information.

A:
undefined method `permit' for nil:NilClass

You are doing it wrong. Your params will not contain :userinfo key. Your params will look like this :user => {:information => 'value'}. You should change your code to below
#controller
def userinfo
  @currentUser = User.find_by_id(current_user.id)

  if @currentUser.update(user_params)
    redirect_to myprofile_path
  else
    render 'userinfo'
  end
end

protected
def user_params
  params.require(:user).permit(:information)
end

And also as you are trying to update a certain record, you need to change
<%= form_for @currentUser.information do |f| %>

to
<%= form_for @currentUser, method: put do |f| %>

Finally if you have set a post route for this corresponding controller#action, then you need to change it to put


text:
Q: How to apply log function to dataframe in R? I have a dataframe named COMP with 24 columns in it. I would like to create another dataframe named COMPLog with log10 versions of all 24 columns/variables in it.
COMPLog <- lapply(COMP[,c(1:24)], function(x) log(x))

Error in log(x) : non-numeric argument to mathematical function

I've trawled through other questions and tried using df.log <- log(df) from one of the earlier questions, but I am unsure how to modify it for my situation. I've also tried mutate and transmute but I did not manage to get my code to work.
What code should I use to apply log10 to all of the variables in a dataframe? (and then to save it as another dataframe).


text:
Q: caching common lookup data - strategies Looking at implementing caching for some common lookup data in an asp.net web application.
In the past, I've created a singleton that creates a bunch of hashtables, which have public accessors.  This works pretty well for read-only data that never changes.
I've done a bit of looking into the System.Web.Caching, but it doesn't seem to offer any benefits over the singleton approach.  We're not using SQLServer, so we wouldn't be able to take advantage of the SQLCacheDependency for the rare cases where the data might change.
Anyone have experience with either of these alternatives?  Or have a better suggestion?

A: One benefit to the System.Web.Caching is that the memory is stored in the app pool. This is handy because it is very easy to setup memory/processing limits on application pools.
I ran into this when we were stress testing our application (Each user task requires costly computation). As we added more and more users, the cache took up all the available memory. Once we setup a memory limit on the app pool, everything took care of itself. The Cache has LRU algorithms to manage memory.
I don't know if the data in your cache is dependent on load, but if it is, this is a handy benefit.

A: I can't speak to the benefits of System.Web.Caching since, like you, I've typically implemented singleton instances of a lookup table data structure.  The singleton class also exposes an InvalidateCache() method to handle the rare cases where data might change.
If you're building a business object library for use in both asp.net and, for example, winforms then you might decide to avoid using System.Web.Caching.
The Business Object framework which I use provides a base class for lookup tables called NameValueListBase<TKey, TValue>.  This generic base class provides strongly typed helper methods.  You could develop a similar base class and expose your own helper methods as opposed to just exposing an instance of System.Collections.Generic.Dictionary.
The Business Object framework to which I refer is called CSLA.Net and is explained in great detail in Expert C# 2008 Business Objects.  There is also a version of the book available for VB.Net.

A: I have experience with both. I prefer the singleton pattern for the following reasons:

*

*It's not tied to asp.net

*It allows you to use the lookup in the bisiness layer to validate or whatever.

*It's easier to refactor if the lookup becomes more complicated and you decide not to cache it.


text:
Q: Python: Why is one function able to mutate an array in another function? I guess it's an issue of scope I'm confused. I don't understand how visited can be updated in numIslands by making a change in DFS.
The way I understood it was that visited, once passed into DFS, is like a copy of the original visited.
Is this not the case?
class Solution:
    def DFS(self, grid, visited, i, j):
        if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or visited[i][j] or grid[i][j] == '0':
            return
        visited[i][j] = True
        self.DFS(grid, visited, i+1, j)
        self.DFS(grid, visited, i-1, j)
        self.DFS(grid, visited, i, j+1)
        self.DFS(grid, visited, i, j-1)

    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid: return 0
        visited = [[False for i in range(len(grid[0]))] for j in range(len(grid))]
        count = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == '1' and visited[i][j] == False:
                    self.DFS(grid, visited, i, j) # TODO
                    count += 1
        return count

A:
The way I understood it was that visited, once passed into DFS, is like a copy of the original visited.

This is not true. Python never makes implicit copies for you. If you pass an object to a function, a copy of it is not made. You're simply giving the object associated with visited a second name visited within the scope of the function.
To actually have DFS operate independently of visited in numIslands, you'd need to make a deep-copy:
from copy import deepcopy

. . .

self.DFS(grid, deepcopy(visited), i, j)

Although this is often not a great idea since deepcopy is a rather expensive function, and I don't think you'd want to do that here anyways. The algorithm requires that DFS mutate visited. If it didn't, DFS wouldn't do anything since it never returns a value.


text:
Q: How to set logging level to DEBUG in Guacamole I'm just trying to set the log level of Guacamole to DEBUG.. I've successfully set the logging level for guacd and tried multiple environment variables for the guacamole container but it's still not working.. I've found a logging.properties file in the Guacamole container at path: /home/guacamole/tomcat/conf/logging.properties. Is it possible to configure the logging file path so I can add a custom logging.properties file?
The current state of the deployment.yml file looks like this:
# apiVersion: v1
# kind: ConfigMap
# metadata:
#   name: logback
#   namespace: $NAMESPACE
# data:
#   logback.xml: |
#     <configuration>
#
#     <!-- Appender for debugging -->
#     <appender name="GUAC-DEBUG" class="ch.qos.logback.core.ConsoleAppender">
#         <encoder>
#             <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
#         </encoder>
#     </appender>
#
#     <appender name="GUAC-DEBUG-2" class="org.apache.juli.ClassLoaderLogManager">
#         <encoder>
#             <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
#         </encoder>
#     </appender>
#
#     <!-- Log at DEBUG level -->
#     <root level="debug">
#         <appender-ref ref="GUAC-DEBUG"/>
#     </root>
#
#     <root level="debug">
#         <appender-ref ref="GUAC-DEBUG-2"/>
#     </root>
#
#     </configuration>

apiVersion: v1
kind: ConfigMap
metadata:
  name: logging
  namespace: $NAMESPACE
data:
  logging.properties: |
    handlers = 1catalina.org.apache.juli.AsyncFileHandler, 2localhost.org.apache.juli.AsyncFileHandler, 3manager.org.apache.juli.AsyncFileHandler, 4host-manager.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler

    .handlers = 1catalina.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler

    ############################################################
    # Handler specific properties.
    # Describes specific configuration info for Handlers.
    ############################################################

    1catalina.org.apache.juli.AsyncFileHandler.level = FINE
    1catalina.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
    1catalina.org.apache.juli.AsyncFileHandler.prefix = catalina.
    1catalina.org.apache.juli.AsyncFileHandler.encoding = UTF-8

    2localhost.org.apache.juli.AsyncFileHandler.level = FINE
    2localhost.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
    2localhost.org.apache.juli.AsyncFileHandler.prefix = localhost.
    2localhost.org.apache.juli.AsyncFileHandler.encoding = UTF-8

    3manager.org.apache.juli.AsyncFileHandler.level = FINE
    3manager.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
    3manager.org.apache.juli.AsyncFileHandler.prefix = manager.
    3manager.org.apache.juli.AsyncFileHandler.encoding = UTF-8

    4host-manager.org.apache.juli.AsyncFileHandler.level = FINE
    4host-manager.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
    4host-manager.org.apache.juli.AsyncFileHandler.prefix = host-manager.
    4host-manager.org.apache.juli.AsyncFileHandler.encoding = UTF-8

    java.util.logging.ConsoleHandler.level = FINE
    java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
    java.util.logging.ConsoleHandler.encoding = UTF-8

    ############################################################
    # Facility specific properties.
    # Provides extra control for each logger.
    ############################################################

    org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = FINE
    org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = 2localhost.org.apache.juli.AsyncFileHandler

    org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = FINE
    org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = 3manager.org.apache.juli.AsyncFileHandler

    org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].level = FINE
    org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].handlers = 4host-manager.org.apache.juli.AsyncFileHandler

    # For example, set the org.apache.catalina.util.LifecycleBase logger to log
    # each component that extends LifecycleBase changing state:
    #org.apache.catalina.util.LifecycleBase.level = FINE

    # To see debug messages in TldLocationsCache, uncomment the following line:
    #org.apache.jasper.compiler.TldLocationsCache.level = FINE

    # To see debug messages for HTTP/2 handling, uncomment the following line:
    #org.apache.coyote.http2.level = FINE

    # To see debug messages for WebSocket handling, uncomment the following line:
    #org.apache.tomcat.websocket.level = FINE
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: guacamole
  namespace: $NAMESPACE
  labels:
    app: guacamole
spec:
  replicas: 1
  selector:
    matchLabels:
      app: guacamole
  template:
    metadata:
      labels:
        app: guacamole
    spec:
      containers:
      - name: guacd
        image: docker.io/guacamole/guacd:$GUACAMOLE_GUACD_VERSION
        env:
        - name: GUACD_LOG_LEVEL
          value: "debug"
        ports:
        - containerPort: 4822
        securityContext:
          runAsUser: 1000
          runAsGroup: 1000
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
      - name: guacamole
        image: docker.io/guacamole/guacamole:$GUACAMOLE_GUACAMOLE_VERSION
        env:
        - name: GUACD_HOSTNAME
          value: "localhost"
        - name: GUACD_PORT
          value: "4822"
        - name: POSTGRES_HOSTNAME
          value: "database-url.nl"
        - name: POSTGRES_PORT
          value: "5432"
        - name: POSTGRES_DATABASE
          value: "guacamole"
        - name: POSTGRES_USER
          value: "guacamole_admin"
        - name: POSTGRES_PASSWORD
          value: "guacamoleadmin"
        - name: HOME
          value: "/home/guacamole"
        - name: GUACAMOLE_LOG_LEVEL
          value: "debug"
        - name: JAVA_TOOL_OPTIONS
          value: "-Djava.util.logging.config.file=/home/guacamole/logging.properties"
        ports:
        - name: http
          containerPort: 8080
        - name: https
          containerPort: 8443
        volumeMounts:
          # - name: logback
          #   mountPath: /home/guacamole/logback.xml
          #   subPath: logback.xml
          - name: logging
            mountPath: /home/guacamole/logging.properties
            subPath: logging.properties
        securityContext:
          runAsUser: 1001
          runAsGroup: 1001
          allowPrivilegeEscalation: false
          runAsNonRoot: true
      volumes:
        # - name: logback
        #   configMap:
        #     name: logback
        - name: logging
          configMap:
            name: logging

UPDATE 1:
According to this page it's possible to add custom logging configuration by adding the logback.xml file in the GUACAMOLE HOME folder, but this didn't fixed it. I've added this logback.xml file via a ConfigMap
UPDATE 2:
I can see in the logging of the Guacamole container it adds the following Java Option: -Djava.util.logging.config.file=/home/guacamole/tomcat/conf/logging.properties. So I added the following environment variable to edit this config path and added my own logging.properties file via a ConfigMap:
- name: JAVA_TOOL_OPTIONS
  value: "-Djava.util.logging.config.file=/home/guacamole/logging.properties"

I've updated the deployment.yml file so you can see the current state of the file.. According to the logging it updates the argument correctly, but one line later it overwrites the same argument with the old path..
Anybody ideas? :')

A: I got in contact with Guacamole support.
For the people they're experiencing the same issue because the people from Guacamole didn't documented this yet, you can use the environment variable LOGBACK_LEVEL.


text:
Q: Dummy/One Hot Encoding of Comma Separated column in Dask I have a column in a dask data frame that contains comma separated lists of different categories. I'm looking to replicate the functionality of sklearn's MultiLabelBinarizer or the pandas function pd.get_dummies(',') exactly as this thread describes: Create dummies from column with multiple values in dask
Is there absolutely no way to do this as the one answer there states? Is there a way to implement this if I got a list of all of the values?

A: If the list of all classes are known, then it's an easy task for dask:
import dask.dataframe as dd
import pandas as pd
from sklearn.preprocessing import MultiLabelBinarizer

df = pd.DataFrame({"col_a": ["c, d", "e", "g", "e, g", "d, e"]})
all_classes = ["c", "d", "e", "g"]
mlb = MultiLabelBinarizer(classes=all_classes)

def myfunc(df):
    return pd.DataFrame(mlb.fit_transform(df["col_a"].values), columns=all_classes)

ddf = dd.from_pandas(df, npartitions=2)

ddf.map_partitions(myfunc, meta=pd.DataFrame(columns=all_classes)).compute()

If the list is not known, then one option is to do a first pass through the dataframe, collecting all unique values, then integrating these classes into a snippet similar to above.


text:
Q: What's the difference between legal (illegal) and lawful (unlawful)? For example, why signage in national parks says "it's unlawful to feed wildlife" instead of illegal?

A: There is no difference in meaning.
In this case, "unlawful" is a synonym of "illegal." The sign could just as well read "it's illegal to feed wildlife" – it would mean the same thing to the vast majority of people.
The first definition the Merriam-Webster online dictionary gives for unlawful:

not lawful :  illegal

A: In the context of this sign and the US Park Service, there may be no difference between "unlawful" and "illegal".

Some laws prohibit certain activities, making them illegal, i.e. against the law. Most of the time there are penalties or sanctions against illegal activity.
Outside of criminal law, some laws prescribe or specify certain activities.  For example, contract law specifies what constitutes a valid contract.  If a contract is executed according to that specification, then it is a lawful contract.  An unlawful contract fails on one or more counts in the specification.  It isn't illegal, however.  Just not enforceable.

A: In United States criminal law there is no difference between "illegal" and "unlawful."  Mostly this is because of something called "substantive due process," a right which is guaranteed under the 14th Amendment and which (in part) demands that laws must not be so vague as to leave someone unsure of whether his actions are criminal.  In particular, any law must enumerate which acts it is making illegal.  So says the United States Supreme Court in Connally v General Construction Co. 269US385 (1926).
Since the rule on the sign prohibiting the feeding of park wildlife seems clear, perhaps the issue is whether violating the rule is tantamount to violating the law.  And so it is.  Step right up to 16 USC §3 - Rules and regulations of national parks, reservations, and monuments:

The Secretary of the Interior shall make and publish such rules and
  regulations as he may deem necessary or proper for the use and
  management of the parks, monuments, and reservations under the
  jurisdiction of the National Park Service, and any violation of any of
  the rules and regulations authorized by this section and sections 1,
  2, and 4 of this title shall be punished by a fine of not more than
  $500 or imprisonment for not exceeding six months, or both,....

The principle here has a Latin description nulla poena sine lege, meaning "no punishment without the law," and is usually interpreted to mean that laws must be "praevia, scripta, certa, stricta", i.e., enacted previous to the offense, written down, certain in description, and strictly interpreted.  A brief time spent in the google leads me to believe this is the way modern law works in Europe (including Great Britain), but I'm out of my depth on that subject.


text:
Q: Determining if a user should be able to see another user's profile property in code I'm trying to create a Web Part that will conditionally display its contents if the current user has permission to see a specific user profile property.  Here's what I've got so far.  It seems that I can use the ProfileSubtypeProperty privacy settings, but I'm not sure what to do.  I'd like to hide the content when either 1) the user cannot override the privacy settings and the default privacy setting doesn't allow the current user to view the profile property or 2) the user can override the privacy settings and has done so so that the current user can't see the profile property.
The first part, I think I can figure out using UserOverridePrivacy and DefaultPrivacy.  The second part is what I need help with.  How can I check to see what whether or not the property should be visible?
This stems from an earlier question I'd asked.
Control code:
[ParseChildren(true)]
[PersistChildren(false)]
[ToolboxItemAttribute(false)]
public class UppvWebPart : WebPart
{
    public class UppvWebPartTemplate : WebControl, INamingContainer
    {
        protected override void Render(HtmlTextWriter writer)
        {
            this.RenderContents(writer);
        }
    }

    protected override void CreateChildControls()
    {
        String accountName = HttpContext.Current.Request["accountname"];
        if (UvvpWebTemplate != null && PropertyName != null && accountName != null)
        {
            SPWeb thisWeb = SPContext.Current.Web;
            SPServiceContext context = SPServiceContext.GetContext(thisWeb.Site);
            UserProfileConfigManager upcm = new UserProfileConfigManager(context);
            ProfilePropertyManager ppm = upcm.ProfilePropertyManager;
            UserProfileManager upm = new UserProfileManager(context);

            if (upm.UserExists(accountName))
            {
                UserProfile userProfile = upm.GetUserProfile(accountName);

            ProfileSubtypeProperty psp = userProfile.Properties.GetPropertyByName(PropertyName);
            if( /* what to do with psp? */)
            {
                ProfileValueCollectionBase pv = userProfile.GetProfileValueCollection(PropertyName);

                if (pv != null)
                {
                    foreach (String v in pv)
                    {
                        HttpContext.Current.Response.Output.WriteLine("
{0}
", v);
                    }

                    Control container = new Control();
                    this.Controls.Add(container);
                    UvvpWebTemplate.InstantiateIn(container);
                }
            }
            }
        }
    }

    public virtual String PropertyName
    {
        set;
        get;
    }

    [Browsable(false)]
    [DefaultValue(null)]
    [PersistenceMode(PersistenceMode.InnerProperty)]
    [TemplateContainer(typeof(UppvWebPartTemplate))]
    public virtual ITemplate UvvpWebTemplate
    {
        set;
        get;
    }
}
And here is the usage:

<UppvWebPart:UppvWebPart PropertyName="Hobbies" runat="server" Description="My WebPart" Title="UppvWebPart" __MarkupType="vsattributemarkup" __WebPartId="{339ea49b-f2b0-4bd6-a029-73ead84e4915}" WebPart="true" __designer:IsClosed="false" id="UppvWebPart1">
    <UvvpWebTemplate>
Show the property!
</UvvpWebTemplate>
</UppvWebPart:UppvWebPart>

A: from what I can see, the DefaultPrivacy property is the only thing you should need to check.  Provided this is at the right level to display then you don't need to do any alternative checks if the UserOverridePrivacy is set.  If I'm completely honest, I haven't tried this, but looking through the object model the DefaultPrivacy property appears to be the only property to hold any privacy settings for the user profile property.  I'd be interested to know whether you've managed to sort this out...


text:
Q: $(u_1,\ldots,u_k,v_1,\ldots,v_l)$ is linearly ind. iff $\operatorname{span}(u_1,\ldots,u_k) \cap (\operatorname{span}(v_1,\ldots,v_l) = \{0\} $
Assume that $(u_1,\ldots,u_k)$ and $(v_1,\ldots,v_l)$ are linearly independent. Prove that $(u_1,\ldots,u_k,v_1,\ldots,v_l)$ is linearly independent if and only if $\operatorname{span}(u_1,\ldots,u_k) \cap \operatorname{span}(v_1,\ldots,v_l) = \{0\}.$

I've had trouble making any progress beyond rattling off that $\alpha_1u_1+\cdots+\alpha_k u_k + \beta_1 v_1 + \cdots + \beta_l v_l = 0$ implies that the $\alpha_i,\beta_j$ are all $0.$ Not asking for a detailed answer, I would just like a hint. Thank you

A: $\alpha_1u_1+\cdots+\alpha_k u_k =- \beta_1 v_1 - \cdots - \beta_l v_l$ right hand is $\in {span}(u_1,\ldots,u_k)$ and left hand $\in {span}(v_1,\ldots,v_l)$ thus
$\operatorname{span}(u_1,\ldots,u_k) \cap (\operatorname{span}(v_1,\ldots,v_l) = \{0\} $ so $\alpha_1u_1+\cdots+\alpha_k u_k =0$ and $- \beta_1 v_1 - \cdots - \beta_l v_l=0$ use  linearly independent you will get result.


text:
Q: How do I set the output port on my audio card? My audio card has two ports; for clarity I'll call them the 'speaker' and 'headphone' port. In Windows, the audio control sees two separate ports, and I can switch back and forth between speaker and headphone at will.
In Linux, the audio will always come out the speaker port by default, and automatically switch to the headphone port if I plug headphones in.
How do I control this behaviour? I've tried using pacmd's "sink-set-port", and the "list-sinks" output suggests that the 'active port' has changed, but nothing actually happens.
Data from list-sinks:
properties:
    alsa.resolution_bits = "16"
    device.api = "alsa"
    device.class = "sound"
    alsa.class = "generic"
    alsa.subclass = "generic-mix"
    alsa.name = "ALC889 Analog"
    alsa.id = "ALC889 Analog"
    alsa.subdevice = "0"
    alsa.subdevice_name = "subdevice #0"
    alsa.device = "0"
    alsa.card = "0"
    alsa.card_name = "HDA Intel PCH"
    alsa.long_card_name = "HDA Intel PCH at 0xfbff8000 irq 60"
    alsa.driver_name = "snd_hda_intel"
    device.bus_path = "pci-0000:00:1b.0"
    sysfs.path = "/devices/pci0000:00/0000:00:1b.0/sound/card0"
    device.bus = "pci"
    device.vendor.id = "8086"
    device.vendor.name = "Intel Corporation"
    device.product.id = "1c20"
    device.product.name = "6 Series/C200 Series Chipset Family High Definition Audio Controller"
    device.form_factor = "internal"
    device.string = "front:0"
    device.buffering.buffer_size = "65536"
    device.buffering.fragment_size = "32768"
    device.access_mode = "mmap+timer"
    device.profile.name = "analog-stereo"
    device.profile.description = "Analog Stereo"
    device.description = "Built-in Audio Analog Stereo"
    alsa.mixer_name = "Realtek ALC889"
    alsa.components = "HDA:10ec0889,1458a022,00100004"
    module-udev-detect.discovered = "1"
    device.icon_name = "audio-card-pci"
ports:
    analog-output: Analog Output (priority 9900, latency offset 0 usec, available: unknown)
        properties:

    analog-output-headphones: Headphones (priority 9000, latency offset 0 usec, available: yes)
        properties:
            device.icon_name = "audio-headphones"
active port: <analog-output>

A: Turns out ALSA will automatically mute my main speakers when something plugs in the headphone jack. I can disable that by disabling auto-mute mode in alsamixer. I can then control the levels of the headphone port and speaker port independently.


text:
Q: Drupal, modify an enity I have this entity:
    $schema['apiuser'] = array(
        'description' => 'The base table for api_user.',
        'fields' => array(
            'apiuser_id' => array(
                'description' => 'The primary identifier for an artwork.',
                'type' => 'serial',
                'unsigned' => TRUE,
                'not null' => TRUE,
            ),
            'public_key' => array(
                'type' => 'int',
                'not null' => TRUE,
                'default' => 0,
                'description' => "Foreign key: {file_managed}.fid of user's picture.",
            )
        ),
        'unique keys' => array(
            'id' => array('apiuser_id')
        ),
        'primary key' => array('apiuser_id'),
        );

Later I have added a new field:
,
            $schema['apiuser'] = array(
    'description' => 'The base table for api_user.',
    'fields' => array(
        'apiuser_id' => array(
            'description' => 'The primary identifier for an artwork.',
            'type' => 'serial',
            'unsigned' => TRUE,
            'not null' => TRUE,
        ),
        'public_key' => array(
            'type' => 'int',
            'not null' => TRUE,
            'default' => 0,
            'description' => "Foreign key: {file_managed}.fid of user's picture.",
        ),
        'user_id' => array(
            'description' => 'The primary identifier for an artwork.',
            'type' => 'int',
            'not null' => TRUE,
        )

    ),
    'unique keys' => array(
        'id' => array('apiuser_id')
    ),
    'primary key' => array('apiuser_id'),
    );

Drupal doesn't change the respective table into mysql so I modified it manually. But now when I try to save the entity that new field is not filled. I have installed devel module and used 'drush cc all' to clear the cache, deactivated and activated the modeule but still doesn't work

A: This is what the update script is for. You'll want to write an update_N function, in which you can use the schema object to add your column:
function your_module_update_7001($sandbox) {
  // do some checking (i.e. if already exists, etc)
  // get $schema from wherever you defined it for hook_schema...
  $spec = $schema['fields']['user_id'];
  Database::getConnection()->schema()->addField('apiuser', 'user_id', $spec);
}

Then run http://yoursite.com/update.php and drupal will modify your table accordingly.


text:
Q: Simple rewrite with subfolder I want to point:
www.reneebuller.com/paintings/busy-pair-humming-bird-painting.html to
www.reneebuller.com/painting-details.cfm?ID=136&Type=Bird
Is this the correct rewrite?  I'm not sure how to account for the /paintings/ folder.
RewriteRule ^paintings/busy-pair-humming-bird-painting.html painting-details.cfm?ID=136&Type=Bird [NC, R=301, L]

A: The above rewrite is correct.  It just takes time for the server to process the .htaccess file.


text:
Q: Rows number check in PHP I am trying to check if there were any records (more than 0) in my database table:
        $ifExists = DB::select('SELECT COUNT(*) FROM `characters` WHERE userid = ?', array(Auth::id()));

Now I am checking if there are more than 0:
   if($ifExists > 0){
                return Redirect('/board');
            }
            else{
                return view('intro');
            }

It always takes me to the /board. But there are many rows in this database table.
The echo $ifExists; shows me [{"COUNT(*)":0}]
How do I check this number?

A: Try it this way:
$ifExists = DB::table('characters')->where('userid', Auth::id())->count();

If you do it like in your question, you will receive an array of objects.
If you only want to check for existens of entries and do not need the count, you can just use the exists() function whitch will return you a boolean:
$ifExists = DB::table('characters')->where('userid', Auth::id())->exists();

if($ifExists){
    return Redirect('/board');
}else{
    return view('intro');
}

A: Been a while since I've done PHP, but from the looks of it you get a result object from the database. That object is 1 object.
I think that's why it's always redirecting to /board.
Not sure how to do this in PHP, but you want to get the value of "COUNT(*)" from the object for your if statement. Hope that helps :)


text:
Q: Android recyclerview items not displayed I have a little problem with my RecyclerView object.
Inside my main activity I have a list which I want to display specific objects.
First I create a proper adapter to the list and then I attach it to the RecyclerView, as it should.
My problem is for some reason, the list shows nothing. The type of RecyclerView I'm using is a custom list which extends from RecyclerView class and is intended for displaying an ImageView whenever the list is empty. In this case, when the adapter is attached to the list, no empty image is displayed, nor are the list's items
Here is the code for the main activity:
package com.silverfix.dgdeditor;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.design.internal.NavigationMenuView;
import android.support.design.widget.NavigationView;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.silverfix.dgdeditor.adapters.DocumentsAdapter;
import com.silverfix.dgdeditor.utils.DocumentPack;
import com.silverfix.dgdeditor.utils.files.json.JsonPackReader;
import com.silverfix.dgdeditor.utils.views.AnimationUtils;
import com.silverfix.dgdeditor.utils.views.DividerItemDecoration;
import com.silverfix.dgdeditor.utils.views.EmptyViewRecyclerView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.recyclerview.animators.ScaleInAnimator;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

    private JsonPackReader jsonReader;

    private EmptyViewRecyclerView documentsRv;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    private Toolbar toolbar;

    private DocumentsAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(R.string.app_name);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.app_name) {

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }
        };

        drawerLayout.addDrawerListener(actionBarDrawerToggle);

        // Setting the actionbarToggle to drawer layout
        actionBarDrawerToggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.nav_item_divider, getTheme());

        for(int i = 1; i < navigationView.getChildCount(); i++) {
            NavigationMenuView itemView = (NavigationMenuView) navigationView.getChildAt(i);
            itemView.addItemDecoration(new DividerItemDecoration(drawable));
        }

        ImageView emptyView = (ImageView) findViewById(R.id.empty_view);
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                launchCreateActivity();
            }
        });
        AnimationUtils.fadeView(emptyView);

        documentsRv = (EmptyViewRecyclerView) findViewById(R.id.documents_rv);

        // Setting linear layout manager for the list
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        documentsRv.setLayoutManager(linearLayoutManager);
        documentsRv.setEmptyView(emptyView);
        documentsRv.setItemAnimator(new ScaleInAnimator());

        documentsRv.getItemAnimator().setAddDuration(Constants.Extras.ITEM_ANIMATION_DURATION);
        documentsRv.getItemAnimator().setRemoveDuration(Constants.Extras.ITEM_ANIMATION_DURATION);
        documentsRv.getItemAnimator().setMoveDuration(Constants.Extras.ITEM_ANIMATION_DURATION);
        documentsRv.getItemAnimator().setChangeDuration(Constants.Extras.ITEM_ANIMATION_DURATION);

        jsonReader = new JsonPackReader(this);

        List<DocumentPack> packsList = new ArrayList<>();

        try {
            packsList = jsonReader.fetchPacksFromJsonFile();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Error: data not synchronized", Toast.LENGTH_SHORT).show();
        } finally {
            adapter = new DocumentsAdapter(packsList);

            adapter.setMenuInflater(getMenuInflater());
        }

        documentsRv.setAdapter(adapter);
    }

    private void launchCreateActivity() {
        Intent intent = new Intent(MainActivity.this, NewDocActivity.class);
        startActivity(intent);
    }
    @Override
    protected void onResume() {
        super.onResume();

        System.out.println("Paused");
        if(toolbar != null)
            setSupportActionBar(toolbar);
    }

    @Override
    protected void onPause() {
        super.onPause();
        System.out.println("Paused");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_action_bar, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.action_create) {
            launchCreateActivity();
        } else if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        return false;
    }
}

Here is the code for the DocumentsAdapter class:
package com.silverfix.dgdeditor.adapters;

import android.support.v7.widget.RecyclerView;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.silverfix.dgdeditor.R;
import com.silverfix.dgdeditor.utils.DocumentPack;

import java.util.List;

/**
 * Created by David on 08/03/2017.
 */

public class DocumentsAdapter extends ContextAdapter{

    private List<DocumentPack> dataSet;

    public DocumentsAdapter(List<DocumentPack> dataSet) {
        super();
        this.dataSet = dataSet;
    }

    @Override
    public DocumentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.document_list_item, parent, false);

        return new DocumentViewHolder(view, menuInflater);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        DocumentPack pack = dataSet.get(position);

        DocumentViewHolder documentViewHolder = (DocumentViewHolder) holder;

        documentViewHolder.bindData(pack);

        documentViewHolder.bindClick(onClickListener);
        documentViewHolder.bindLongClick(onLongClickListener);
    }

    @Override
    public int getItemCount() {
        return dataSet.size();
    }

    public static class DocumentViewHolder extends AbstractViewHolder implements View.OnCreateContextMenuListener {

        private TextView documentName, documentDate;

        public DocumentViewHolder(View rootView, MenuInflater inflater) {
            super(rootView);

            rootView.setOnCreateContextMenuListener(this);
            this.inflater = inflater;

            documentName = (TextView) rootView.findViewById(R.id.document_card_name_tv);
            documentDate = (TextView) rootView.findViewById(R.id.document_card_date_tv);

        }

        @Override
        public void bindData(Object object) {
            DocumentPack pack = (DocumentPack) object;

            documentName.setText(pack.getFileName());
            documentDate.setText(pack.getDate());
        }

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

        }
    }
}

Code for the ContextAdapter:
package com.silverfix.dgdeditor.adapters;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.MenuInflater;
import android.view.ViewGroup;

import com.silverfix.dgdeditor.utils.views.RecyclerViewClickListener;
import com.silverfix.dgdeditor.utils.views.RecyclerViewLongClickListener;
import com.silverfix.javadgd.components.GoodObject;

import java.util.List;

/**
 * Created by David on 09/03/2017.
 */

public abstract class ContextAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    protected int clickedItemPos;

    protected RecyclerViewClickListener onClickListener;
    protected RecyclerViewLongClickListener onLongClickListener;

    protected MenuInflater menuInflater;

    public ContextAdapter() {
        clickedItemPos = -1;
    }
    public void setClickedItemPosition(int clickedItemPos) {
        this.clickedItemPos = clickedItemPos;
    }

    public int getClickedItemPosition() {
        return clickedItemPos;
    }

    public void setMenuInflater(MenuInflater menuInflater) {
        this.menuInflater = menuInflater;
    }

    public void setClickListener(RecyclerViewClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    public void setOnLongClickListener(RecyclerViewLongClickListener onLongClickListener) {
        this.onLongClickListener = onLongClickListener;
    }
}


text:
Q: fadeIn DIV affecting other div values I'm new to jquery and javascript in general so I'm having some trouble figuring things out. Right now, I want an image to animate downward (iphone) while an image fades in (shadow) while another image animates upwards (reflection) while fading in. The code I have now just fades everything in at the same speed (doesn't matter if each div has different time values). Also, if I try to animate the reflection, it just pulls all the elements down (if I edit the start value of the div). This is probably because the reflection is the first element in the "wrap" div. I can't really change this because I want the iphone overlapping the shadow which overlaps the reflection. So, I need to initiate the reflection div first (I tried using z values which didn't work). Any tips? Here is the code:
<!DOCTYPE html>

  <link rel=StyleSheet href="external_style_sheet.css" type="text/css">

And the CSS
    `p {font-family: georgia, serif; font-size: x-small;}
hr {color: #000000; height: 1px }
a:hover {color: #ff0000; text-decoration: none}

body {
  background-color:#1b1a1f;

}

#reflection {
  margin-top:0px;
  margin-left: 400px;
  position:relative;
  width: 414px;
  height: 993px;
  background-image: url("images/reflection2.png");
  display: none;
  z-index: -1;

}

#shadow {
  margin-top:0px;
  margin-left: 0px;
  position:absolute;
  width: 414px;
  height: 818px;
  background-image: url("images/shadow3.png");
  display: none;
  z-index: 1;
}

#iphone {
  margin-top:-1000px;
  margin-left: 0px;
  position:relative;
  width: 414px;
  height: 818px;
  background-image: url("images/iphone_2.png");
  z-index: 0;
}

#wrap {
  width:800px;
  margin:0 auto;
  background-image: url("images/logo.png");
}

#left {
  float:left;
  width:500px;
}

#right {
  float:right;
  width:500px;

}

HTML

Content

A: There are few issues here, though I think you're close...

*

*make sure your HTML is well-formed and that div elements open and close

*don't use a z-index of -1, use only positive values for each element (I usually space them out by 5 or so levels)

*apply "position: relative;" to #right, manually set the height and width, and then make #reflection, #shadow, and #iphone all "position: absolute;" so everything doesn't shift around while animating (just make sure this works with your page layout)


text:
Q: How to get impersonated UserGuid Id in docusign I am trying to get the impersonated userguid from the docusign api. Per the documentation I need to call /restapi/v2/accounts/account_id/users?email=email, which is not working for me. I assume the full url would be https://admin.docusign.com/restapi/v2/accounts/account_id/users?email="sampleemail@gmail.com" .
I am getting a 404 when entering my email in the above format.

A: Looks like you have the incorrect domain. API Calls generally don't get made against admin.docusign.com. You'll want to make that call against the Application Server your account is on.
In the Sandbox environment that will be demo.docusign.net. In prod you'd need to make a UserInfo call to determine which server your account is on. It could be something like www.docusign.net or na2.docusign.net, but there are several possible domains.

A: In order to get Impersonate GUID ,

*

*Login to admin account

*Under setting options Click API and keys

*Value under the user id text  box is Impersonate GUID

A: During configuration & setup:
 1. You have an account admin enter information such as account, their userId ("API User Name" in web app). Save both items.
 2. You follow the "consent flow", get their consent, generate a JWT and
    exchange for a token.
 3. Use the /user_info call against the account
    server to get the list of their accounts.  If more than one account
    in the array, find the one that matches what they entered in the
    configuration.  Get and save the associated "base_uri".  You will
    use that for all subsequent API calls.
Your application now has stored the account ID, the admin's "userId", and the base URI to built API URLs.
During business application operations:
Admin is "Bob".  Sender is "Jill"
You need to get an access token for Jill.
 1.  Create JWT for Bob, exchange for access token, make GET /users?email={Jill's email).  This gives you Jill's "userId".
 2. Create JWT for Jill, exchange for access token.
 3. Make API call as Jill, using her access token.


text:
Q: How can I use a compressed connection between Django and MySQL? I have compression on my MySQL server, and I'd like to ensure Django is making compressed connections. How can I do this?

A: Trial, error and inference suggest the solution is to use a compress field set to True in the OPTIONS dict:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        ...
        'OPTIONS': {
            'compress': True
        }
    }
}

I can't confirm the connection is actually compressed though.

A: A cursory (no pun intended) examinations of /django/db/backends/mysql/base.py of Django 1.3:
298     def _cursor(self):
299         if not self._valid_connection():
300             kwargs = {
301                 'conv': django_conversions,
302                 'charset': 'utf8',
303                 'use_unicode': True,
304             }
305             settings_dict = self.settings_dict
306             if settings_dict['USER']:
307                 kwargs['user'] = settings_dict['USER']
308             if settings_dict['NAME']:
309                 kwargs['db'] = settings_dict['NAME']
310             if settings_dict['PASSWORD']:
311                 kwargs['passwd'] = settings_dict['PASSWORD']
312             if settings_dict['HOST'].startswith('/'):
313                 kwargs['unix_socket'] = settings_dict['HOST']
314             elif settings_dict['HOST']:
315                 kwargs['host'] = settings_dict['HOST']
316             if settings_dict['PORT']:
317                 kwargs['port'] = int(settings_dict['PORT'])
318             # We need the number of potentially affected rows after an
319             # "UPDATE", not the number of changed rows.
320             kwargs['client_flag'] = CLIENT.FOUND_ROWS
321             kwargs.update(settings_dict['OPTIONS'])
322             self.connection = Database.connect(**kwargs)
323             self.connection.encoders[SafeUnicode] = self.connection.encoders[unicode]
324             self.connection.encoders[SafeString] = self.connection.encoders[str]
325             connection_created.send(sender=self.__class__, connection=self)
326         cursor = CursorWrapper(self.connection.cursor())
327         return cursor

When creating a connection on line 322, the code does not seem to pass the compress argument in kwargs, not by default anyway.
Passing 'compress': True through OPTIONS should let you create a compressed connection when it's available, this dictionary is merged to kwargs on line 321.
There does not seem to be any other calls to the MySQLdb.connect() method in the rest of the backend. Note that MySQLdb is imported as: import MySQLdb as Database in that file.


text:
Q: Merging lists/tuples stored inside a list in python I have a list of lists each containing tuples with some co-ordinates which sort of look like this:
[[(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)], [(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)], [(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)]]
Considering orders, lets call the outer list - L0, and the inner list - L1
The number of tuples inside of L1 may vary with incoming data but will be constant for all elements of L0. For example, if there are 3 tuples in L1, there will be 3 tuples in all the rest of the lists.
My goal is to get minimum values of all xn co-ordinates and the maximum values of all yn co-ordinates across all L1 elements and return a list which looks something like this:
[(x1min, y1max), (x2min, y2max), (x3min, y3max) ... (xnmin, ynmax)]
I tried approaching this by looping through L0 and then again looping through L1 only to get individual elements and then trying to construct a new list of the expected output but it is very long and I think would be inefficient.
I am not at all able to figure out how to approach this problem and I am pretty sure there is a very clever and efficient way of solving this. I would be really grateful for any help I can get on this.
Note: I am a newbie learning python so please forgive me if I am accidently using any wrong terms and stuff. Also, this problem might probably be a very easy one but I cannot develop a method to approach this yet. I also tried searching for it everywhere but couldn't find a solution that fits my problem.

A: A short and relatively fast way to do this would be to use list comprehensions:
xmin = min([x for L1 in L0 for x, y in L1])
ymax = max([y for L1 in L0 for x, y in L1])

Basically, you loop through the lists L1 in the list L2 and make a new list containing all the first (for x) or last (for y) elements of the tuples. Then you call min or max on these new lists which gives you the maximum or minimum argument.
Just for understanding purposes: This list comprehension [x for L1 in L0 for x, y in L1] is equivalent to constructing a new list of all x values with an explicit for-loop like this:
xelements = []
for L1 in L0:
    for coordinates in L1:
        xelements.append(coordinates[0])

A: You have a list comprised of other lists. Let's call them sub-lists. Each sub-list contains a number of 2-tuples. The challenge appears to be to find the minimum value of all 0th elements of the tuples within a sub-list and the maximum value of the 1th element.
If that's the case then (with some invented numbers), you could do this:
L = [[(-1, 2), (0, 4)], [(1, 6), (2, 9)]]
M = []

for e in L:
    _min = min(t[0] for t in e)
    _max = max(t[1] for t in e)
    M.append((_min, _max))

print(M)

Output:
[(-1, 4), (1, 9)]


text:
Q: Gradle DSL method not found:'buildConfigFields' Like the title,my gradle version is 2.10, like this:
...
distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

my gradle plugin version is 2.1.2, like this:
classpath 'com.android.tools.build:gradle:2.1.2'

in my app module , my code like this:
...

android {
compileSdkVersion 23
buildToolsVersion "23.0.3"

defaultConfig {
    applicationId "com.dazd.supplyinout"
    minSdkVersion 14
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    debug {
        buildConfigFields("BASE_URL": ['String', debugUrl])
    }
    release {
        buildConfigFields('BASE_URL': ['BASE_URL', releaseUrl])
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

when i sync the project, i get the build error like the title , like this:
Error:(30, 0) Gradle DSL method not found: 'buildConfigFields()'
Possible causes:
The project 'SupplyInOut' may be using a version of Gradle that does not contain the method.
The build file may be missing a Gradle plugin.

could anybody help me?

A: the method is buildConfigField, singular not plural and its syntax is
buildConfigField(type, name, value)

in your case
buildConfigField ("String", "BASE_URL", debugUrl)

should do it. It will create an entry in BuildConfig.java, called BASE_URL and of type String.
you can find the documentation here


text:
Q: Excel VBA Forms Error Message loop i currently have a problem with a simple login form in excel (VBA), when having an error, continuing and having another error it still gives me two more MsgBoxes with errors but with the "Unload Me" and "Goto Ende" it should close itself completely.
Any guesses why this isn't working? I know this is very basic and probably very redundant, but it should still work.
Public Name As Variant
Public Password As Variant

Private Sub Btn_Register_Cancel_Click()
    Unload Me
End Sub

Private Sub Btn_Register_Register_Click()

Start:

Dim Error As Integer

Error = 0

Name = Tbx_Register_Name.Value
Password = Tbx_Register_Password.Value

'Check for Name, Password, Password2 if empty
If Tbx_Register_Name.Value = "" Then
    Error = MsgBox("Please enter a username.", _
            vbRetryCancel, "Error")

        If Error = 2 Then
            Unload Me
            GoTo Ende

        Else
            Application.ScreenUpdating = False
            Register.Hide
            Register.Show
            Application.ScreenUpdating = True
            GoTo Start

        End If

ElseIf Tbx_Register_Password.Value = "" Then
    Error = MsgBox("Please enter a password.", _
            vbRetryCancel, "Error")

        If Error = 2 Then
            Unload Me
            GoTo Ende

        Else
            Application.ScreenUpdating = False
            Register.Hide
            Register.Show
            Application.ScreenUpdating = True
            GoTo Start

        End If

ElseIf Tbx_Register_Password2.Value = "" Then
    Error = MsgBox("This field cannot be empty.", _
            vbRetryCancel, "Error")

        If Error = 2 Then
            Unload Me
            GoTo Ende

        Else
            Application.ScreenUpdating = False
            Register.Hide
            Register.Show
            Application.ScreenUpdating = True
            GoTo Start

        End If

End If

With Workbooks("General Makro.xlsx").Worksheets("User")
'Check for Username match in registration list
For i = 1 To 100

    If .Cells(i, 1).Value = Name Then

        Error = MsgBox("This username is already taken.", _
            vbRetryCancel, "Error")

        If Error = 2 Then
            Unload Me
            i = 100
            GoTo Ende

        Else
            Application.ScreenUpdating = False
            Register.Hide
            Register.Show
            Application.ScreenUpdating = True
            GoTo Start

        End If

    End If

Next i

End With

'Check for the passwords to match
If Tbx_Register_Password.Value = Tbx_Register_Password2.Value Then

    With Workbooks("General Makro.xlsx").Worksheets("User")

        For i = 1 To 100

            If .Cells(i, 1) = "" Then

                .Cells(i, 1).Value = Name
                .Cells(i, 2).Value = Password

                Tbx_Register_Password.Value = ""
                Tbx_Register_Password2.Value = ""

                Application.ScreenUpdating = False
                Register.Hide
                Login.Show
                Tbx_Login_Name.Value = .Cells(i, 1).Value
                Tbx_Login_Password.Value = .Cells(i, 2).Value
                Application.ScreenUpdating = True

                i = 100
                GoTo Ende

            End If

        Next i

    End With

Else
    Error = MsgBox("The passwords have to match!", vbRetryCancel, "Error")

    If Error = 2 Then
        Unload Me
        GoTo Ende

    Else
        Application.ScreenUpdating = False
        Register.Hide
        Register.Show
        Application.ScreenUpdating = True
        GoTo Start

    End If

End If

Ende:

End Sub

Edit: I Actually Tried to do the 2nd UserForm for the login, and i happen to get the same problem there. Everything works just fine, until i close the whole program, then the error-message appears again. Am i unloading the userform incorrect? Maby the login userform says open and continues when everything is getting closed.
Edit 2: I could just turn off alerts but that would be an ugly solution and definitely nothing i want to implement on every close button in the program.

A: You can verify blank values in textboxes with this:
If TextBox.Text = "" Then
    MsgBox "Is blank!"
    Unload Me
    GoTo Ende
End If

'Your code

Ende:    Exit Sub

To verify the username and password in a database, you can do this:
Dim sh As Worksheet
Dim LastRow As Long
Dim UserRange As Range
Dim UserMatch As Range

Set sh = ThisWorkbook.Sheets("database")
LastRow = sh.Range("A" & Rows.Count).End(xlUp).Row

Set UserRange = sh.Range("A1:A" & LastRow)

Set UserMatch = UserRange.Find(What:=UserTextBox.Text, LookIn:=xlValues)
If Not UserMatch Is Nothing Then
    MsgBox "User exists!"

    If PwdTextBox.Text = UserMatch.Offset(0, 1) Then
        MsgBox "Pwd matched!"
        'do something
    Else
        MsgBox "Wrong password!"
        'do something
    End If

Else
    MsgBox "User dont exists!"
   'do something
End If

This will work if in the database the usernames are in column A and the passwords in column B.


text:
Q: Android app having a marketplace within the app I've been going through a design for an app I wish to be making soon. My app will rely on user generated content. Is it possible to have users add an item to this in-app marketplace and recieve payments when other users buy from them directly using Google Wallet or PayPal? Is there a recommended way of implementing this type of feature?
Thanks in advance!

A: I am not aware of any recommended way to do this, however, doing this your app will likely not be allowed to be uploaded to the Google Play Store.
This would be against Google's Terms of Service as a developers apps is not allowed to make money through other means and other purchases that are made within the app have to go via the Google Play.


text:
Q: Navbar button not appearing bootstrap 4 The navbar button is just not appearing i don't know whats wrong.
I am sure that the code is correct i even have jquery file.
This is the code:
<!doctype html>

      <title>Bootstrap Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
      <link rel="stylesheet" href="style.css">

              <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive">

              </button>

A: Your code doesn't make any sense. Can you adjust this for yourself and try it ? The navbar toggler also needs to have a specific width value to appear.

      ***Your İmg Here***
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            Home (current)

            Features

            Pricing

A: You have used navbar-expand-md class in your nav element because of that your toggle is only visible in resolution smaller than 768px and for higher resolution you can use navbar-expand-lg or navbar-expand-xl classes. If you want to keep it visible in all screen just remove the class navbar-expand

          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive">

          </button>


text:
Q: Segfault in libc upon running statically linked application I am trying to run a statically linked hello world program on an ubuntu tegra (ARM) board, but a function within libc seems to be giving a segmentation fault.
Program received signal SIGSEGV, Segmentation fault.
0x00039a1a in _dl_get_origin ()
(gdb) bt
#0  0x00039a1a in _dl_get_origin ()
#1  0x0001abaa in _dl_non_dynamic_init ()
#2  0x0001b5d8 in __libc_init_first ()
#3  0x00008ae2 in __libc_start_main ()
#4  0x000088d4 in _start ()

When dynamically linked, there are no problems whatsoever.
Some more details:
a.out: ELF 32-bit LSB  executable, ARM, EABI5 version 1 (SYSV), statically linked, for GNU/Linux 2.6.32, BuildID[sha1]=f56e8ee17aa966e641c8b4e1ba3105abc077a143, not stripped

gcc (Ubuntu/Linaro 4.8.2-19ubuntu1) 4.8.2

Linux tegra-ubuntu 3.10.24-g6a2d13a #1 SMP PREEMPT Fri Apr 18 15:56:45 PDT 2014 armv7l armv7l armv7l GNU/Linux

Any pointers on how to fix this? Thanks!


text:
Q: UITableViewCell won't become first responder (Showing UIMenuController on cell gesture) I have an application with a UITabBar. Every tab is a UINavigationController with several UIViewControllers inside. One of those View Controllers contains a UITableView, and I want to display a floating menu for deleting the long pressed UITableViewCell.
I am using UIMenuController but it's not displayed because the cell refuses to become first responder.
Here's my code:
    - (void)viewDidLoad
    {
        [super viewDidLoad];

        UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
        lpgr.minimumPressDuration = 1.0; //second
        [table addGestureRecognizer:lpgr];

        [lpgr release];
    }

-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint p = [gestureRecognizer locationInView: table];

        NSIndexPath *indexPath = [table indexPathForRowAtPoint:p];
        if (indexPath != nil) {
            UITableViewCell* cell = [self tableView:table cellForRowAtIndexPath: indexPath];

            [cell becomeFirstResponder];
            UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:@"Delete" action:@selector(delete:)];

            UIMenuController *menu = [UIMenuController sharedMenuController];
            [menu setMenuItems:[NSArray arrayWithObjects:delete, nil]];
            [menu setTargetRect:cell.frame inView:cell.superview];
            [menu setMenuVisible:YES animated:YES];
        }
    }
}

On the UITableViewCell I have overriden the method:
-(BOOL) canBecomeFirstResponder {
    return YES;
}

Any ideas on why the cell is not becoming the first responder?
Thanks!

A: I think I fixed your code :-)
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint p = [gestureRecognizer locationInView: self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
        if (indexPath != nil) {

            [self becomeFirstResponder];
            UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:@"Delete" action:@selector(customDelete:)];

            UIMenuController *menu = [UIMenuController sharedMenuController];
            [menu setMenuItems:[NSArray arrayWithObjects:delete, nil]];
            [menu setTargetRect:[self.tableView rectForRowAtIndexPath:indexPath] inView:self.tableView];
            [menu setMenuVisible:YES animated:YES];
        }
    }
}

- (void)customDelete:(id)sender {
//
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(customDelete:) ){
        return YES;
    }
    return NO;
}

I did the following..

*

*[self becomeFirstResponder];

*[menu setTargetRect:[self.tableView rectForRowAtIndexPath:indexPath] inView:self.tableView];

*Added true for canPerformAction Not mostly needed if you have implemented the function

Please change the tableview and other things to your local reference variables :-)
Good read - http://www.intridea.com/blog/2010/12/22/developers-notes-for-uimenucontroller


text:
Q: How to create a NOT NULL self-referencing foreign key in sqlalchemy I'm trying to make a not-null self-referencing foreign key in sqlalchemy, something like this:
class MyModel(Base):
    __tablename__ = "mytable"

    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey("mytable.id"), nullable=False)

    def __init__(self, parent_id):
        self.parent_id = parent_id

There will need to be root records that are their own parent, to seed chains of relationships. The trick that I can't figure out, is how to create one of these root records, since at the moment I create a MyModel instance, I don't know yet what the DB will assign for an id.
One option would be to make the parent_id nullable, so the root records would be NULL instead of pointing to themself, but it would be preferable for this field to be NOT NULL. Is this pattern generally possible, to have a NOT NULL self-referencing foreign key in sqlalchemy?


text:
Q: How to know the network bandwidth used at a given time? I'm trying to build a load balancer for a program that is running in 2 different servers.
So far my load balancer, only checks the CPU usage of each server using an instance of PerformanceCounter in each server program.
I would also like to check the bandwidth usage of each server, how can I check that?
(it is probably done also using the PerformanceCounter but I'm unfamiliar with its usage)

A: Thanks to moonlight I've found this http://www.keyvan.ms/how-to-calculate-network-utilization-in-net
public double getNetworkUtilization(string networkCard){

            const int numberOfIterations = 10;

            PerformanceCounter bandwidthCounter = new PerformanceCounter("Network Interface", "Current Bandwidth", networkCard);
            float bandwidth = bandwidthCounter.NextValue();//valor fixo 10Mb/100Mn/

            PerformanceCounter dataSentCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", networkCard);

            PerformanceCounter dataReceivedCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", networkCard);

            float sendSum = 0;
            float receiveSum = 0;

            for (int index = 0; index < numberOfIterations; index++)
            {
                sendSum += dataSentCounter.NextValue();
                receiveSum += dataReceivedCounter.NextValue();
            }
            float dataSent = sendSum;
            float dataReceived = receiveSum;

            double utilization = (8 * (dataSent + dataReceived)) / (bandwidth * numberOfIterations) * 100;
            return utilization;
        }

to find the available network cards this code helped me:
public void printNetworkCards()
        {
            PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");
            String[] instancename = category.GetInstanceNames();

            foreach (string name in instancename)
            {
                Console.WriteLine(name);
            }
        }


text:
Q: Subscription website architecture questions + SQL Server & .NET I have a few questions about the architecture of a subscription service I am about to embark on and I am looking for some feedback on how best to set it up.
I won't have a large amount of customers as Basecamp, maybe a few hundred and was wondering what would be a solid architecture for setting up the customer sites. I'm running SQL Server and .NET on a dedicated machine. Should create a new database for each customer as to have control and isolation of data or keep them all in one database?
I am also thinking of creating a sub-domain for each customer as well so modifications can be made to each site as needed.  The customer URLs would look like this:
https://customer1.foobar.com
https://customer2.foobar.com
I am going to have the ability to 'plug-in' reports that will be uploaded to the site so each customer can customize as needed. Off the top of my head this necessitates having each sub domain on its own code-base for the uploading of these reports.
So on the main site the customer would sign up for their new subscription and I would programmatically create a new directory for the customer from the main code base and then create a sub domain pointing to the new directory for the customer and then finally their database.
Does this sound about right? Am I on the right track? How do other such sites accomplish the same thing?
Thanks for letting me bend your ear for a bit on this.

A: From a maintenance perspective, having a virtual directory for each customer scares me. Having done something similar, I would create separate domain pointers as you are intimating. Then you can check the referral headers to see what should be displayed. I would probably create one main site template and dynamically brand it for each customer. You can still create separate folders for customer specific reports or if you really need custom pages unique to that customer. I just wouldn't make each their own site.

A: The advantage of separate sites (including databases) is that the fate on one client isn't bound to all others. It'd be easier to upgrade (trial) to a sub-set before deploying to everyone else. The big issue here, as Scot points out, is time. You'd want to have things as automated as possible (and well tested), etc. It's also easy when a client leaves. You can always just back-up their database and send it to them (for example).
Auto-provisioning new sites and databases isn't easy, and the account that does that will need plenty of privileges - so your security testing will need to be better than usual.
A multi-tenancy approach is good for minimizing your time but you do have to be careful, you don't want customers data getting mixed up.
One approach that will work, within the one app (and database), is to make use of HttpHandlers (MVC framework, perhaps) so that some sort of client identifier is in part of the URL - but the folder doesn't have to physically exist (or virtually in the IIS sense). That way you don't have to worry about getting folder permission correct; but you do have to be careful about correctly identifying clients, their ids, and making sure clients can't make calls that use an id that isn't theirs.
https://www.foobar.com/[clientid]/subscriptions
The advantage of this is it's relatively straight forward: everything is in the application, and you don't have to worry about adding new DNS records, setting directory and/or database permissions, etc.


text:
Q: How to call a native Objective-C method from javascript function in a local HTML5 file and vice-versa using native Objective-C method? I want to call a JavaScript function like:
- (void)alertMe:(NSString *)msg {
[[[UIAlertView alloc] initWithTitle:@"Alert" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
}

and
function alertMe(msg) {
alert(msg);
}

How can I call it using XCode if the HTML file is loaded on a UIWebView in XCode

A: Use the delegate method UIWebView
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
implement query string for your javascript function

A: You can use EasyJSWebView to easily implement calling Native Objective-C method from JavaScript.
The more convenient way is to implement a class that holds all your methods that your JS will call and instantiate that class with your UIWebView Control Object subclass with EasyJSWebView as an argument.
For example:
I created a class JSInterface to hold all my native Obj-C methods
I have a custom method
- (void)initializeJSInterfaceForWebView:(EasyJSWebView *)webView {
    self.jsInterface.appDelegate = appDelegate;
    self.jsInterface.webView.delegate = self;
    [webView addJavascriptInterfaces:self.jsInterface WithName:@"nativeInterface"];
}

that will initialized EasyJSWebView.
I instantiate
self.jsInterface = [JSInterface initWithView:self];
[self initializeJSInterfaceForWebView:self.webView];

For instance, we have a native Objective-C method:
- (void) printLog:(NSString *)msg {
    NSLog(@"%@", msg);
}

To call on the native method from JavaScript using the nativeInterface object name as follows:
nativeInterface.printLog("This is only a test.");

A: You may want to implement query string for your JavaScript function e.i:
function getQueryString(){
var mySearch = window.location.search.substr(1).split("&");

     if (mySearch!="")
     {
          for(var x=0;x<mySearch.length;x++) {
                // loop to all your query string here
          }

     }
}//end function

Or you may also want to use the method

[webView stringByEvaluatingJavaScriptFromString:(NSString*)]

where you may call you local javascript like:
[webView stringByEvaluatingJavaScriptFromString:@"javascript:myJSFunction()"];

Bu this method can only be called within the webViewDidFinishLoad:(UIWebView *)webView and/or when called within webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType method the return must be NO.


text:
Q: Enabling rtl support in Vuetify implemented through CDN I am using vuetify through CDN. I need rtl support for my application. How can I enable rtl when using CDN. The following didnot work for me:
Vue.use(Vuetify, {
  rtl: true
})

A: I was finally able to solve it by putting rtl= true inside created event as following:
new Vue({
    data(){ return {
      // data
       }
    },
    created () {
       this.$vuetify.rtl = true;
    }

})

The same could be done for each components as well.


text:
Q: Oracle Entity Framework passing parameter to command text i have a table test
CREATE TABLE TEST
(
  ID    NUMBER,
  NAME  VARCHAR2(30 BYTE)
)

CREATE OR REPLACE TRIGGER test_trigger
BEFORE INSERT
ON test
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT test_sequence.nextval INTO :NEW.ID FROM dual;
END;

ALTER TABLE TEST ADD (
  PRIMARY KEY
 (ID)

Now I want to insert from a page with values from textbox.
The code is given below
protected void ASPxButton1_Click(object sender, EventArgs e)
    {
        //string name = Convert.ToString(ASPxTextBox1.Text);
        int retVal = 0;
        string providerName = "Oracle.DataAccess.Client";
        string constr =
               @"User Id=scott;Password=tiger;Data Source=orcl;enlist=true";

        // Get the provider factory.
        DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);

        try
        {

            using (scope txn = new scope())
            {
                using (DbConnection conn1 = factory.CreateConnection())
                {
                    conn1.ConnectionString = constr;
                    conn1.Open();

                    // Create a command to execute the sql statement.
                    DbCommand cmd1 = factory.CreateCommand();
                    cmd1.Connection = conn1;
                    cmd1.CommandText = @"insert into test ( [NAME] ) values (:name)";
                    //OracleParameter Nameprm = cmd1.Parameters.Add("name" , OracleDbType.Varchar2, 10 );
                    //Nameprm.Direction = ParameterDirection.Input;
                    //Nameprm.Value = ASPxTextBox1;
                    var name = Convert.ToString(ASPxTextBox1);
                    var parameter = factory.CreateParameter();
                    parameter.DbType = System.Data.DbType.String;
                    parameter.ParameterName = "@name";
                    parameter.Value = name;
                    cmd1.Parameters.Add(parameter);

                    retVal = cmd1.ExecuteNonQuery();

                    //Console.WriteLine("Rows to be affected by cmd1: {0}", retVal);

                    // Close the connection and dispose the command object.
                    conn1.Close();
                    conn1.Dispose();
                    cmd1.Dispose();

                }

                txn.SaveChanges();
            }

        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

But i am always getting ORA-00928: missing SELECT keyword. but if i give values directly then its inserting data. I am trying to solve it in many ways still no luck. Your help will be very much appreciated as i am stuck here. Thank you in advance.

A: I don't think that your parameter name is correct.
Try changing:
parameter.ParameterName = "@name";

to
parameter.ParameterName = "name";

A: @competent_tech 's answer looks good, as an additional thought:
In my last job-but-one we used a massive Oracle database for all our persistence, and I had no end of grief with this sort of problem.  Most of them were solved when I stopped using the built-in ADO.Net drivers and used the Oracle provided drivers (as recommended by Microsoft here).
You can get the Oracle Data Provider for .Net (ODP.Net) for your version of Oracle here.
If you're already using the ODP.Net my sincere apologies, it's a little hard to tell from the code snippet :)
If the name isn't the problem, then it may be with the parameter type (OracleDBType.VarChar2, although this should be inferred for you by DbType) or the parameter direction (ParameterDirection.InputOnly parameter?)
I hope that might help :)


text:
Q: Where is the setting for automatically adding " in html-attributes in PhpStorm If I try to write puggan in a html-dockument in PhpStorm, it ends up as: /puggan.se/">puggan
The problem is that when I add the = after href, it automatically adds two quotes ", and places the cursor between them, and when I write the " myself (as I'm used to do), its overwrites the 2nd ", and the cursor ends up behinds them, and the attribute value ends up outside the ".

*

*Where is the setting for turning this off?

*Dose it have a name?

A: *

*Settings/Preferences

*Editor | General | Smart Keys

*Disable XML/HTML | Add quotes for attribute value on typing '=' and attribute completion option


text:
Q: What will happen with a domain user if I quit the domain? I bought my old laptop from my company. It has Windows 10 installed and I do not want to reinstall it. This computer is still in the corporate domain but there is trouble with Windows updates on it: I cannot change settings because of its domain policy.
I have a domain user that I use to login with. This one is a local admin.
If I exit the current domain will I be able to login with this domain user? This is a domain user and I'm scared that I can't login anymore if I do this.

A: Once you remove the computer from the domain you will no longer be able to logon using your domain user account. Therefore you should create a new local user account for continued use of the computer:

*

*Create a new local user account. Make it an Administrator

*Login with the new local admin account.

*Optionally, copy any files from the domain user account you want to keep. (The domain user's profile folders won't be removed from the machine when the PC is removed from the domain, but as noted above you won't be able to logon to the account directly to access them.)

*Remove the computer from the domain.


text:
Q: Show and hide loading spinner with Angular on HTTP I spent the last days trying to move from AngularJS to Angular. I already have a web app and I want to rewrite it for exercise. One of the features I had in the old one was a loading spinner during a HTTP request. I searched on Google and online tutorials to see how I could do that with Angular and I opted for a service. Here is the code:
spinner.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';

export interface ISpinnerState {
  show: boolean
}

@Injectable()
export class SpinnerService {
  private _spinnerSubject = new Subject();

  spinnerState = <Observable<ISpinnerState>>this._spinnerSubject;

  show() {
    this._spinnerSubject.next(<ISpinnerState>{ show: true });
  }

  hide() {
    this._spinnerSubject.next(<ISpinnerState>{ show: false });
  }
}

spinner.component.ts
import {Component, OnDestroy, OnInit} from '@angular/core';
import { Subscription } from 'rxjs/Rx';

import { ISpinnerState, SpinnerService } from './spinner.service';

@Component({
  selector: 'loading-spinner',
  template: `
    <div
      class="spinner">
    </div>
  `,
  styles: [`.spinner {position: absolute;left: 46%;top: 12%;background-color:black;width:50px;height:50px}`]
})

export class SpinnerComponent implements OnDestroy, OnInit {
  visible = false;

  private _spinnerStateChanged: Subscription;

  constructor(private _spinnerService: SpinnerService) { }

  ngOnInit() {
    this._spinnerStateChanged = this._spinnerService.spinnerState
      .subscribe((state: ISpinnerState) => this.visible = state.show);
  }

  ngOnDestroy() {
    this._spinnerStateChanged.unsubscribe();
  }
}

At the moment, it is just a black square so I can test it. After that, I will add a proper loading icon. Here is another service that I call it during an HTTP request.
apartment.service.ts
....other stuff

@Injectable()
export class ApartmentService {

  constructor(
    private _http: Http,
    private _spinnerService: SpinnerService
  ) { }

getApartments() {
    this._spinnerService.show();
    return this._http.get(API + 'apartments')
      .map((response: Response) => <Apartment[]>response.json().apartments)
      //.catch(this._exceptionService.catchBadResponse)
      .finally(() => this._spinnerService.hide());
  }

}

The problem is that the spinner is always visible. Not only on the loading process. I cannot see what I have done wrong. Any idea?

A: I think you are missing the binding to show/hide depending on the visible state:
<div *ngIf="visible"
  class="spinner">
</div>


text:
Q: Type error when making generic MessageBus in Typescript (with rxjs) I'm trying to make a generic MessageBus in Typescript. I want to have some message classes that derive from a parent MessageBusMessage class. Then I want to be able to subscribe to messages of this class, and have messages of this type returned. Strong generic typing all the way.
This is what I have so far:
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/filter';

export class MessageBusMessage {
}

export class TestMessage extends MessageBusMessage {
    constructor(public readonly someValue: string) {
        super();
    }
}

export class MessageBus {
    private subject: Subject<MessageBusMessage>;

    constructor() {
        this.subject = new Subject();
    }

    public publish(message: MessageBusMessage) {
        this.subject.next(message);
    }

    public getMessagesOf<T extends MessageBusMessage>(messageType: T): Observable<T> {
        return this.subject.filter( (message) => {
            return (message.constructor as any).name === (messageType as any).name;
        }) as any;
    }
}

const messageBus = new MessageBus();
const subscription = messageBus.getMessagesOf(TestMessage).subscribe(
    (message) => {
        console.log('got test message', message.someValue);
    }
)

messageBus.publish(new TestMessage('some test value'));

The problem is inside the message subscription. The type of the message is the constructor type, not the actual object instance type, so I get a type checking error from the Typescript compiler: Property 'someValue' does not exist on type 'typeof TestMessage'.
So I can see how the type Observable is wrong for the return type of getMessageOf. But what is the correct type? How do I get a hold of the object instance type?

A: You need to declare getMessagesOf<T> as taking the constructor for T rather than an instance of T:
public getMessagesOf<T extends MessageBusMessage>(messageType: new (...args: any[]) => T): Observable<T>


text:
Q: How do I monitor file modifications of a Linux user from the user process instead of the file-system itself? We have a requirement to fill that will give us a daily report on all the changes that were made (and who made them) through the SSH protocol; whether it be files or database resources.
Monitoring database actions are no problem with the exception that we have about 4000 queries per second and logging each just to capture queries from a certain user or host requires some planning. But it can be done so I'm okay with this.
We have a few senior developers who have ssh access to production web servers for various reasons. Files can be edited using VIM or other common text-editors such as Pico but a deployment system is suppose to be used instead. We need to watch and report on when the web environment is modified outside of this deployment process.
Our web directory structure is filled with over 5,000,000 different files and folders, some directories have so many files in it, the command "ls" breaks or simply hangs. This is a inherited CRM system but its live production. For this reason, utilities such as ossec hids, inotify or other system/file monitoring processes would require to much resources for real-time monitoring and notification.
Instead of monitoring the file-system, it should be possible to simply monitor the user and watch for when they access files or directories within a defined path as well as record the changes they make.
As for the requirements, we need to present a daily report of all file and database changes made throughout the day (via ssh), and if needed, produce what changes were made (a before & after).
The Linux command utility 'script' almost gives us the replay except it doesn't like to work when the user opens certain programs (vim, etc). Another method of recording is needed.
I'm surprised there isn't a bonafide package out there that has an all-in-one real-time terminal-based user monitoring solution; complete with directory path tracking, resource access, modifications with time sliders, event history that can be filtered by host or user (local/ldap/etc).
Or... is there one?

A: I think auditd might be what you're looking for. Though I'm not sure if is capable of logging diffs.


text:
Q: Unable to access facebook via Firefox when IPv6 is enabled I have a really strange situation. When IPv6 is enabled, I can't access facebook. I can browse to it, but all the AJAX queries fail, so I cannot view the feed, send messages, or do anything remotely useful.
facebook.com is pingable and returns an IPv6 address:
$ ping facebook.com
PING facebook.com(edge-star-mini6-shv-01-nrt1.facebook.com (2a03:2880:f10f:83:face:b00c:0:25de)) 56 data bytes
64 bytes from edge-star-mini6-shv-01-nrt1.facebook.com (2a03:2880:f10f:83:face:b00c:0:25de): icmp_seq=1 ttl=54 time=21.3 ms
64 bytes from edge-star-mini6-shv-01-nrt1.facebook.com (2a03:2880:f10f:83:face:b00c:0:25de): icmp_seq=2 ttl=54 time=21.8 ms
64 bytes from edge-star-mini6-shv-01-nrt1.facebook.com (2a03:2880:f10f:83:face:b00c:0:25de): icmp_seq=3 ttl=54 time=20.7 ms

I can disable IPv6, and then everything works:
$ sudo sysctl -p
[sudo] password for misha:
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
$ ping facebook.com -c 5
PING facebook.com (31.13.82.36) 56(84) bytes of data.
64 bytes from edge-star-mini-shv-01-nrt1.facebook.com (31.13.82.36): icmp_seq=1 ttl=55 time=20.3 ms
64 bytes from edge-star-mini-shv-01-nrt1.facebook.com (31.13.82.36): icmp_seq=2 ttl=55 time=20.4 ms
64 bytes from edge-star-mini-shv-01-nrt1.facebook.com (31.13.82.36): icmp_seq=3 ttl=55 time=21.4 ms
64 bytes from edge-star-mini-shv-01-nrt1.facebook.com (31.13.82.36): icmp_seq=4 ttl=55 time=21.5 ms
64 bytes from edge-star-mini-shv-01-nrt1.facebook.com (31.13.82.36): icmp_seq=5 ttl=55 time=21.1 ms

--- facebook.com ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4007ms
rtt min/avg/max/mdev = 20.330/20.957/21.503/0.493 ms

Everything continues to work well for a few hours, until IPv6 gets somehow re-enabled, and I have to repeat the procedure.
My questions:

*

*Why is FB not working when IPv6 is enabled?

*Why does IPv6 get re-enabled after some time passes? I updated sysctl.conf, so shouldn't the changes be permanent?

A: Facebook uses IPv6 a lot, so it should definitely work. Their datacenters are completely IPv6 internally.
What you might be seeing are problems with MTU handling. The initial page might be smaller than the lowest MTU, or maybe that server uses different packet sizes. If the other requests have different sizes, or their servers handle path MTU discovery differently, then you might see something like this. It's a guess though.
Are you using an IPv6 tunnel by any chance? That might explain part of it. I'll update the answer when you provide more information.


text:
Q: Point my Domain to another Domain's sub-domain I am developing an application which process is like below:

*

*User do registration

*System will create a sub-domain as the username registered.
i.e : xyz.abc.com

*User will build his webpage under this sub-domain (xyz.abc.com)

*if user got a domain (example.com), user will be able to link the domain with the sub-domain that was created during registration.

My Question is:
To link the Domain (example.com) with the sub-domain (xyz.abc.com) what need to do?
Note: user will browse the domain (example.com) and will view the content from Sub-Domain (xyz.abc.com).
Do I need to do CNAME, A Record or ALIAS configuration?

A: There are two layers in this.

*

*The web server needs to know the external domain in order to serve the correct content requested in the HTTP Host: header. This is a HTTP protocol thing: DNS can't do this for you as it, in all its forms, only resolves names to IP addresses. The connection to the server is always established using the IP address alone.
You wouldn't want your users to write freely anything to your web server configuration, so you need to check at least:

*

*The syntax: it must be a valid FQDN (minus root .).

*The maximum sub domain level.

*That there is a valid corresponding A record in DNS.

*Whether the user has right to use this domain or not. You could e.g. require an additional example.com. TXT "kazi=userid" record to confirm that someone is not trying to use a domain of another user. (A CNAME instead of A would do this for a sub-domain to sub-domain arrangement, but you can't use it for the domain itself.)

*Who is responsible of the DNS? Your question does not state that you are willing to host the DNS for custom domains, as well. For external DNS you must write a proper documentation on what records are required for using your service.