text:
Q: Blur textbox when an item is selected with mouse or enter key I'm having problems trying to resolve the issue with the tab key with an autocomplete field.
The idea is that when a user presses the up or down key, and then tabs to make a selection and move to the next field, what happens is that the tab unexpectedly skips to some other (possible) tabindex.
The whole thing is driving me nuts, here is the code:
$(function () {
    var countryTags = ["China", "Colombia", "Cuba"];
    var cityTags = ["China", "Colombia", "Cuba"];
    $("#whatcountry").autocomplete({
        source: function (request, response) {
            var results = $.ui.autocomplete.filter(countryTags, request.term);
            response(results.slice(0, 5));
        },
        select: function (event, ui) {
            $("#whatcity").focus();
        }
    });
    $("#whatcity").autocomplete({
        source: function (request, response) {
            var results = $.ui.autocomplete.filter(cityTags, request.term);
            response(results.slice(0, 5));
        },
        select: function (event, ui) {
            $("#Submitme").focus();
        }
    });
    // Hover states on the static widgets
    $("#dialog-link, #icons li").hover(
        function () {
            $(this).addClass("ui-state-hover");
        },
        function () {
            $(this).removeClass("ui-state-hover");
        });
});

Please see the jsfiddle! which demonstrates the problem.
Any ideas?

A: jQuery UI autocomplete seems to do a good job with setting focus when tab key is used to select an item. Set a special case to handle selection via enter key or click:
select: function (event, ui) {
    var e = event.originalEvent.originalEvent;
    if (e.which === 1 || e.which === 13) {
        $("#whatever").focus();
    }
}

Demo here
Read the documentation to improve the code


text:
Q: Exponential: What's the probability John will wait more than 1 hour for his 4 friends? I was studying for statistics exam and I'm having a hard time solving this problem:
John is never late and his friends are usually 20 minutes late (exponencial distribuition).

*John invited one of his friends for lunch, what's the probability he will wait less than 30 minutes?
This one was easily solved by using the comulative distribuition function

*If John invites his four friends, what's the probability he will have to wait more than 10 minutes alone?
This one was solved in a similar fashion to the above one, calculating the probability for one friend and then taking the power of four of the result.

*What's the probability John will have to wait more than 1 hour for everyone to be on the spot?
This is the one I'm having issues with. I've tried taking the probability of waiting more than 60 minutes for one of them as I did with the problem above, however, since it's for all four friends, only the last one matters and they can either reach all after 60 minutes, only one after 60 minutes, two of them, etc.
Edit for clarity: Basically at least one of his friends (the last one to arrive) has to arrive after 60 minutes, they can all be an hour late but it can also happen that only one is that late, and so on.
Appreciate any answer or feedback.

A: The last one is just the same as the next to last.  For the last one, to wait less than one hour, compute the chance one friend is there within one hour.  Now you need them all there within one hour, so raise it to the fourth power. That gives the chance he does not wait more than one hour, so subtract from $1$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tibco JMS Queue Requestor" or "JMS Queue Sender" Dinamic JMS properties mapping I am working with Tibco BW5.I have JMS selectors string that looks like this:
SelectorString = "Name='Value' AND Name='Value' AND Name='Value' AND ...."

I need to use this string in "JMS Queue Requestor" or "JMS Queue Sender" as JMS selectors.
Solution:
For setting selectors to "JMS Queue Requestor" or "JMS Queue Sender" I am using "DynamicProperties" in "Input" tab:

For mapping SelectorString to "DynamicProperties" I created  "Repeat-Until-True" group with MapData inside.
Repeat condition:
($i >= count(tib:tokenize($Start/root/SelectorString, "AND")))

I map "name" to:
tib:trim(tib:tokenize(tib:tokenize($Start/root/SelectorString, "AND")[$i], "=")[1])

I map "value" to:
substring-before(substring-after(tib:tokenize(tib:tokenize($Start/root/SelectorString, "AND")[$i], "=")[2], "'"), "'")

Then I set accumulated output to "JMS Queue Requestor" dynamic properties.
Please see screenshot:

Is there more elegant way to do this ?

A: Looks like you have not much experience with set-based math ... a typical "sequential programmer's approach to sets":-(
Assuming that the you have a non-hierarchical statement (containing ONLY "AND" between name value pairs) you can once translate " AND " into a single "special char" (like "¶"), use a for-each XML element with the tokenized string it by this char and then split and trim the name and values inside the for-each.
Process with mapping
ActivityInput:
That's the set-based approach which btw is much faster than the iteration loop (4 simple lines of XPath code)


text:
Q: error while configuring FFmpeg in CentOS: Segmentation fault & gcc is unable to create an executable file I am trying to compile FFmpeg in CentOS from source code. I referenced the official compilation guide (https://trac.ffmpeg.org/wiki/CompilationGuide/Centos) for CentOS step by step, and have installed the listed dependencies. But when I tried to configure FFmpeg, I met with a problem as below:

The error lines (1249~1270) in file configure are:
check_exec(){
    check_ld "cc" "$@" && { enabled cross_compile || $TMPE >> $logfile 2>&1; }
}

check_exec_crash(){
    log check_exec_crash "$@"
    code=$(cat)

    # exit() is not async signal safe.  _Exit (C99) and _exit (POSIX)
    # are safe but may not be available everywhere.  Thus we use
    # raise(SIGTERM) instead.  The check is run in a subshell so we
    # can redirect the "Terminated" message from the shell.  SIGBUS
    # is not defined by standard C so it is used conditionally.

    (check_exec "$@") >> $logfile 2>&1 <<EOF

The config.log shows:
zscale_filter=yes
zscale_filter_deps=libzimg
mktemp -u XXXXXX
Ubjjqz
check_ld cc
check_cc
BEGIN /tmp/ffconf.rgbbriKe.c
    1   int main(void){ return 0; }
END /tmp/ffconf.rgbbriKe.c
gcc -I/home/vis/guangli/local/include -c -o /tmp/ffconf.LLalSg6X.o /tmp/ffconf.rgbbriKe.c
gcc -L/home/vis/guangli/local/lib -ldl -o /tmp/ffconf.G3SYKa9M /tmp/ffconf.LLalSg6X.o
C compiler test failed.

My OS is CentOS x86_64, the gcc installed in system is gcc-4.4.6, but in order to compile FFmpeg with gcc-4.8.2, I add GCC482_HOME/{bin,include} to environment variables: PATH, C_INCLUDE_PATH correspondingly.

A: Turns out (for reasons yet unknown) that any executable placed in /tmp on your system segfaults. Even cp /bin/ls /tmp && cd /tmp && ./ls gives an ls that segfaults. But if moved to your home directory, then it works.
That is breaking configure; the obvious workaround is to create a subdirectory of your home directory and set TMPDIR to that.


text:
Q: Flask admin , update a column after_model_change not working I have successfully overridden on_model_change in flask but when I try to do the same for after_model_change it does nothing , how to make changes to model after model changes ?
Class CustomAdminView(ModelView):  # pylint: disable=no-init

    #works fine and udpates the column
    def on_model_change(self, form, model, is_created):
        curr_user = getpass.getuser()
        model.updatedby = curr_user

    #does nothing to the model
    def after_model_change(self, form, model, is_created):
        current_remarks= model.remarks
        model.rhistory = f'changes made : {current_remarks}'

What I am doing is get the current remarks and update it to the history , but I can get the remarks column data after only it has been updated to the model
If its not possible to do this in make changes after model has been updated ,Can I get the value of the the remarks which user is entering so that I can update it during model update.

A: Reading the after_model_change docs you can see that the model has already been committed. If you want to change the model in this method you need to commit the changes to the database. e.g.
def after_model_change(self, form, model, is_created):
    current_remarks= model.remarks
    model.rhistory = f'changes made : {current_remarks}'
    try:
        db.session.commit():
    except Exception as ex:
        db.session.rollback()
        #  handle error

You ask, "Can I get the value of the the remarks which user is entering so that I can update it during model update". Of course you can, providing the remarks field is present in the create/edit form. e.g. The form passed in the on_model_change(form, model, is_created) is the form used to create/update model - see the docs. e.g.
#works fine and udpates the column
def on_model_change(self, form, model, is_created):
    curr_user = getpass.getuser()
    model.updatedby = curr_user

    # assume form has a field called remarks
    model.remarks = form.remarks.data


text: Q: Conormal distributions and the wave front set Let $X$ be a smooth closed manifold and $Y$ a regular submanifold. For all conormal distributions at $Y$ on $X$, their wave front set is contained in the conormal bundle of $Y$. Is the reciprocal true? In another way, is this a characteristic property of conormal distributions?


text:
Q: What do I do with my Google Oauth2 token when trying to call the Calendar API? I'm trying to talk to the Google Calendar API using Ruby. I followed this guide to gain consent from a user, and I saved their authorization token and refresh token. I'm following this guide to call the actual API, but I can't find any instructions anywhere about what specifically to actually do with the token. I assume I'm supposed to include it in the API request somewhere, but where?
Anyone use Google Calendar with Oauth before?

A: I've never used this API nor used Ruby.
But maybe this is part of the documentation you need to read.
https://developers.google.com/identity/protocols/OAuth2InstalledApp#callinganapi
You add a header in your Http request.
In Java (sorry i really don't know anything about Ruby) I do something that looks like this :
headers.add("Authorization", "Bearer " + token);
Hope this helps

A: You need to follow the Google Calendar API Quickstart which has function to trigger authentication flow (def authorize)

*

*This function will create a token file that includes the access token and refresh token

*It will refresh automatically the token when necessary and authorize your calendar service

*Once you have an authorized service, you can use it to perform any calls to the API

Sample how to interlink the quickstart with the guide for event creation:
# This part is from the quickstart and includeds token creation and authorization flow
require "google/apis/calendar_v3"
require "googleauth"
require "googleauth/stores/file_token_store"
require "date"
require "fileutils"

OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze
APPLICATION_NAME = "Google Calendar API Ruby Quickstart".freeze
CREDENTIALS_PATH = "credentials.json".freeze
# The file token.yaml stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
TOKEN_PATH = "token.yaml".freeze
SCOPE = Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY

##
# Ensure valid credentials, either by restoring from the saved credentials
# files or intitiating an OAuth2 authorization. If authorization is required,
# the user's default browser will be launched to approve the request.
#
# @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
def authorize
  client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH
  token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH
  authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store
  user_id = "default"
  credentials = authorizer.get_credentials user_id
  if credentials.nil?
    url = authorizer.get_authorization_url base_url: OOB_URI
    puts "Open the following URL in the browser and enter the " \
         "resulting code after authorization:\n" + url
    code = gets
    credentials = authorizer.get_and_store_credentials_from_code(
      user_id: user_id, code: code, base_url: OOB_URI
    )
  end
  credentials
end

# Initialize the API
service = Google::Apis::CalendarV3::CalendarService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
require "google/apis/calendar_v3"
require "googleauth"
require "googleauth/stores/file_token_store"
require "date"
require "fileutils"

OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze
APPLICATION_NAME = "Google Calendar API Ruby Quickstart".freeze
CREDENTIALS_PATH = "credentials.json".freeze
# The file token.yaml stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
TOKEN_PATH = "token.yaml".freeze
SCOPE = Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY

##
# Ensure valid credentials, either by restoring from the saved credentials
# files or intitiating an OAuth2 authorization. If authorization is required,
# the user's default browser will be launched to approve the request.
#
# @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
def authorize
  client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH
  token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH
  authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store
  user_id = "default"
  credentials = authorizer.get_credentials user_id
  if credentials.nil?
    url = authorizer.get_authorization_url base_url: OOB_URI
    puts "Open the following URL in the browser and enter the " \
         "resulting code after authorization:\n" + url
    code = gets
    credentials = authorizer.get_and_store_credentials_from_code(
      user_id: user_id, code: code, base_url: OOB_URI
    )
  end
  credentials
end

# Initialize the API
service = Google::Apis::CalendarV3::CalendarService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize

# this part uses service to create an event

event = Google::Apis::CalendarV3::Event.new(
  summary: 'Google I/O 2015',
  location: '800 Howard St., San Francisco, CA 94103',
  description: 'A chance to hear more about Google\'s developer products.',
  start: Google::Apis::CalendarV3::EventDateTime.new(
    date_time: '2015-05-28T09:00:00-07:00',
    time_zone: 'America/Los_Angeles'
  ),
  end: Google::Apis::CalendarV3::EventDateTime.new(
    date_time: '2015-05-28T17:00:00-07:00',
    time_zone: 'America/Los_Angeles'
  ),
  recurrence: [
    'RRULE:FREQ=DAILY;COUNT=2'
  ],
  attendees: [
    Google::Apis::CalendarV3::EventAttendee.new(
      email: 'lpage@example.com'
    ),
    Google::Apis::CalendarV3::EventAttendee.new(
      email: 'sbrin@example.com'
    )
  ],
  reminders: Google::Apis::CalendarV3::Event::Reminders.new(
    use_default: false,
    overrides: [
      Google::Apis::CalendarV3::EventReminder.new(
        reminder_method: 'email',
        minutes: 24 * 60
      ),
      Google::Apis::CalendarV3::EventReminder.new(
        reminder_method: 'popup',
        minutes: 10
      )
    ]
  )
)

result = service.insert_event('primary', event)
puts "Event created: #{result.html_link}"

All you need to interlink those two code parts is to change the name
  from client to service or vice versa.


text:
Q: Custom TFS Check-In Policy in Visual Studio 2017 A while ago I developed a custom TFS check-in policy that was working fine with Visual Studio 2015.
Now I installed Visual Studio 2017 and wanted to register the check-in policy assembly the same way as I did with VS2015 before. But this does not work. How can I register custom check-in policy assemblies with VS2017?
For VS2015, I had these registry keys:
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\14.0\TeamFoundation\SourceControl\Checkin Policies]
"MyCheckInPolicy"="C:\\Program Files\\My\\MyCheckInPolicy.dll"

and
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\14.0_Config\TeamFoundation\SourceControl\Checkin Policies]
"MyCheckInPolicy"="C:\\Program Files\\My\\MyCheckInPolicy.dll"

and accordingly I added those keys for VS2017 (15.0):
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\15.0\TeamFoundation\SourceControl\Checkin Policies]
"MyCheckInPolicy"="C:\\Program Files\\My\\MyCheckInPolicy.dll"
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\15.0_Config\TeamFoundation\SourceControl\Checkin Policies]
"MyCheckInPolicy"="C:\\Program Files\\My\\MyCheckInPolicy.dll"

But unfortunately this does not work:

*

*If I open the Team Project SourceControl settings, go to the "Check-in Policy" tab and try to Add... a policy, MyCheckInPolicy does not appear1

*If I open the team project that uses this check-in policy already and do the above, I got an error message telling me that the assembly (mycheckinpolicy) "has not been registered".

Of course I restarted the IDE after the registry change, but even rebooting my machine did not help.
The information I found so far seems to suggest that check-in policies now have to be part of an extension (vsix), which I don't want to believe.

I guess that the problem comes from some references that cannot be resolved when the assembly is loaded into the IDE.
The MyCheckInPolicy project references the Microsoft.TeamFoundation.VersionControl.Client.dll v14.0 from the VS2015 folder C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer.
I tried to reference the respective dll from the VS2017 folders, but then the assembly does not work in both IDEs.
I also tried to use the Nuget package "Microsoft.TeamFoundation.VersionControl.All" v12.0.30723.2 instead and deployed all files from the output directory (which seem to contain all assemblies of the package) to the location mentioned in the registry keys. This had the same result: the policy cannot be loaded in neither VS2015 nor VS2017.
We are using TFS 12.0.30723.0.

1So it seems VS2017 doesn't even try to load the assembly and does not care about the registry keys?

A: It worked to me adding this key to HKCU:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\15.0\TeamFoundation\SourceControl\Checkin Policies

Hope it helps.
Thanks,
Wilsade

A: In Visual Studio 2017 there are breaking changes to extensibility. Much of the registry configuration has been moved into a "private" registry:

To reduce the impact on the registry, Visual Studio now uses the
  RegLoadAppKey function to store registry keys in a private binary file
  under %VsAppDataFolder%\privateregistry.bin. Only a very small number
  of Visual Studio-specific keys remain in the system registry. (link)

By defining the registry keys as part of a .pkgdef file in a vsix, on installation VS 2017 will (I assume) write the keys to the private registry as opposed to the actual registry, which was the case in previous versions of VS. This will allow the policy to be picked up.
So, here are the steps I went through to get our policies working in VS 2017:

*

*Install the Visual Studio SDK (can be done by modifying your installation if you didn't select the workload originally).

*Add a new VSIX Project to your checkin policy solution

*Add a .pkgdef file to the VSIX project with the following (this is the registry key entry):
[$RootKey$\TeamFoundation\SourceControl\Checkin Policies]
 "YourPolicy"="$PackageFolder$\YourPolicy.dll"

*Modify source.extension.vsixmanifest (using the GUI wizard) in the VSIX project:

*

*Install Targets: Add your lowest supported VS Version:

*

*Microsoft.VisualStudio.Community [15.0,16.0)

*Microsoft.VisualStudio.IntegratedShell [15.0,16.0)

*Assets:

*

*Microsoft.VisualStudio.Assembly

*

*A Project in current solution

*Project: Select your checkin policy project

*Microsoft.VisualStudio.VsPackage

*

*File on filesystem

*Path: Select your .pkgdef file from step 3.

*Prerequisites: Visual Studio core editor [15.0,16.0)

*Build the VSIX project and distribute/install the generated vsix

This GitHub repo was helpful for piecing everything together. Some quirks I found when migrating to the vsix:

*

*By default, vsix installations are now per-user. If you operate VS under multiple users on the same machine you will need to install it for each. There is an option in the vsixmanifest to have the extension installed for all users, but this requires elevation.

*Our checkin policy used an app.config file, which is not supported in a vsix. I had to migrate our settings to a .settings file.


text:
Q: Use multithreading for multiple file copies I have to copy large number of files (10000 files)
because it takes long time to copy.
I have tried using two threads instead of single thread, one to copy odd number files in list and other to copy even numbers from list
I have used this code:
ThreadPool.QueueUserWorkItem(new WaitCallback(this.RunFileCopy),object)

but there is no significant difference in time when using single thread and when using two threads.
What could be the reason for this?

A: File copying is not a CPU process, it a IO process, so multithreding or parallelism wont help you.
Multithreading will slow you down in almost all cases.If disc is SSD too it has a limited speed for r/w and it will use it efficiently with single thread too. If u use parallelism you will just split your speed into pieces and this will create a huge overhead for HDD
Multithreading only helps you in more than one disc case, when you read from different discs and write to different discs.
If files are too small. Zipping and unzipping the files on the target drive can be faster in most cases, and if u zip the files with low compression it will be quite faster
using System.IO;
using System.IO.Compression;

.....

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";

ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);

ZipFile.ExtractToDirectory(zipPath, extractPath);

More implementation details here
How to: Compress and Extract Files

A: I'm going to provide a minority opinion here.  Everybody is telling you that Disk I/O is preventing you from getting any speedup from multiple threads.   That's ... sort ... of right, but...
Given a single disk request, the OS can only choose to move the heads to the point on the disk selected impliclity by the file access, usually incurring an average of half of the full stroke seek time (tens of milliseconds) and rotational delays (another 10 milliseconds) to access the data. And sticking with single disk requests, this is a pretty horrendous (and unavoidable) cost to pay.
Because disk accesses take a long time, the OS has plenty of CPU to consider the best order to access the disk when there are multiple requests, should they occur while it is already waiting for the disk to do something.  The OS does so usually with an elevator algorithm, causing the heads to efficiently scan across the disk in one direction in one pass, and scan efficiently in the other direction when the "furthest" access has been reached.
The idea is simple:  if you process multiple disk requests in exactly the time order in which they occur, the disk heads will likely jump randomly about the disk (under the assumption the files are placed randomly), thus incurring the helf-full seek + rotational delay on every access.  With 1000 live accesses processed in order, 1000 average half-full seeks will occur.  Ick.
Instead, give N near-simultaneous accesses, the OS can sort these accesses by the physical cylinder they will touch, and then process them in cylinder order. A 1000 live accesses, processed in cylinder order (even with random file distributions), is likely to have one request per cylinder.  Now the heads only have to step from one cylinder to the next, and that's a lot less than the average seek.
So having lots of requests should help the OS make better access-order decisions.
Since OP has lots of files, there's no reason he could not run a lot of threads, each copying its own file and generating demand for disk locations.    He would want each thread to issue a read and write of of something like a full track, so that when the heads arrive at a cylinder, a full track is read or written (under the assumption the OS lays files out contiguously on a track where it can).
OP would want to make sure his machine had enough RAM to buffer his threadcount times tracksize.  An 8Gb machine with 4 Gb unbusy during the copy has essentially a 4 Gb disk cache.  A 100Kb per track (been a long time since I looked) suggests "room" for 10,000 threads.  I seriously doubt he needs that many; mostly he needs enough threads to overwhelm the number of cylinders on his disk.   I'd surely consider several hundred threads.
Two threads surely is not enough. (Windows appears to use one thread when you ask it copy a bunch of files. That's always seemed pretty dumb to me).
Another poster suggested zipping the files.  With lots of threads, and everything waiting on the disk (the elevator algorithm doesnt change that, just the average wait time), many threads can afford to throw computational cycles at zipping.  This won't help with reads; files are what they are when read.  But it may shorten the amount of data to write, and provide effectively larger buffers in memory, providing some additional speedup.
Note: If one has an SSD, then there are no physical cylinders, thus no seek time, and nothing for an elevator algorithm to optimize.  Here, lots of threads don't buy any cylinder ordering time.   They shouldn't hurt, either.


text:
Q: Amazon Managed Airflow Dags wont sync Did anyone try the new Amazon managed services Airflow? I did all the steps mentioned and could open airflow link. But none of the dags are synched. I don't see any error. I event tried updating the environment with a different S3 bucket .

A: Are you uploading dags in the dags folder in your s3 bucket?
dags.py should be inside the dags folder in s3 bucket to get synced.


text:
Q: Delete the key which contains empty object inside an array using javascript or jQuery I want to delete the JSON key which contains empty object inside an array...
This is my JSON structure:
{
    "CreateSubnet": {
        "description": "Creatingasubnet.",
        "input": {
            "body": {
                "subnet": {
                    "network_id": "sdfsdfds",
                    "ip_version": "sdfdsfs",
                    "cidr": "sdfsdf",
                    "allocation_pools": [
                        {}
                    ]
                }
            }
        },
        "action": "neutron.create_network",
        "publish": {},
        "on-success": []
    }
}

Please help me to delete the element "allocation_pools"..
I never want this key and this value ...
The expected output JSON will be look like...
{
    "CreateSubnet": {
        "description": "Creatingasubnet.",
        "input": {
            "body": {
                "subnet": {
                    "network_id": "sdfsdfds",
                    "ip_version": "sdfdsfs",
                    "cidr": "sdfsdf"
                }
            }
        },
        "action": "neutron.create_network",
        "publish": {},
        "on-success": []
    }
}

Note this JSON is from external source it changes dynamically...
So please tell me how to validate the JSON key contains Array...
if yes , Check whether it has empty object or not ....
This is my question

A: Use the delete operator to remove the property.

var obj = {
    "CreateSubnet": {
        "description": "Creatingasubnet.",
        "input": {
            "body": {
                "subnet": {
                    "network_id": "sdfsdfds",
                    "ip_version": "sdfdsfs",
                    "cidr": "sdfsdf",
                    "allocation_pools": [
                        {}
                    ]
                }
            }
        },
        "action": "neutron.create_network",
        "publish": {},
        "on-success": []
    }
}
delete (obj.CreateSubnet.input.body.subnet.allocation_pools);
document.getElementById("output").innerHTML = JSON.stringify(obj)


text:
Q: Cordova/Phonegap install file to externalDataDirectory I am using the cordova file plugin to read and write to files on my android device. What I would like to do is to 'install' a json file to the cordova.file.externalDataDirectory directory. This file will contain default settings for the application but i would like to allow users to edit these settings as well (and so can't be hidden in the apps sandbox).
I can't seem to find a way how to do this. Is it possible?
The only alternative i can think of is to install a default settings file to the apps sandbox and on app bootup copy this file to the cordova.file.externalDataDirectory directory. This isn't ideal but it might be the the way that i'll have to go...

A: You should use something like this:
        fileEntry.createWriter(function(fileWriter) {
            // ...
            var blob = new Blob(['{"key":"value"}'], {type: 'text/plain'});
            fileWriter.write(blob);

        }, function(e){console.log('Error')});

wrapped inside:
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(fileEntry) {
     // ...
});

I cannot test it now, but I hope it's useful. Check also the filesystem api guide and this tutorial.


text: Q: How can I use Deepin OS's boot disk to delete and merge partitions I was dual booting Windows 10 and Elementary OS and decided to overwrite the Elementary OS with Deepin. After installing the Deepin successfully and was trying to restart then no hard disk issue appeared. I can see that I now have too many partitions. How can I delete some of the unwanted partitions? I am desperate now because I want to go into my Windows 10 where development environment is.


text:
Q: my app is not showing in the list to open shared location Hi i am developing an app to open shared location on google map fragment inside app .When user touches a location link shared my app should shown in open with list. here is my manifest
this is what i have tried by adding intent filter
<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data android:scheme="http" android:host="maps.google.com" android:pathPattern="/maps"/>
  <data android:scheme="https" android:host="maps.google.com" android:pathPattern="/maps"/>
  <data android:scheme="geo"/>
</intent-filter>

I expect that on click location my app will be shown in open with dialogue.

A: I have tried with this Manifest Entry and it's working for me.
<activity
        <intent-filter>
          <!-- Filter to run activity without geo -->
            <action android:name="com.example.MYACTION" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        <intent-filter>
            <!-- Filter for geo scheme geo -->
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="geo" />
        </intent-filter>
    </activity>

onCreate() of My Activity is like below
protected void onCreate(Bundle savedInstanceState) {
  Intent intent = getIntent();
  String action = intent.getAction();
  Uri data = intent.getData();

  if(Intent.ACTION_VIEW.equals(action) ) {
    if(data != null && "geo".equals(data.getScheme())) {

      // Displaying map when there is geo Data
    }
  }
  else {
    // Other code when there is no geo DATA from intent
  }
}

You can Try and let me know.


text:
Q: My module has __init__.py and still Python can't import it I have a small python module
+-- address_book
|   +-- models.py
|   +-- __init__.py
    +-- test
    |   +-- test_models.py

When I run python address_book/test/test_models.py I get this error
Traceback (most recent call last):
  File "address_book/test/test_models.py", line 5, in <module>
    from address_book import models
ImportError: No module named 'address_book'

test_models.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest
from address_book import models
...
...
...
if __name__ == '__main__':
    unittest.main()

A: Your file structure should look like
+-- address_book
|    +-- __init__.py
|    +-- models.py
     +-- test
     |    +-- test_models.py
     |    +-- __init__.py

For your code to work you also have to be in the directory above address_book.

A: Like said in comment, your tree looks strange. Put tests on the same level as address_book.
To run the tests, you should use auto test discovery tools like nose or pytest (in doubt, go for pytest). Those tools automatically find the packages they are testing so that you don't have to install them or care in any way about their presence in the PATH.
It might sound like a burden at first, having to learn a new tool, but it's pretty straightforward, and on the long run, pytest is really helpful.

A: The problem stems from the fact that python does not know where to look for address_book. You can fix this by setting the PYTHONPATH environment variable before starting python.
Given the following directory structure:
base_dir
+-- address_book
|   +-- __init__.py
|   +-- models.py
    +-- test
    |   +-- test_models.py

Then this will work:
$ env PYTHONPATH=/path/to/base_dir python address_book/test/test_models.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

PYTHONPATH can be a relative path as well, just so long as the relative path points to the source directory from the current working directory
To avoid typing out the env PYTHONPATH=/path/to/base_dir each time you can set it using your shells appropriate syntax. Below I set the PYTHONPATH environment variable using a bash syntax.
$ cd /path/to/base_dir
$ export PYTHONPATH=. # the current directory as a relative link
$ python address_book/test/test_models.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

As a side note I would alter your directory structure as it's not a great idea to keep your tests in the same directory tree as your source directory. Typically you might do something like this:
base_dir
+-- address_book
|   +-- __init__.py
|   +-- models.py
+-- test # no __init__, not a module
|   +-- test_models.py

This allows you to more easily package your project without also including your tests.

A: There is problem with import of module from parent directory as __main__ lies in child folder
if you do the folder structure like below your same code for import will work

+----test
     +---test_models.py
     +---__init__.py
     +---address_book
         +---__init__.py
         +---models.py

or you can add your project path to PYTHONPATH variable and your same code will work


text:
Q: K8S traffic to one service via two separate ingress (http + https) So I have a bunch of services running in a cluster, all exposed via HTTP only ingress object, example:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
  name: some-ingress
spec:
  ingressClassName: nginx
  rules:
  - http:
      paths:
      - backend:
          service:
            name: some-svc
            port:
              number: 80
        path: /some-svc(/|$)(.*)
        pathType: Prefix

They are accessed by http://<CLUSTER_EXTERNAL_IP>/some-svc, and it works ofc.
Now I want to create an additional ingress object for every service which will force SSL connections and allow the use of a domain instead of an IP address.
The problem is that the newer SSL ingresses always return 404 while testing the connection.
The manifests are as follows:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: "some-ingress-ssl"
  annotations:
    ingress.kubernetes.io/ssl-redirect: "true"
    ingress.kubernetes.io/app-root: "/some-svc"
spec:
  tls:
  - hosts:
      - foobar.com
    secretName: foobar-tls
  rules:
  - host: foobar.com
    http:
      paths:
      - path: /some-svc(/|$)(.*)
        pathType: Prefix
        backend:
          service:
            name: some-svc
            port:
              number: 80

tests (foobar.com point to CLUSTER_EXTERNAL_IP):
> curl -I http://<CLUSTER_EXTERNAL_IP>/some-svc
HTTP/1.1 200 OK
> curl -I https://foobar.com/some-svc
HTTP/2 404

Is it possible to have both ingresses simultaneously? (one enforcing SSL, the other not)
If so what am I doing wrong here?

A: Figured out I was missing this annotation:
nginx.ingress.kubernetes.io/rewrite-target: /$2

in SSL ingress...
works like a charm now, maybe someone will find this usefull


text:
Q: How to upload images in Spring MVC from TinyMCE editor I am making a content management system for ecommerce and have a blocks wich would be displayed in different parts of the pages. This blocks can contain html and images, so I use  with TinyMCE to manage blocks content.
I didn't found complete solution anyware - only separate questions about TineMCE or loading images controllers, so I want to share my experience with you - complete JavaScript for TinyMCE initialization and back end controller, that saves images.
JavaScript is taken from this theme answers(I used steve.hanson answer), but I changed it a bit to fit my controller and moved image button methods inside setup function.

A: Important thing- 'files' is the name of multipart form variable in ajax and controller, and request url is : '${pageContext.request.contextPath}/a/images'
JavaScript initialization of TinyMCE and ajax request to process images:
<script src="https://cloud.tinymce.com/stable/tinymce.min.js"></script>
<script>
tinymce.init({
      selector: 'textarea',  // change this value according to your HTML
      auto_focus: 'element1',
      toolbar: 'undo redo | imageupload',
      setup: function(editor) {

              // create input and insert in the DOM
              var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
              $(editor.getElement()).parent().append(inp);

              // add the image upload button to the editor toolbar
              editor.addButton('imageupload', {
                text: 'Add image',
                icon: 'image',
                onclick: function(e) { // when toolbar button is clicked, open file select modal
                  inp.trigger('click');
                }
              });

              // when a file is selected, upload it to the server
              inp.on("change", function(e){
                uploadFile($(this), editor);
              });

            function uploadFile(inp, editor) {
              var input = inp.get(0);
              var data = new FormData();
              data.append('files', input.files[0]);

              $.ajax({
                url: '${pageContext.request.contextPath}/a/images',
                type: 'POST',
                data: data,
                enctype: 'multipart/form-data',
                dataType : 'json',
                processData: false, // Don't process the files
                contentType: false, // Set content type to false as jQuery will tell the server its a query string request
                success: function(data, textStatus, jqXHR) {
                  editor.insertContent('<img class="content-img" src="${pageContext.request.contextPath}' + data.location + '" data-mce-src="${pageContext.request.contextPath}' + data.location + '" />');
                },
                error: function(jqXHR, textStatus, errorThrown) {
                  if(jqXHR.responseText) {
                    errors = JSON.parse(jqXHR.responseText).errors
                    alert('Error uploading image: ' + errors.join(", ") + '. Make sure the file is an image and has extension jpg/jpeg/png.');
                  }
                }
              });
            }
      }
    });

</script>

Here is my controller for Spring MVC and method to save files:
@RequestMapping(value = "/a/images", method = RequestMethod.POST)
@ResponseBody
public String handleTinyMCEUpload(@RequestParam("files") MultipartFile files[]) {
    System.out.println("uploading______________________________________MultipartFile " + files.length);
    String filePath = "/resources/uploads/tinyMCE/" + files[0].getOriginalFilename();
    String result = uploadFilesFromTinyMCE("tinyMCE", files, false);
    System.out.println(result);
    return "{\"location\":\"" + filePath + "\"}";

}

private String uploadFilesFromTinyMCE(String prefix, MultipartFile files[], boolean isMain) {
    System.out.println("uploading______________________________________" + prefix);
    try {
        String folder = context.getRealPath("/") + "/resources/uploads/" + prefix;
        StringBuffer result = new StringBuffer();
        byte[] bytes = null;
        result.append("Uploading of File(s) ");

        for (int i = 0; i < files.length; i++) {
            if (!files[i].isEmpty()) {

                try {
                    boolean created = false;

                    try {
                        File theDir = new File(folder);
                        theDir.mkdir();
                        created = true;
                    } catch (SecurityException se) {
                        se.printStackTrace();
                    }
                    if (created) {
                        System.out.println("DIR created");
                    }
                    String path = "";
                    path = folder + files[i].getOriginalFilename();
                    File destination = new File(path);
                    System.out.println("--> " + destination);
                    files[i].transferTo(destination);
                    result.append(files[i].getOriginalFilename() + " Succsess. ");
                } catch (Exception e) {
                    throw new RuntimeException("Product Image saving failed", e);
                }

            } else
                result.append(files[i].getOriginalFilename() + " Failed. ");

        }

        return result.toString();

    } catch (Exception e) {
        return "Error Occured while uploading files." + " => " + e.getMessage();
    }
}


text:
Q: Are build config keys obfuscated by ProGuard? Is the build config key declared in the build.gradle file obfuscated by ProGuard using proguard-android.txt?
For example:
android {
    buildTypes {
        release {
            buildConfigField "String", "key", "\"value\""
        }
    }
}

A: It depends. If you have minifyEnabled and shrinkResources set to true and not excluded in the proguard rules file, which you should add to your question.


text:
Q: From android.graphics.Path to ImageView I have a android.graphics.Path variable which I want to convert into an ImageView in my activity.
What I do right now and does NOT work (but it does run without error, it just displays a blank activity) is:
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Path p = ... // some bezier curves
        PathShape pathShape = new PathShape(path, (float)20.0, (float)20.0);
        ShapeDrawable shapeDrawable = new ShapeDrawable(pathShape);
        ImageView testImage = (ImageView) findViewById(R.id.testImage);
        testImage.setImageDrawable(shapeDrawable);
    }

}

The corresponding activity_main.xml is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.tg.MindGames.set.MainActivity">
<ImageView
    android:id="@+id/testImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</RelativeLayout>
What did I do wrong and what is considered best practice to put Path into an ImageView?
Additional Information: I want to use the Paths to draw the images of cards in a simple card game. Several cards and additional text fields should be displayed on the activity at the same time, cards should be able to have an onClickListener.
The size of 20.0 x 20.0 is arbitrary and should be altered later when I use the ImageViews in a GridView.

A: so here you have a red triangle drawn on the view's background:
View v = new View(this);
Path path = new Path();
path.moveTo(0, 1);
path.lineTo(0.5f, 0);
path.lineTo(1, 1);
ShapeDrawable sd = new ShapeDrawable(new PathShape(path, 1, 1));
sd.getPaint().setColor(Color.RED);
v.setBackgroundDrawable(sd);
setContentView(v);


text:
Q: C# application copies files from GAC to execution folder I am somewhat new to using the Global Assembly Cache in .NET, and have a question regarding how it works since I haven't been able to find anything online.
My msi(created using Visual Studio Installer extension (using Visual Studio 2015)) installs a number of assemblies into the GAC and my application(the assemblies need to be in the GAC because 3rd party application need to access them too). After running the installer and starting the application, I noticed that when I start my application, copies of the dlls from the GAC are made in the application execution directory.
My question is, is this how using assemblies from GAC normally works? I assumed that the assemblies would just be loaded from the GAC without making local copies. Or is this some error on my part and how I built my application(CopyLocal is set to true but from what I understand, this only matters for Visual Studio and has no effect on actual execution after deployment).

A: Based on Hans' input, the issue is with my msi and is not GAC related. While msi installs the assemblies to GAC and not the execution directory, when the application is run it is msi "self-healing" that creates the files, they are not copied from GAC.


text:
Q: Is it a good idea to either drop requirement for a limit of 6 character for edits, or drop the ability to edit for users under 2K? I have just attempted to make my first edit of another user's post - correcting a reference to a single-letter class name, which otherwise could throw a novice (see paercebal's answer in In C++, what is a virtual base class?).
I was then confronted with the "6 letter limit" for edits because my reputation is below 2K.
Trying to understand the reason for the 6-character limit, I have found and scavenged the following threads: Legitimate edits of less than 6 characters, Change this behavior to allow for spelling corrections and the like: "Edits must be at least 6 characters", How to overcome "Edits must be at least 6 characters"?, Allow under 6 character changes if they are inside code tags, and Suggestion: Allow 1-char edits, if they are within the code block.
These threads are filled with people who disagree with the rule and provide tips and tricks for workarounds.  One of these "tips and tricks" is the "accepted answer" for the third link I just gave, which is a question about how to overcome the 6-character limit.  Here is the relevant quote from the answer:

look for other changes that can be made

It should go without saying that this is not an answer to my question.
Of the links above, there is only one reference to a justification (that I can find).  It says (see comment beneath second question linked above):

The limitations imposed on low-rep editors are largely there to
  discourage incomplete edits

Is this rationale based on experience - that (without the requirement) users below 2K would otherwise tend to overload the system with edits below 6 characters that are trivial or incomplete, such as the fixing of typos, but otherwise tend to make good edits (when over 6 characters), such that simply removing the ability for users under 2K to edit would detract from the community?
Is it really true that for users under 2K, it is known that edits under 6 characters tend to be incomplete, but that edits over 6 characters tend to be complete?
If so, I understand the requirement.  But in this case I would like to recommend that StackExchange add an "orange box" at the top of the "edit" page, appearing only when the editor's reputation is below 2K and only when the number of characters in the edit is less than 6, that says something like:

Edits must be a minimum length of 6 characters for users with a
  reputation below 2K.  This is to discourage incomplete or trivial
  edits.  If you have a legitimate edit of less than 6 characters
  and your reputation is below 2K, please add a comment, which will
  be received by the post's author.

On the other hand, if the "incomplete" rationale is not justified, can StackExchange please either remove the 6-character limitation, or simply remove the ability of users under 2K to make edits?
Quite obviously, for highly popular code-oriented sites such as StackOverflow, code edits can be critical, and the length of the edit has no bearing on its legitimacy.
I suspect that the reason this issue has not been attended to is that most people who develop the StackExchange sites, and other users who make frequent edits, have reputations higher than 2,000.  In my opinion, to the extent that this is true, this is not a justification to maintain an unnecessary and/or unhelpful requirement for users whose reputation is below 2K (that is, if I'm correct that the requirement is unnecessary and/or unhelpful).
Can something please be done about this?  I have taken the time to write this post after running into this issue in order to help the StackExchange sites, so I hope someone else can follow through and recommend that something be changed.

A: My suggestion would be that the character count shouldn't be checked when any change is made inside a code snippet (either inline or block)... even a single character there can produce dramatically different results, in nearly any language.
Since <2k edits are going into a queue for review anyway, I think that's the only change needed.
In the meantime, you definitely should leave a comment on any post that contains an error if you can't fix it yourself.
Of course, this has already been proposed:

*

*Suggestion: Allow 1-char edits, if they are within the code block

*Allow under 6 character changes if they are inside code tags

Please note that I'm not expressing an opinion for or against allowing low rep users to edit code... just that the number of characters changed is a useless metric of whether a change is trivial, when the change occurs in code.

A: Indeed. The arbitrary limits and hard coded regulations on edits have a very annoying effect on editors wishing to help other people.
Just let people edit and let the community moderate itself like it always has.

A: As you have probably seen, the 6-character limit is completely asininearbitrary, so you should feel morally in the clear to abuse it by making pointless edits just to exceed the character limit.
One popular solution is to link to the Wikipedia page for one of the concepts in the text.

A: Everyone has their excuses, but In my humble opinion, Trivial edits(formatting, spelling, grammar, etc.) are more appropriate than non-trivial edits.
Otherwise you risk changing the meaning of the post to something that the author didn't intend.

A: When a user with less than 2k reputation suggests an edit, the idea is that they should not just be fixing one problem with the post; they should fix all of the problems with that post.  This limit is targeted towards what are clearly small fixes for single, narrowly scoped problems, and those are not encouraged by the system.  When someone is fixing all of the problems with a post it should involve editing more than 6 characters.
The reason for this is that the suggested edits need to be reviewed, and those reviews consume time and effort of multiple (2-5+) higher reputation users.  Filling the queue with lots of small edits ends up consuming much more of their time, which could be spent on more valuable edits (or other types of reviews).
Other costs with small edits are that, from the time the edit is suggested until the review is complete the post is locked.  If someone else would like to make a substantive edit but there is a very minor pending edit the substantive edit can't be made.  Additionally there is a limit of 200 pending suggested edits for the entire site at any one time.  If the system is flooded with lots of very minor edits the queue can end up sitting at capacity and thus preventing anyone from suggesting edits to any posts.  This is less of a problem now, with some of the changes to the review system (instead of constantly sitting near capacity during peek hours; it's usually sitting pretty low) but it's still a concern.
As for what you should do; it's fairly simple:

*

*If you notice a small problem with a post that doesn't involve editing more than 6 characters, first be sure that there are no other problems with the post.  If you can find any other problems you should fix them.  Don't just change things that aren't wrong though; your edits should be correct and improvements.

*If you still haven't edited 6 characters you can comment on that post.  Describe the small fix that needs to be made.  Either the OP, or another 2k+ user who comes along can make that edit.  If the change isn't important enough that you feel it's worthy of a comment, then clearly it's fine to leave it.  You can delete your comment if/when the change is made.

*You can wait until you have 2k+ reputation to make such changes.  Note that even if you have 2k reputation you should still strive to fix all problems with a post when you edit it, but this isn't enforced nearly as much as with <2k users.

A: I would say the system worked as it should. Code Edits are generally frowned upon for anything more than cleaning up the formatting. If you see a problem with the code, you should leave a comment so that the poster can verify and fix, or explain why it is not a problem.
EDIT:
Incorrect code: Edit, comment, or provide a correct answer? I would like to point out it is a gray area and that is why I said generally.
The problem is that when you do not have enough rep to do it yourself, and it goes through the suggested edit review queue. I can tell you personally, when I see a code edit to an answer, and the answer was posted by a high rep user I tend to decline it. Rationale being that the high rep users are generally active on the site, and if the editor left a comment pointing out the problem, they would fix it or explain why their answer is correct.

A: The 6-character minimum is arbitrary, just like the 30-character minimum for new answers or the 15-character minimum for comments.
They're based on the belief that, generally-speaking, doing something worthwhile requires a minimal amount of effort. It's pretty easy to find examples that violate this rule, and just as easy to find examples that support it. All things being equal, it rarely hurts to write more...
It's somewhat harder to hit the 2K reputation mark that makes minimum edit lengths irrelevant. But worth it.


text:
Q: AngularJs build a angular-chartjs App Does anybody know why i always get a error message like

angular.js:11607Error: [ng:areq] Argument 'TestCtrl' is not a function, got undefined

I really don't know why this is happening. Here are some files:
App.js
(function(module, undefined) {
  'use strict';

  var $ = require('jquery'),
      _ = require('underscore'),
      angular = require('angular'),
      modulePrototype = require('modulePrototype'),
      chartjs = require('angular-chartjs'),
      ChartController = require('./Controller/ChartController'),
      AjaxService = require('../../Utilities/Service/AjaxService/Service'),
      ajaxServiceInstance;

  var chart = modulePrototype.extend({

    /**
     * @param el
     */
    initialize : function(el) {
      this.el = el;
      this.$el = $(el);

      this.chartApp = angular.module('chart', ['chartjs']);
      this.AppCtrl = new ChartController(this.chartApp, this.el);

      var _this = this;
    }

  });

  module.exports = chart;

})(module);

Controller.js
/**
 * AngularJS Chart App
 *
 * @module ChartController
 */

var $ = require('jquery'),
    _ = require('underscore'),
    angular = require('angular'),
    ChartController;

/**
 * UserController
 * @param angularApp
 * @constructor
 */
ChartController = function(angularApp) {
    'use strict';

    angularApp.controller('TestCtrl', function($scope, $http) {
        console.log('hey');
    });

    return angularApp;
};

// Return the Constructor.
module.exports = ChartController;

And the .html file:

            <cjs-line dataset="activeData" responsive="true"></cjs-line>

        <button ng-click="swapData()">Swap Data</button>

I just want to create a simple chart view for some datas.
Thanks in advance, regards.


text:
Q: Hide element if named router-outlet has active route We are currently developing an Angular 13 application that is split into several independent modules that are maintained by different teams and each module represents the UI for a different application that is backed by its own microservice.
These modules are allowed to depend on our "SharedModule", but not the other way around.
Now, we want to implement a "Help Center" which consists of a question mark button that floats in the lower right corner and if clicked provides help for the currently loaded page. The thing is, that we want to keep the content of each modules Help Center pages inside that module, furthermore, some modules do not need Help Center pages.
Our current solution adds a component to our main layout:
<router-outlet name="navbar"></router-outlet>

<router-outlet></router-outlet>

<app-help></app-help>

<router-outlet name="footer"></router-outlet>

The app-help component has said floating button,
<button mat-fab (click)="openHelpCenter()">
  <mat-icon>help</mat-icon>
</button>

that opens a Material dialog with a named router-outlet inside:
@Component({
  selector: 'app-help',
  templateUrl: './help.component.html',
  styleUrls: ['./help.component.scss']
})
export class HelpComponent {

  constructor(
    private dialog: MatDialog,
  ) {
  }

  openHelpCenter() {
    this.dialog.open(HelpDialogComponent, {
      width: '300px'
    })
  }
}

@Component({
  selector: 'app-help-dialog',
  template: '<router-outlet name="help"></router-outlet>'
})
export class HelpDialogComponent {

  constructor() {
  }
}

Inside each module the teams may now implement routes that use the named router-outlet:
...
{
        path: '',
        component: HelpComponent,
        outlet: 'help'
}
...

which "injects" the modules HelpComponent inside the Dialog according to the currently loaded url.
This works fairly well, however, we have an open problem:
How to we hide the floating button if the router-outlet is empty, i.e. if you are on a page that does not provide help?
I believe the easiest solution (i.e. the solution that manages stuff with minimal amount of code inside the modules) would be to listen to Router events inside HelpComponent, e.g. NavigationEnd, and then find out whether there is an "active" routing for the "help"-router-outlet and set visibility accordingly. (similar to the RouterLinkActive-Directive)
However, I am not able to find out how to retrieve this information from the Router-Framework.
Of course, I would also appreciate ideas on how to tackle the problem differently.

A: You can have a service hold a boolean, and have modules manually flip the help on or off on init to fit their needs. We do something like this in our app, but also have something subscribed to navigation events that flips based on certain routes.
You could also add in a query param into the routes that is something like showhelp=true or false, and react to that in the main component.
You could also have a whitelist in the main component where you hold the help button and listen to routing events here, and just use the mapping to control the ngif on it.
Lots of options, not sure what is the best one, I'm curious what route you end up taking though

A: After reading through the Angular Router source, I stumbled upon ChildrenOutletContexts which seems to be a map of the currently "active" outlets.
I adjusted my Component to get it injected and check it every time a navigation completes:
import {
  ChildrenOutletContexts,
  NavigationEnd,
  Router
} from "@angular/router";
import {filter} from "rxjs";
import {map} from "rxjs/operators";

@Component({
  selector: 'app-help',
  templateUrl: './help.component.html',
  styleUrls: ['./help.component.scss']
})
export class HelpComponent {
  helpOutletActive$ = this.router.events.pipe(
    filter(event => event instanceof NavigationEnd),
    map(() => this.contexts.getContext('help') !== null)
  )

  constructor(
    private dialog: MatDialog,
    private router: Router,
    private contexts: ChildrenOutletContexts
  ) {
  }

  openHelpCenter() {
    this.dialog.open(HelpDialogComponent, {
      width: '300px'
    })
  }
}

According to my tests this seems to produce the desired result

A: There is another solution by using RouterLinkActive directive

   ... show/hide content on a specific route ...

style.scss
.d-none {
  display: none
}

Another way is to use template variable

    ... show/hide content on a specific route ...


text:
Q: Запрос на поиск по ключевому слову из двух таблиц Всем привет. Есть рабочий запрос:
SELECT * FROM `realty_kvartiru`
WHERE (dopolnitelnaya_infa LIKE 'Ленина'
       OR ulitsa LIKE 'Ленина'
       OR orientir LIKE 'Ленина')

который ищет по ключевому слову в одной таблице realty_kvartiru по трем столбцам, как можно его модернизировать, чтоб он искал еще по четвертому полю agenstvo_title из второй таблицы phones?
таблицы имеют следующую структуру :
realty_kvartiru: id, user_id, tip, tsena, rayon_id, ulitsa, orientir, etaj, etajnost, kolichestvo_komnat, nomer_doma, nomer_kvartiru, sostoyanie_tip, shema_tip, balcon_tip, sanuzel_tip, istochnik_id, material_tip, julaya_plowad, obwaya_plowad, kuhnya_plowad, dopolnitelnaya_infa, fio, nuzno_prodat, is_deleted, created_at, updated_at, is_imported, in_blacklist, in_deleted_list, deleted_at, secretary_id, call_status, commentary, own_type, is_exclusive, link, deleted_by, must_called, wanted_to_remove, notebook_comment, agents_realty
phones: id, phone, is_posrednik, agenstvo_title

A: Если эти 2 таблицы можно связать по id, то можно:
SELECT *
FROM realty_kvartiru r LEFT JOIN phones p ON r.id = p.id
WHERE dopolnitelnaya_infa LIKE 'Ленина'
       OR ulitsa LIKE 'Ленина'
       OR orientir LIKE 'Ленина'
       OR agenstvo_title LIKE 'Ленина'

A: Можно использовать оператор UNION
http://www.w3schools.com/sql/sql_union.asp


text:
Q: Integration by parts of $\cos(x)e^{-x}dx$ I do the integral but I end up getting the original $\cos(x)e^{-x}dx$ on both sides and canceling them out resulting in no solution.
Can I get a step by step break down of how to solve?

A: First, set $u = \cos x$ and $dv = e^{-x} dx$, so $du = - \sin x \,dx$ and $v = - e^{-x}$. We get
$$\int \cos (x) e^{-x} \,dx = (\cos (x))(-e^{-x}) - \int (-\sin (x))(-e^{-x})\, dx$$.
Now, set $u = - \sin x$ and $dv = -e^{-x}\,dx$ to get $du = - \cos x\, dx $ and $v = e^{-x}$. This gives us
$$\int \cos (x) e^{-x} \,dx = (\cos(x))(-e^{-x}) - (-\sin(x))(e^{-x}) - \int \cos(x)e^{-x}\, dx.$$
Hence,
$$ \int \cos(x) e^{-x}\, dx = \frac{e^{-x}}{2}(\sin(x) - \cos(x)) + C.$$

A: $$\int\cos xe^{-x}dx=Re\int e^{ix}e^{-x}dx=Re\int e^{x(i-1)}dx$$

A: Using $e^{-x}=dv$ and $cos(x)=u$: $$-e^{-x}cos(x)-\int e^{-x}sin(x)$$ $$\int e^{-x}sin(x)=-e^{-x}sin(x)-\int -e^{-x}cos(x)$$ Be careful with the signs, and you will get an expression like this: $$2\int e^{-x}cos(x)=-e^{-x}cos(x)+e^{-x}sin(x)$$
Divide by two, and that is your solution.

A: Letting $u = e^{-x}$ and $dv = \cos x \, dx$ so that $du = -e^{-x} \, dx$ and $v = \sin x$, we obtain:
\begin{align*}
\int e^{-x}\cos x  \, dx
&= (e^{-x})(\sin x) - \int (\sin x)(-e^{-x} \, dx) \\
&= e^{-x}\sin x + \int e^{-x}\sin x \, dx
\end{align*}
Letting $u = e^{-x}$ and $dv = \sin x \, dx$ so that $du = -e^{-x} \, dx$ and $v = -\cos x$, we obtain:
\begin{align*}
\int e^{-x}\cos x  \, dx
&= e^{-x}\sin x + (e^{-x})(-\cos x) - \int(-\cos x)(-e^{-x} \, dx)\\
&= e^{-x}(\sin x -\cos x) - \int e^{-x}\cos x  \, dx
\end{align*}
which contains the original integral! Collecting like terms and dividing by $2$, we conclude that:
$$
\int e^{-x}\cos x  \, dx = \frac{1}{2}e^{-x}(\sin x -\cos x) + C
$$


text:
Q: Trying to output a list using class I am trying to get the moving average of a price, but I keep getting an attribute error in my Moving_Average class:
'Moving_Average' object has no attribute 'days'

Here is what I have:
class Moving_Average:

    def calculation(self, alist:list,days:int):
        m = self.days
        prices = alist[1::2]
        average = [0]* len(prices)
        signal = ['']* len(prices)
        for m in range(0,len(prices)-days+1):
            average[m+2] = sum(prices[m:m+days])/days
            if prices[m+2] < average[m+2]:
                signal[m+2]='SELL'
            elif prices[m+2] > average[m+2] and prices[m+1] < average[m+1]:
                signal[m+2]='BUY'
            else:
                signal[m+2] =''
        return average,signal

def print_report(symbol:str,strategy:str):
        print('SYMBOL: ', symbol)
        print('STRATEGY: ', strategy)
        print('Date            Closing        Strategy        Signal')

def user():
    strategy = '''
    Which of the following strategy would you like to use?
    * Simple Moving Average [S]
    * Directional Indicator[D]

    Please enter your choice: '''

    if signal_strategy in 'Ss':
        days = input('Please enter the number of days for the average')
        days = int(days)
        strategy = 'Simple Moving Average {}-days'.format(str(days))
        m = Moving_Average()
        ma = m.calculation(gg, days)
        print(ma)

gg is an list that contains date and prices.
[2013-10-01,60,2013-10-02,60]

The output is supposed to look like:
 Date       Price      Average      Signal
2013-10-01   60.0
2013-10-02   60.0       60.00         BUY

A: You are referencing days which is an argument of the calculation function not an instance variable of the class. You don't need to use self.days to access it just use m = days


text:
Q: Histogram not showing data in grafana I added a prometheus Histogram with name retrieve_stripe_subscription_latency_ms. From what I read, three metrics get generated from this. I am able see data when I enter the below in Grafana as is

*

*retrieve_stripe_subscription_latency_ms_count

*retrieve_stripe_subscription_latency_ms_sum

*retrieve_stripe_subscription_latency_ms_bucket

But when I plot using the below query in Grafana, I don't see any data
histogram_quantile(0.95, sum(rate(retrieve_stripe_subscription_latency_ms_bucket[5m])) by (le))
What could be wrong here?

A: The issue was the the values were all going to the Inf bucket since the library I am using doesn't automatically handle that.


text:
Q: Numpy linspace function stop value I giving start and stop values as parameters to the linspace function
Stop value is normally does not include in the array. Because of this we always write [stop+1] in order to make include the stop value.
But in linspace, if i write
np.linspace(0, 20, 5)

the output is:
[0, 5, 10, 15, 20]

Why linspace function output includes the stop value when arange function does not?

A: from Numpy linspace documnetation
Parameter

endpoint : bool, optional
If True, stop is the last sample. Otherwise, it is not included. Default is True.

as explained nicely here the 2 functions are similar with slightly different approaches -

*

*linspace's goal is to give us a list of values equally spaced between the start point and endpoint, the only required parameter (except for the start/end) is how many items do we want. Therefore the end considers a legitimate item in that list.

*arrange's  goal is to give a list of steps according to the stepsize parameter we gave it. we're handling the steps so I guess the end doesn't concern us
this is my two cents for this issue...


text:
Q: Convert Microsoft Graph Message to .msg Format I am using MS Graph API to get the message but I need to convert it to .msg file and store it on my machine, is there a way to do this?
I need to covert messageToBeSavedAsMSG as .msg format:
            graphClient.users(properties.getUser()).sendMail(
                UserSendMailParameterSet.newBuilder().withMessage(msg).withSaveToSentItems(saveToSentItems).build())
                .buildRequest().post();

        //Start saving .msg format
        MessageCollectionPage messages = graphClient.users(properties.getUser()).messages()
                .buildRequest()
                .get();

        String msgID = messages.getCurrentPage().get(0).id;

        Message messageToBeSavedAsMSG = graphClient.users(properties.getUser()).messages(msgID)
                .buildRequest()
                .get();

A: MS Graph doesn't provide anything for that. The file format is specific to Outlook on Windows only.
The MSG file format is described in full in MSDN. MS Graph (nor EWS) doesn't expose such files in any way. As a possible workaround you can create an MSG file and import EML into it, see How to create ".msg" file without using outlook in mfc? for more information on that.


text:
Q: what is the correct way to be back to first view controller if not using navigation controller?
I have case that I can't use navigation controller, I want to back from YellowVC to blueVC. if using navigation controller I usually use
self.navigationController?.popToRootViewController(animated: true)

but If I don't use navigation controller I find there is two way to back from blueVC to yellowVC.

*

*using unwind segue

*using present modally like the picture below

so what is the best way to back to first view controller? using unwind segue or using present modally segue?

A: Assuming you are presenting all views, better way is to use unwind Segues.

A: I Think it will be easy if you use dismiss view controller.

*

*you just have to pass any uniq value to the second view controller class when the back button of third VC class.(any string or any integer)

*and just check the value with a if condition in the view did load of second VC class then if its matches dismiss the current VC(second VC) thats enough.

3VC class
@IBAction func back_clicked(_ sender: Any) {
dismiss(animated: false, completion: nil)
    2_vcObject.String = "skip2"
    }

2Vc Class
view did load()

 if string == "skip2"
{
dismiss(animated: false, completion: nil)
}


text:
Q: laravel - using if statement correctly My code here is working fine but I need it to be short. I'm using if statement so Select if I will use user_id or Guest_ip.
But I get a long code, any help?
if (Auth::guest()) {

        $Task = Enrollee::with('path.ProgrammingField')->with(['path.pathtags' => function ($q) use ($TagArray)
        {
            $q->with(['Tasks' => function ($q) use ($TagArray)
              {$q->has('tasktags', '=', 2)->orderBy('id', 'ASC') ->whereDoesntHave('tasktags',
                function ($query) use ($TagArray) {
                            $query->whereNotIn('name', $TagArray);
                        }
                    )
               ->with('tasktags');
           }]
        )->orderBy('id', 'ASC');
       }])
        ->where( 'user_id' , '=' , Auth::user()->id )
        ->where('Path_id', $Path->id) ->get();

        $Tasks = $Task[0]->path;
        $Subs = Enrollee::where( 'user_id' , '=' , Auth::user()->id )->where('Path_id', $Path->id)->get();
       $AllSubs = [];
        foreach($Subs as $sub){
            $AllSubs[] = $sub->task_id;
        }
        $AllSubTasks = implode(" ",$AllSubs);
        $SubTasks = explode(",", ($AllSubTasks));
}

       else {

$Task = Enrollee::
with('path.ProgrammingField')

->with(['path.pathtags' => function ($q) use ($TagArray)
{
    $q->with(['Tasks' => function ($q) use ($TagArray)
      {$q->has('tasktags', '=', 2)->orderBy('id', 'ASC')
    ->whereDoesntHave('tasktags',
                function ($query) use ($TagArray) {
                    $query->whereNotIn('name', $TagArray);
                }
            )
       ->with('tasktags');
   }]
)->orderBy('id', 'ASC');
    }])
->where( 'guest_ip' , '=' , '127.0.0.1' )
->where('Path_id', $Path->id) ->get();

$Tasks = $Task[0]->path;
$Subs = Enrollee::where( 'guest_ip' , '=' ,'127.0.0.1') ->where('Path_id', $Path->id)->get();
   $AllSubs = [];
       foreach($Subs as $sub){
            $AllSubs[] = $sub->task_id;
      }
$AllSubTasks = implode(" ",$AllSubs);
$SubTasks = explode(",", ($AllSubTasks));
}

Can I Use
if (Auth::guest()) {

->where( 'guest_ip' , '=' , '127.0.0.1' )
}

I need to be one code and change if I use guest_ip or user id  Using if statement

A: Hope this will help you.
$ObjTask = Enrollee::with('path.ProgrammingField')
        ->with(['path.pathtags' => function ($q) use ($TagArray) {
                $q->with(['Tasks' => function ($q) use ($TagArray) {
                        $q->has('tasktags', '=', 2)->orderBy('id', 'ASC')
                        ->whereDoesntHave('tasktags', function ($query) use ($TagArray) {
                                    $query->whereNotIn('name', $TagArray);
                                }
                        )
                        ->with('tasktags');
                    }]
                )->orderBy('id', 'ASC');
            }])
        ->where('Path_id', $Path->id);
$Subs = null;
if (Auth::guest()) {
    $Task  = $ObjTask->where('user_id', '=', Auth::user()->id)->get();
    $Subs  = Enrollee::where('user_id', '=', Auth::user()->id)->where('Path_id', $Path->id)->get();
}
else {
    $Task  = $ObjTask->where('guest_ip', '=', '127.0.0.1')->get();
    $Subs  = Enrollee::where('guest_ip', '=', '127.0.0.1')->where('Path_id', $Path->id)->get();
}
$Tasks = $Task[0]->path ?? null;
$AllSubs     = [];
$AllSubTasks = $SubTasks    = null;
if (!empty($Subs)) {
    foreach ($Subs as $sub) {
        $AllSubs[] = $sub->task_id;
    }
    $AllSubTasks = implode(" ", $AllSubs);
    $SubTasks    = explode(",", ($AllSubTasks));
}

A: After properly indenting the code (like @castis correctly advised) , you can start extracting the bits within the statements into methods. That's called refactoring.
From wikipedia:

Code refactoring is the process of restructuring existing computer code—changing the factoring—without changing its external behavior.

It will look something like this:
if(true) {
    doWhateverNeedsToBeDone();
} else {
    doTheOtherThing();
}

And you copy all code and paste into the body of these new methods.


text:
Q: write a program that prompts the user to input five decimal numbers This is the question.
write a program that prompts the user to input five decimal numbers. the program should then add the five decimal numbers, convert the sum to the nearest integer,m and print the result.
This is what I've gotten so far:
// p111n9.cpp : Defines the entry point for the console application.
//

#include <iostream>
using namespace std;

double a, b , c , d , e, f;

int main(int argc, char* argv[])
{
 cout << "enter 5 decimals: " << endl;
 cin >> a >> b >> c >> d >> e;
 f = a + b + c + d + e;
 return 0;
}

Now I just need to convert the sum(f) to the nearest integer, m and print the result. How do I do this?

A:
"declare m" means say

int m;

if you say
m = (int)f; // it means the int value of f is assigned to m.

The casting is actually not even necessary here:
m=f; //works just as well

now you can print m
cout<<m;

A: You need to

*

*Declare m. A declaration looks like this:
double a, b , c , d , e, f;

*Call a rounding function or change the default rounding that occurs when you use =.

*

*Assigning a double value to an int variable rounds down by default. You can change the default with fesetround( FE_TONEAREST ); from #include <fenv.h>.

*Alternately you can call the function round from #include <cmath>.

*Neither of these functions are currently strictly standard C++; they are standard C and are scheduled to become standard C++.

*Add a statement to print m, using cout and <<.

A: This is the answer:
// p111n9.cpp : Defines the entry point for the console application.
//

#include <iostream>
using namespace std;

double a, b , c , d , e, f;

int main(int argc, char* argv[])
{
 cout << "enter 5 decimals: " << endl;
 cin >> a >> b >> c >> d >> e;
 f = a + b + c + d + e;
 cout << static_cast<int> (f + .5)<< endl;
 return 0;
}

By type casting from double to integer the decimal is being truncated AFTER the .5 is added. This means if you have a number like 13.4 and you add .5 to it and then truncate the decimal it will round down. If you have 13.6 and add .5 and then truncate the decimal it will be 14. That is how you round up and down with type casting.


text:
Q: What does LIBXML_NOENT do (and why isn't it called LIBXML_ENT)? In PHP, one can pass optional arguments to various XML parsers, one of them being LIBXML_NOENT. The documentation has this to say about it:

LIBXML_NOENT (integer)
     Substitute entities

Substitute entities isn't very informative (what entities? when are they substituted?). But I think it's fair to assume that NOENT is short for NO_ENTITIES or NO_EXTERNAL_ENTITIES, so to me it seems to be a fair assumption that this flag disables the parsing of (external) entities.
But that is indeed not the case:
$xml = '<!DOCTYPE root [<!ENTITY c PUBLIC "bar" "/etc/passwd">]>
<test>&c;</test>';
$dom = new DOMDocument();
$dom->loadXML($xml, LIBXML_NOENT);
echo $dom->textContent;

The result is that the content of /etc/passwd is echoed. Without the LIBXML_NOENT argument this is not the case.
For non-external entities, the flag doesn't seem to have any effect. Example:
$xml = '<!DOCTYPE root [<!ENTITY c "TEST">]>
<test>&c;</test>';
$dom = new DOMDocument();
$dom->loadXML($xml);
echo $dom->textContent;

The result of this code is "TEST", with and without LIBXML_NOENT.
The flag doesn't seem to have any effect on pre-defined entities such as <.
So my questions are:

*

*What exactly does the LIBXML_NOENT flag do?

*Why is it called LIBXML_NOENT? What is it short for, and wouldn't LIBXML_ENT or LIBXML_PARSE_EXTERNAL_ENTITIES be a better fit?

*Is there a flag that actually prevents the parsing of all entities?

A: Q: What exactly does the LIBXML_NOENT flag do?
The flag enables the substitution of XML character entity references, external or not.
Q: Why is it called LIBXML_NOENT? What is it short for, and wouldn't LIBXML_ENT or LIBXML_PARSE_EXTERNAL_ENTITIES be a better fit?
The name is indeed misleading. I think that NOENT simply means that the node tree of the parsed document won't contain any entity nodes, so the parser will substitute entities. Without NOENT, the parser creates DOMEntityReference nodes for entity references.
Q: Is there a flag that actually prevents the parsing of all entities?
LIBXML_NOENT enables the substitution of all entity references. If you don't want entities to be expanded, simply omit the flag. For example
$xml = '<!DOCTYPE test [<!ENTITY c "TEST">]>
<test>&c;</test>';
$dom = new DOMDocument();
$dom->loadXML($xml);
echo $dom->saveXML();

prints
<?xml version="1.0"?>
<!DOCTYPE test [
<!ENTITY c "TEST">
]>
<test>&c;</test>

It seems that textContent replaces entities on its own which might be a peculiarity of the PHP bindings. Without LIBXML_NOENT, it leads to different behavior for internal and external entities because the latter won't be loaded.


text:
Q: AWS cloudformatiom template is this possible to List of unused and empty s3 buckets in Excel sheet using CloudFormation template
list unused and empty s3 buckets  in excel sheet using Cloudformation template
template will create a lambda function which will list unused and empty s3 buckets and print that list in a excel form

A: Yes, its possible. You can program any logic you want with custom resource in CloudForamtion.


text:
Q: Convolutional networks vs small signal features I'm trying to use convolutional network to extract some specific time series features. The signal contains some slowly changing component of high amplitude and small amplitude signal features (two magnitudes smaller) that I want my network to learn. In my case a sequence of [1,2,1] and [101,102,101] is the same feature class. However in case convolutional layer the second sequence would probably rather fit to some flat filter. (Or maybe my guess is wrong)
Are there any means to remove constant component, or slowly changing component from the signal, or should I just preprocess the data before I feed it in the network?

A: Networks models the rate of change. The rate of change in both of them is the same, it will learn itself. Just feed it the data. If it is time series data, try LSTM + Conv layers.


text:
Q: how to show progress bar in html with different colors I want that progress bar should have three different let say from o t0 40 is blue 40 to 80 is red and from 80 to 100 is green.I have searched a lot but i am getting only simple bar moving.
is there any way to do this.
I am using following code which i got but it also does not move.
  <!doctype html>

  <meta charset="utf-8" />
  <title>jQuery UI Progressbar - Default functionality</title>
  <link rel="stylesheet"  href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />

  <link rel="stylesheet" href="/resources/demos/style.css" />

A: I don't know how it's in Jquery UI but you can simply use CSS and make 2 layers one will be mask and the other is image where 40% of it's width will be blue, ten 40-80 red and 80 - 100 green then you need to uncover it.
On JQuery you need to hide this mask and it'll show you the layer below.
I googled and I found topic where is answer to your question
jQuery UI: How to change the color of a ProgressBar?
check it.

A: Try to apply this Css code to your #progressbar
#progressbar{
width:300px;height:14px;
 background-color:#00aeff;
 filter:progid:DXImageTransform.Microsoft.gradient(GradientType=1,startColorstr=#00aeff, endColorstr=#ff0000);
 background-image:-moz-linear-gradient(left, #00aeff 40%, #ff0000 80%,#2fff00 100%);
background-image:linear-gradient(left, #00aeff 40%, #ff0000 80%,#2fff00 100%);
background-image:-webkit-linear-gradient(left, #00aeff 40%, #ff0000 80%,#2fff00 100%);
background-image:-o-linear-gradient(left, #00aeff 40%, #ff0000 80%,#2fff00 100%);
background-image:-ms-linear-gradient(left, #00aeff 40%, #ff0000 80%,#2fff00 100%);
 background-image:-webkit-gradient(linear, left bottom, right bottom, color-stop(40%,#00aeff), color-stop(80%,#ff0000),color-stop(100%,#2fff00));}

A: sounds like you want to hook in theo the Change event and check where the progress is and then recolor the bar from that. looking at The API it looks douable

A: Two different approaches that come to mind (if you don't want to use the CSS3 gradients mentioned by chermanarun:

*

*Background image: if you know how wide your progress bar is going to be, simply create a background graphic that has three colours set at the points you specify. Apply this background to the progress indicator.

*Layered bars: this requires you to 'limit' the growth of the first two bars to the upper range of progress (so bar 1 can't get wider than 40%, bar 2 can't get wider than 80%). Use CSS positioning and z-indexing so that all thee bars have the same left/top position, and stack them (bar 1 on top, bar 2 in the middle, bar 3 on the bottom). As the bars grow with the loading progress, the first two will stop at their upper limit allowing the ones underneath to keep going, giving the illusion of seamless progress.


text:
Q: "char*" with an unusual memory word size (Knuth's MIX architecture) The original MIX architecture features 6-bit bytes and memory is addressed as 31-bit words (5 bytes and a sign bit). As a thought exercise I'm wondering how the C language can function in this environment, given:

*

*char has at least 8 bits (annex E of C99 spec)

*C99 spec section 6.3.2.3 ("Pointers") paragraph 8 says "When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object." My interpretation of this requirement is that it underpins "memcpy(&dst_obj, &src_obj, sizeof(src_obj))".

Approaches that I can think of:

*

*Make char 31 bits, so indirection through "char*" is simple memory access. But this makes strings wasteful (and means it isn't POSIX-compliant as that apparently requires 8 bit chars)

*Pack three 8 bit chars into one word, with 7 ignored bits: "char*" might be composed of word address and char index within it. However this seems to violate 6.3.2.3, i.e. memcpy() would necessarily skip the ignored bits (which are probably meaningful for the real object type)

*Fully pack chars into words, e.g. the fourth 8 bit char would have 7 bits in word 0 and one bit in word 1. However this seems to require that all objects are sized in 8 bit chars, e.g. a "uint31_t" couldn't be declared to match the word length since this again has the memcpy() problem.

So that seems to leave the first (wasteful) option of using 31-bit chars with all objects sized as multiples of char - am I correct in reading it this way?

A: I agree that C on a MIX architecture could be a pain to implement, and, though not a language lawyer myself, it seems to me that you are right to point out your approach 1. as the only conforming one.
Anyway, the space waste for strings is the least of your problems: you can circumvent it by resorting to a solution older than C itself: making each char representing multiple letters. For the MIX architecture you could for example devise a 7-bit encoding and packing 4 letters into each char:
char hi[4];
hi[0] = 'hell';
hi[1] = 'o, w';
hi[2] = 'orld';
hi[3] = '\0';

printf("%s", hi);

// Whoops, we forgot the exclamation mark
putchar('!\n');

This implementation seems strange, but according to Wikipedia, it was used in the first "Hello world" program ever. I took a look at the Standard and found nothing preventing it, even in C11. Especially § 6.4.4.4 allows encoding literal characters and strings in implementation-specific ways.
EDIT:
This does not help against other difficulties, the main one being your inability to use the wide majority of your machine's possible instructions, since you cannot address single bytes with the native C types. You can however make use of bitfields in this way:
typedef struct _bytes {
    unsigned int sign  : 1;
    unsigned int byte1 : 6; // EDIT: bitfields must be
    unsigned int byte2 : 6; // declared as ints in standard C
    unsigned int byte3 : 6;
    unsigned int byte4 : 6;
    unsigned int byte5 : 6;
} bytes;

typedef union _native_type {
    char as_word;
    int as_int; // int = char; useful for standard library functions, etc.
    bytes as_bytes;
} native_type;

Note that in C++, because of a clause in the strict aliasing rules, you must be careful to always access the char member between an access to int and one to the bytes, since this snippet:
native_type a, b;
a.as_int = 0xC11BABE;
b.as_bytes.byte4 = a.as_bytes.byte4; // Whoops

would yield undefined behavior: see here for details.

A: The most practical approach would probably to make int be 30 bits and have char be either 10 or 15.  Using ten bits for char would allow ASCII text to be packed more tightly, but would increase the cost of indexing into char arrays because of the required divide-by-three.  Storage of Unicode text could be fairly efficient with either 10- or 15-byte char.  With 15-byte char, about 30720 code points would take 15 bits, and the remainder would take 30.  With 10-byte char, 128 code points would take 10 bits, 65408 would take 20, and the remainder would take 30.
To mitigate the cost of dividing by 3, it may be helpful to have each char* contain two words; one would would identify the word containing the character, and the other would identify the offset, in characters, from the start of that word.  Adding a constant offset to a pointer which was known to be normalized could use code like:
p += 5; // Becomes...
if (p.offset) { p.offset=2; p.base+=1; }
else { p.offset--; p.base+=2; }

Not great, but it would avoid any need for a "divide" step.


text:
Q: how detecting if combo selection is selected for first time My question is simple: I have a swt combo and I must do some things if the combo was selected for first time, and do other things if it was selected other times than first. Sorry but I´m newbie and I don´t know how to do that. The listener is in inner class:
combo_agrupacion1.addSelectionListener(new GroupListener());

    class GroupListener extends SelectionAdapter {

        @Override
        public void widgetSelected(SelectionEvent evento) {
}
}

A: You will not find a built-in solution for that. The best you can do is:
First create a variable, something like:
private boolean wasSelectedAlready = false;

Then in your widgetSelected() function start with an if:
if (!wasSelectedAlready) {
   wasSelectedAlready = true; //your function will not execute it
                              //is main body ever again
   do anything else you ever wanted to do in this function
}


text:
Q: How to bring selected list item position in centre of listview in android How to bring selected list item position in centre of lisview in android
I need to use this method
public void smoothScrollByOffset (int offset)
How to find offset?

A: I think what you actually want is:
smoothScrollToPositionFromTop (int position, int offset)
This will scroll the list item you indicate with position so that it is offset pixels below the top edge of the ListView.
To make it scroll to the center you could do something like:
int listViewHeight = myListView.getMeasuredHeight();
myListView.smoothScrollToPositionFromTop(myItemPosition, (listViewHeight / 2));

This will put the top edge of your chosen item half way down the ListView.
If you wanted to go further, you could also get the measured height of the item's view and subtract half of that from the offset too. This would truly "center" the item at the mid height of the ListView.


text:
Q: what's the difference between ClassLoader().getResourceAsStream("./path") and ClassLoader().getResourceAsStream("path") I have a spring boot project, and packaged to a war.
in my project I need read a file as resource.
and this way is work fine
DemoApplication.class.getClassLoader().getResourceAsStream("META/app.properties")//this way works
but when I add a "./" in front of the path ,it won't work
DemoApplication.class.getClassLoader().getResourceAsStream("./META/app.properties")//this way didn't work
and two ways both work fine if didn't use spring boot ,like just usual way to running in tomcat.
so what the difference?
sorry my English not good enough.


text:
Q: Python pandas with split columns by text I have data something like this and I am not sure how to split and convert into table.
I use pandas to sep by |, but I am not sure how to sep by | and = at the same time in this case.
Data sample is like this by txt:
SPK_VOLUME=|DEVICE_STATUS=|WAKE_UP=|SCS_STATUS=|SCS_CLASS=||MUSIC_URL_STATUS=|MUSIC_LOGIN_STATUS=|MUSIC_STREAMING_CONNECT_STATUS=|MUSIC_STREAMING_STATUS=|PLAYER_PLAYING_TIME=|TTS_STATUS=|TTS_CLASS=|ALARM_STATUS=|ALARM_END_REASON=|FOTA_STATUS=|FOTA_FAIL_REASON=
....

I loaded data with pandas
log_file = pd.read_csv("./log_file.txt",
                       sep = "|")

But, I also wanted to split by "=" and create table by values.
SPK_VOLUME  DEVICE_STATUS   WAKE_UP
5   22221   0
2   42241   2
3   125214  1

Thanks for your help

A: Try passing sep=r'\=\|', this worked for me:
In [189]:

t="""SPK_VOLUME=|DEVICE_STATUS=|WAKE_UP=|SCS_STATUS=|SCS_CLASS=||MUSIC_URL_STATUS=|MUSIC_LOGIN_STATUS=|MUSIC_STREAMING_CONNECT_STATUS=|MUSIC_STREAMING_STATUS=|PLAYER_PLAYING_TIME=|TTS_STATUS=|TTS_CLASS=|ALARM_STATUS=|ALARM_END_REASON=|FOTA_STATUS=|FOTA_FAIL_REASON="""
df = pd.read_csv(io.StringIO(t), sep=r'\=\|')
df.columns.tolist()

Out[189]:
['SPK_VOLUME',
 'DEVICE_STATUS',
 'WAKE_UP',
 'SCS_STATUS',
 'SCS_CLASS',
 '|MUSIC_URL_STATUS',
 'MUSIC_LOGIN_STATUS',
 'MUSIC_STREAMING_CONNECT_STATUS',
 'MUSIC_STREAMING_STATUS',
 'PLAYER_PLAYING_TIME',
 'TTS_STATUS',
 'TTS_CLASS',
 'ALARM_STATUS',
 'ALARM_END_REASON',
 'FOTA_STATUS',
 'FOTA_FAIL_REASON=']

Alternatively you can just call .str.rstrip on the .columns attribute as a post-processing step:
In [192]:
df.columns = df.columns.str.rstrip('=')
df.columns.tolist()

Out[192]:
['SPK_VOLUME',
 'DEVICE_STATUS',
 'WAKE_UP',
 'SCS_STATUS',
 'SCS_CLASS',
 'Unnamed: 5',
 'MUSIC_URL_STATUS',
 'MUSIC_LOGIN_STATUS',
 'MUSIC_STREAMING_CONNECT_STATUS',
 'MUSIC_STREAMING_STATUS',
 'PLAYER_PLAYING_TIME',
 'TTS_STATUS',
 'TTS_CLASS',
 'ALARM_STATUS',
 'ALARM_END_REASON',
 'FOTA_STATUS',
 'FOTA_FAIL_REASON']


text:
Q: Updating parallel array when one array is sorted which has repeated element I have two array. Array1=[5,4,3,3,2]. Array2=[2,7,1,2,5].
I want to use these two arrays parallely. Like when elements of Array2 changes order then Array1 elements changes order accordingly. So for my program I sorted Array2 and it becomes Array2=[1,2,2,5,7]. So Array1 must be changed to Array1=[3,3,5,2,4].
I want to know how to do this(psudocode or java or c++). I have provided the code I tried in C++ below. The problem is it does not work when an element duplicates. So after it sorts Array2 to [1,2,2,5,7] it updates Array1 to [3,5,5,2,4] ( you should understand why it is giving this output by looking at the code below).
So my task is when Array2 is updated(elemnts changes order) so should Array1. It has to work when Array2 has duplicate elements.
  k=0;
  for(int i=0;i<n;i++)
    {
    int a=arr1[i];
    for(int j=0;j<n;j++)
    {
        if(a==arr2[j])
        {
            arr4[k]=arr1[j];
            k++;
            break;
        }
    }
}

A: If the arrays must be parallel, the better way to sort them is to have a third array of indices, and sort those integers based on Array2.  Note this is C++ code, not Java:
#include <algorithm>
#include <array>
#include <iostream>

int main()
{
   std::array<int, 5> Array1 = {{5,4,3,3,2}};
   std::array<int, 5> Array2 = {{2,7,1,2,5}};
   std::array<int, 5> indices = {{0,1,2,3,4}};

   // only sort the indices, based on Array2
   std::sort(indices.begin(), indices.end(), [&](int n1, int n2)
              { return Array2[n1] < Array2[n2]; });

   // output results
   for (auto& i : indices)
      std::cout << Array1[i] << " ";
   std::cout << "\n";
   for (auto& i : indices)
      std::cout << Array2[i] << " ";
}

Output:
3 5 3 2 4
1 2 2 5 7

The output function could have also been written this way:
   // output results
   for (int i = 0; i < 5; ++i)
      std::cout << Array1[indices[i]] << " ";
   std::cout << "\n";
   for (int i = 0; i < 5; ++i)
      std::cout << Array2[indices[i]] << " ";

A: I am suggesting a different solution, please discard if you don't want to use. Design a class with two fields, one for the number from array1 and one for the number from array 2. Instead of the two int arrays, make one array of objects from this class. Now no matter how the array is reordered, the numbers from each of the original arrays will always follow each other. Also, it's easy to sort by either the first or the second number as necessary.
I didn't expect to write the code for you, but on your request here are some useful snippets in Java to get you started. The class is quite simple, two fields, constructor and getters:
public class ParallelNumbers {

    /** number from array 1 */
    int elem1;
    /** number from array 2 */
    int elem2;

    public ParallelNumbers(int elem1, int elem2) {
        this.elem1 = elem1;
        this.elem2 = elem2;
    }

    public int getElem1() {
        return elem1;
    }

    public int getElem2() {
        return elem2;
    }
}

You may of course add toString method and what else you may like. Since you know your domain better, you can also find a better name for the class. With this class you may do:
    ParallelNumbers[] all = new ParallelNumbers[] { new ParallelNumbers(5, 2), new ParallelNumbers(4, 7),
                    new ParallelNumbers(3, 1), new ParallelNumbers(3, 2), new ParallelNumbers(2, 5) };
    System.out.println("Numbers from array 1: "
            + Arrays.stream(all).map(ParallelNumbers::getElem1).collect(Collectors.toList()));
    System.out.println("Numbers from array 2: "
            + Arrays.stream(all).map(ParallelNumbers::getElem2).collect(Collectors.toList()));

You will recognize your original arrays in the printout:
Numbers from array 1: [5, 4, 3, 3, 2]
Numbers from array 2: [2, 7, 1, 2, 5]

As an example of sorting, here's how to sort the ParallelNumbers elements first by elem2, next by elem1 (to resolve clashes):
    Arrays.sort(all,
            Comparator.comparingInt(ParallelNumbers::getElem2).thenComparingInt(ParallelNumbers::getElem1));
    System.out.println("Numbers from array 1: "
            + Arrays.stream(all).map(ParallelNumbers::getElem1).collect(Collectors.toList()));
    System.out.println("Numbers from array 2: "
            + Arrays.stream(all).map(ParallelNumbers::getElem2).collect(Collectors.toList()));

This time it prints:
Numbers from array 1: [3, 3, 5, 2, 4]
Numbers from array 2: [1, 2, 2, 5, 7]

Exactly as you had requested, isn't it?
EDIT: Something similar has been written before. See for example Anti-pattern: parallel collections and Parallel array.