text:
Q: Google chrome logs out from every webpage after system user has logged out So I've got a really annoying problem and Google Chrome isn't providing me any information on what's causing it.
Every time I log into my account I have to again, and again, and again log into every webpage I'm using, because Google Chrome logs me out of everything I am logged in to. However, some cookies do persist, as Google remembers which account I have logged in to, and I still have access to my company's gitlab as well - it's the only service I'm not logged out of.
In case this is relevant, after I open Google Chrome there's an alert box next to my Google Chrome profile which says that Change made on my account requires logging in again (yes, it also logs me out from Google Chrome profile).
The problem does not appear when I do not log out from my system account (e.g. when I only close Chrome and open it again).
It does not happen on other browsers, only on Google Chrome.
Thanks in advance to everyone!

Update 1: Some specs/data:
OS: Ubuntu 16.04
Chrome: 53.0.2785.143 (64-bit)
Addons: Reddit Enhancement Suite, Adblock Plus, Ghostery, ColorZilla, Json View
Startup programs: Screencloud + ubuntu default ones
It did log me out even if I wasn't logged into any profile (so there weren't any addons installed as well, so I doubt it's an addon fault)
I also uninstalled Chrome and deleted .cache/google-chrome and .config/google-chrome directories entirely.

Update 2:
I ran Chrome from the terminal using google-chrome --enable-logging -v=1
Following errors did appear in terminal on browser startup:
[13645:13712:1007/142537:ERROR:gcm_store_impl.cc(306)] Failed to open database /home/user/.config/google-chrome/Profile 4/GCM Store: Invalid argument: /home/user/.config/google-chrome/Profile 4/GCM Store: does not exist (create_if_missing is false)
[13645:13712:1007/142537:ERROR:gcm_store_impl.cc(306)] Failed to open database /home/user/.config/google-chrome/Profile 4/GCM Store: Invalid argument: /home/user/.config/google-chrome/Profile 4/GCM Store: does not exist (create_if_missing is false)

However, the folder /home/user/.config/google-chrome/Profile 4/GCM Store does exist.
This error does not appear when starting chrome as root with:
sudo google-chrome --user-data-dir=/root/chrome-data --enable-logging -v=1

Update 3
So I closed Chrome, deleted /home/user/.config/google-chrome/Profile 4 directory and once again configured my account. I logged out, and then the following errors appeared:
[21285:21353:1007/145425:ERROR:gcm_store_impl.cc(922)] Failed to restore security token.
[21285:21285:1007/145425:ERROR:account_tracker.cc(357)] OnGetTokenFailure:  Not authorized.

Update 4:
I managed to fix (or at least I think so) the problems with Google Chrome errors and it does not log me out from Chrome Profile. I did this by moving the whole /root/chrome-data (created earlier) directory to ~/.config/google-chrome and changing it's owner. However, the browser still does not keep cookies after user logout.

A: I too would ask you to start over, by uninstalling and killing all chromium processes.
An operational note, you really shouldn't be logging in as the system account. You log in as yourself, and if you need to do system things, become root temporarily.
Also, logging out will kill any processes started by you which haven't been placed in the background.
For install:
sudo /bin/bash
exec su - root
pgrep -l chromium    # ensure list is empty, otherwise kill those processes
                     # pkill chromium
apt install chromium-browser
exit
id   # confirm you are now yourself and not root
# start chrome with specific directory
chromium-browser --user-data=~/.config/chromium >/dev/null 2>&1 &
# you could make this an alias in your .bashrc:
# alias chrome='chromium-browser --user-data=~/.config/chromium >/dev/null 2>&1 &'

You could add  nohup to keep it running after logout, but re-attaching to it after logging in is problematic.
Once chrome is started, edit settings:
Choose Continue where you left off
Choose Offer to save your web passwords (in advanced settings)

A: Even if you resolve the issue at hand with your Chrome Browser installation; it won't necessarily help you in the event of a system/browser crash...
I do alot of testing work on my dev & sys admin machines, so perhaps I crash my browser & system more than most; which was really frustrating when researching topics and all of a sudden you lose all of your tabs...
My solution was to install, TabsOutliner:
https://chrome.google.com/webstore/detail/tabs-outliner/eggkanocgddhmamlbiijnphhppkpkmkl
... in the event of a crash, it will allow you to really easily reopen them one at a time, or in groups.

A: If you have automatic login to Ubuntu, i.e. you don't need to type password on login screen when you start your computer, it might cause the problem because Chrome doesn't have rights to read/write to your profile folder. I solved the issue by disabling automatic login to Ubuntu.

*

*System Settings -> Security&Privacy

*Choose Security tab and Password settings

*Unlock and turn off automatic login


text:
Q: Check if a file exists in UNIX from SQLplus without UTL_FILE My current scenario is like this:

*

*I need to login to sqlplus from a shell script to call a stored procedure.

*After that I need to create a CSV file by SPOOLING data from a table.

*Then I need to check whether the CSV file has been created in a particular directory and depending on the result an update query needs to be run.

I know that this can be checked within sqlplus with the help of UTL_FILE package but unfortunately due to Client policies,the access of this package is restricted in  the current system.
Another way is to exit from sqlplus and perform the file check in UNIX and then again log in to sqlplus to perform the rest actions. But this I believe would result in slower execution time and performance is an important factor in this implementation as the tables contain huge volumes of data(in millions).
So is there any other way to check this from sqlplus without exiting from the current session?
System Info:
OS - Red Hat Enterprise Linux
Database - Oracle 11g

A: If the file is on the same machine that you're running SQL*Plus on, you could potentially use the host command.
If the file you're checking is the same one you're spooling to, it must exist anyway, or you would have got an SP error of some kind; but if you do want to check the same file for some reason, and assuming you have a substitution variable with the file name:
define csv_file=/path/to/spool.csv
-- call procedure
spool &csv_file
-- do query
spool off

host ls &csv_file

update your_table
set foo=bar
where &_rc = 0;

If the file exists when the host command is run, the _rc substitution variable will be set to zero. If the file doesn't exist or isn't readable for any reason it will be something else - e.g. 2 if the file just doesn't exist. Adding the check &_rc = 0 to your update will mean no rows are updated if there was an error. (You can of course still have whatever other conditions you need for the update).
You could suppress the display of the file name by adding 1>/dev/null to the host command string; and could also suppress any error messages by also adding 2>/dev/null, though you might want to see those.
The documentation warns against using &_rc as it isn't portable; but it works on RHEL so as long as you don't need your script to be portable to other operating systems this may be good enough for you. What you can't do, though, is do anything with the contents of the file, or interpret anything about it. All you have available is the return code from the command you run. If you need anything more sophisticated you could call a script that generates specific return codes, but that's getting a bit messy.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Excel find rows between two strings and change value in different column for rows between strings Not really sure how to go about finding the rows of data between the string [801 C] in [Column B] and the string [Nr] in [Column A] then change the value in [Column C] for the rows between from [3] to [27]. I have to reference the data on this sheet on another sheet to be able to graph the data for the L* a* b* for each color standard and the way the standards are stored on the spectrometer there is overlap for the standard ID number between the 700 and 800 color numbers so i have to figure out how to change the value of the standard ID number for the 800 series colors so the graphs only include that data. The standard Id number is the only thing available on each line in the log that ties each line(row) of data to each color. Also need to be able to find multiple instances were both strings may appear in the same sheet multiple times . Any help, ideas and advice will be greatly appreciated.

I did manage with help from here at stackoveverflow to get a batch script to extract the data but can't get it to find but the first instance of both strings and is less than an ideal solution. A macro would be ideal but I am very new to vb scripting and this is beyond my scope of knowledge. Again thank you to anyone who replies to this you are a saint.

A: Didn't test this so there might be typos but you should be able to get it working:
Dim valCell As Range 'store the cell where you find "801 C"
Dim i As Long, first As Long, last As Long 'counter, store rows as you iterate

first = 1 'start at the top
Set valCell = Sheet1.Columns(2).Find("801 C", Sheet1.Cells(first, 2)) 'get the first time you have "801 C", if there are none then this will be Nothing and the While loop condition will fail right away

While (Not valCell Is Nothing)

    first = valCells.Row 'set the first row to the row you found "801 C"
    last = Sheet1.Columns(1).Find("Nr", Sheet1.Cells(first, 1)).Row 'set the last row to the row you found "Nr"

    For i = first To last 'loop through the cells and change the values
        Sheet1.Cells(i, 3).Value = 27
    Next

Wend

Don't forget to change the worksheet reference from Sheet1 to the .CodeName for the sheet you are using; that is the name that appears before the parentheses in the editor.

A: Dim valCell As Range 'store the cell where you find "801 C"
Dim i As Long, first As Long, last As Long 'counter, store rows as you iterate

first = 1 'start at the top
Set valCell = Worksheets("export1").Columns(2).Find("801 C", Worksheets("export1").Cells(first, 2)) 'get the first time you have "801 C", if there are none then this will be Nothing and the While loop condition will fail right away
While (Not valCell Is Nothing)
    If valCell.Row > first Then
        first = valCell.Row 'set the first row to the row you found "801 C"
        last = Worksheets("export1").Columns(1).Find("Nr", Worksheets("export1").Cells(first, 1)).Row 'set the last row to the row you found "Nr"

        For i = first To last 'loop through the cells and change the values
            Worksheets("export1").Cells(i, 3).Value = 27
        Next
        first = last
        Set valCell = Worksheets("export1").Columns(2).Find("801 C", Worksheets("export1").Cells(first, 2)) 'get the next time you have "801 C", if there are none then this will be Nothing and the While loop condition will fail right away8
    Else
        Set valCell = Nothing
    End If
Wend
End Sub

There got it all sorted "should" find every instance of "801 C" & "Nr" going to leave this here in case it helps someone else out.


text:
Q: Efficient thread use on high traffic ASP.NET Core Web API with processing timeout My ASP.NET Core Web API (Linux) endpoint needs to serve a high volume of concurrent requests. If the request takes more than 200ms then it should abort and return a custom piece of JSON. The code is all awaitable. The request must always return HTTP 200 and the HTTP request timeout cannot be reduced from 30 secs to 200ms.
What is the most efficient way to accomplish what I want? Should I use a Task? Should I use Task.Wait or Task.WaitAsync? Or should the work methods run in the HTTP request thread, periodically check Stopwatch.Elapsed and throw a timeout exception?
This is my current code:
var task = Task.Factory.StartNew(async () =>
{
    // Processing part 1
    var result1 = await DoWorkPart1("Param1");

    if (cancellationToken.IsCancellationRequested())
        cancellationToken.ThrowIfCancellationRequested();

    // Processing part 2
    var result2 = wait DoWorkPart2(result1);

    return result2;
}).Unwrap();    // Return lambda task, not outer task

// Is it better to use WaitAsync?
task.Wait(TimeSpan.FromMilliseconds(150));

if (task.IsCompleted)   // Result within timeout
{
    if (task.Exception == null) // Success
    {
        return Ok(task.Result);
    }
    else
    {
        return Ok(new FailedObject() { Reason = ReasonEnum.UnexpectedError };
    }
}
else   // Timeout
{
    return OK(new FailedObject() { Reason = ReasonEnum.TookTooLong };
}

A:
What is the most efficient way to accomplish what I want?

I recommend using CancellationTokens to cancel. With a very short timeout like 200ms, you might just want to create a CancellationTokenSource with that timeout and ignore the CancellationToken provided to you by ASP.NET, which handles situations like clients disconnecting early.

Should I use a Task? Should I use Task.Wait or Task.WaitAsync? Or should the work methods run in the HTTP request thread, periodically check Stopwatch.Elapsed and throw a timeout exception?

I would say none of these. Instead, pass the CancellationToken down as far as you possibly can, ideally right to the lowest-level APIs your asynchronous code is calling.
If some of those APIs ignore their cancellation tokens, or if it's possible they may complete synchronously (e.g., due to caching), then adding cancellationToken.ThrowIfCancellationRequested(); in-between steps is a good idea.
Side note: Don't use StartNew.
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
try
{
  // Processing part 1
  var result1 = await DoWorkPart1("Param1", cts.Token);

  cts.Token.ThrowIfCancellationRequested();

  // Processing part 2
  var result2 = wait DoWorkPart2(result1, cts.Token);

  return Ok(result2);
}
catch (OperationCanceledException)
{
  return OK(new FailedObject() { Reason = ReasonEnum.TookTooLong };
}
catch
{
  return Ok(new FailedObject() { Reason = ReasonEnum.UnexpectedError };
}


text:
Q: How does this code work? The result doesnt make sense to me and doesnt appear in the debugger     #include <iostream>

using namespace std;

int f(int n, int m){
    if (n==1)
        return 0;
    else
        return f(n-1, m) + m;
}

int main()
{

cout << f(3874, 1000);
cout << endl;
    return 0;
}

The result is 3873000. Why is n multiplied by m after deducting 1 and how does the function work in detail please?

A: The else block is executed at all levels of recursion, except the deepest one.
The number of levels in the recursion tree is n. So we have n-1 times that the else block is executed.
This else block first makes the recursive call, and then adds m to the result it gets back, and returns that sum to the caller, who will do the same, ...etc until the walk upwards the recursion tree is complete.
The original caller will thus see a base number (0) to which m was repeatedly added, exactly n-1 times.
So the function calculates m(n-1), provided that n is greater than 0. If not, the recursion will run into a stack overflow error.
Visualisation
To visualise this, let's split the second return statement into two parts, where first the result of the recursive call is stored in a variable, and then the sum is returned. Also, let's take a small value for n, like 3.
So this is then the code:
int f(int n, int m){
    if (n==1)
        return 0;
    else {
        int result = f(n-1, m)
        return result + m;
    }
}

int main()
{
    cout << f(3, 10);
}

We can imagine each function execution (starting with main) as a box (a frame), in which local variables live their lives. Each recursive call creates a new box, and when return is executed that box vanishes again.
So we can imagine the above code to execute like this:
+-[main]----------------------------+
|  f(3, 10) ...                     |
|  +-[f]-------------------------+  |
|  |  n = 3, m = 10              |  |
|  |  f(3-1, 10) ...             |  |
|  |  +-[f]-------------------+  |  |
|  |  |  n = 2, m = 10        |  |  |
|  |  |  f(2-1, 10) ...       |  |  |
|  |  |  +-[f]-------------+  |  |  |
|  |  |  |  n = 1, m = 10  |  |  |  |
|  |  |  |  return 0       |  |  |  |
|  |  |  +-----------------+  |  |  |
|  |  |  result = 0           |  |  |
|  |  |  return 0 + 10        |  |  |
|  |  +-----------------------+  |  |
|  |  result = 10                |  |
|  |  return 10 + 10             |  |
|  +-----------------------------+  |
|  cout << 20                       |
+-----------------------------------+

I hope this clarifies it.

A: The algorithm solves the recurrence
F(n) = F(n-1) + m

with
F(1) = 0.

(I removed m as an argument, as its value is constant).
We have
F(n) = F(n-1) + m = F(n-2) + 2m = F(n-3) + 3m = ... = F(1) + (n-1)m.

As written elsewhere, the recursion depth is n, which is dangerous.


text:
Q: Как сделать, чтобы mysql смотрел наружу? Как сделать, чтобы mysql (ubuntu linux) смотрел наружу и к нему можно было подключиться внешней программой?

A: найдите конфигурационный файл mysqld, содержащий директиву bind-address:
$ grep -rl bind-address /etc/mysql

скорее всего, она содержит адрес 127.0.0.1:
bind-address = 127.0.0.1

чтобы mysqld слушал не только этот адрес, но и любой адрес на всех сетевых интерфейсах, замените 127.0.0.1 на *, чтобы директива выглядела так:
bind-address = *

и перезапустите mysqld:
$ sudo service mysql restart

A:
В MySQL пользователь характеризуется двумя параметрами: именем и
  хостом, с которого он может обращаться. По умолчанию доступ разрешен
  только с локальной машины, т.е. для пользователя user@localhost.  Права на доступ пользователям даются с помощью команды GRANT.

Подробней: Настройка удаленного подключения к MySQL


text:
Q: Error when calling compiled m-file(.jar) in a multi threaded Java app I have a simple m-file
function [fRate,Height,Width] = media(filename)
obj = mmreader(filename);
fRate = obj.FrameRate;
Width = obj.Width;
Height = obj.Height;
end

Which I have successfully compiled using MATLAB Builder JA into a .jar file.
I have tested the .jar file in a single threaded application and it work with no problem.
The error came when I use it in a multi threaded GUI application. I run the .jar as a thread in one of the class I created and the following error occur.

An unexpected error has been detected
  by Java Runtime Environment:
EXCEPTION_ACCESS_VIOLATION
  (0xc0000005) at pc=0x6d9c08b0,
  pid=5920, tid=4788
Java VM: Java HotSpot(TM) Client VM
  (10.0-b19 mixed mode windows-x86)
  Problematic frame:
C  [jvm.dll+0x1108b0]

After debugging, I found that the error occur when my thread is calling
media = new Media();  (I name my .jar as Media.jar)
This is my Java code:

// mediaProperty.java
public class mediaProperty implements Runnable {
public void mediaProperty() {

    Matlab_options matlab = new Matlab_options();
    Object[] mediaProp = null;
    java.util.List lstMedia = new ArrayList();
    Media media = null;

    try {

        media = new Media();
        ...

        mediaProp = media.media(3, lstMedia);

        ...
    } catch (Exception p) {
        System.out.println("Exception: " + p.toString());
    } finally {
        MWArray.disposeArray(mediaProp);
        if (media != null) {
            media.dispose();
        }
    }
}

public void run() {
    mediaProperty();
}

}

  // GUI.java
private Thread mediap;
if (mediap == null) {
mediap = new Thread(new mediaProperty());
mediap.start();
}

What is wrong? Is it my code?

A: My guess is that MATLAB requires you to access it from exactly one thread. You say it works in a single threaded application, perhaps you need to start a dedicated thread for interacting with MATLAB to get this to work correctly.
See also
Thread safety of Matlab engine API


text:
Q: What is the correct use of the ASP.NET Thread Pool? My scenario is this, I have a file that slowly gets populated over the course of an hour or two (mp3, video, etc). As this file is populated many users are connected to the server to receive new data as it is added to the server.
At the moment each visitor connects to the server, and an IHttpAsyncHandler allocates a thread from the thread pool to handle the request. However using the default thread pool settings, this means that only 20 visitors can connect to a server (single processor) at a time.
Because most of the time these threads are simply waiting for new data, what would be the best way to release the thread to the pool, and have it re-activate when new data is available.
Many Thanks,
Ady

A: I would just use regular Threads for this purpose. The .NET ThreadPool is not really designed to support the releasing and re-activation of (long-running) threads depending on their internal state... at the very least, you would have to do some creative programming to achieve the desired behavior if you stick with a ThreadPool (i.e. break the logic into small asynchronous tasks that get executed by the ThradPool).
If you go with Thread, then you will have direct control to all the active threads so you can accept more visitors at the same time.

A: F# has a feature called Asynchronous Workflows that is ideally suited to this sort of thing. When your code is waiting on an external data source, the thread is returned to the thread pool for other uses. When new data arrives, the workflow gets a thread out of the pool and uses it to resume your code where you left off. In this way you never have to tie up a thread that's doing nothing but waiting on I/O.
It may be overkill to learn a new language just for this one use, but F# towers over every other CLR language when it comes to async I/O, and it's a really fun language, besides.


text:
Q: Replace column values using a dictionary I have this dataframe where gender is expected to be male or female.
from io import StringIO
import pandas as pd

audit_trail = StringIO('''
course_id AcademicYear_to months TotalFee Gender
260 2017 24 100 male
260 2018 12 140 male
274 2016 36 300 mail
274 2017 24 340 female
274 2018 12 200 animal
285 2017 24 300 bird
285 2018 12 200 maela
''')

df11 = pd.read_csv(audit_trail, sep=" "  )

I can correct the spelling mistakes using dictionary.
corrections={'mail':'male', 'mael':'male', 'maae':'male'}
df11.Gender.replace(corrections)

But I am looking for a way to keep only male / female and "other" category for rest of the options. Expected output:
0      male
1      male
2      male
3    female
4    other
5    other
6      male
Name: Gender, dtype: object

A: Add another two dummy entries to your corrections dict:
corrections = {'male'   : 'male',    # dummy entry for male
               'female' : 'female',  # dummy entry for female
               'mail'   : 'male',
               'maela'  : 'male',
               'maae'   : 'male'}

Now, use map and fillna:
df11.Gender = df11.Gender.map(corrections).fillna('other')
df11

   course_id  AcademicYear_to  months  TotalFee  Gender
0        260             2017      24       100    male
1        260             2018      12       140    male
2        274             2016      36       300    male
3        274             2017      24       340  female
4        274             2018      12       200   other
5        285             2017      24       300   other
6        285             2018      12       200    male

A: You can use:
corrections={'mail':'male', 'maela':'male', 'maae':'male', 'male':'male', 'female':'female'}
df11[['Gender']] = df11[['Gender']].applymap(corrections.get).fillna('other')
print (df11)
   course_id  AcademicYear_to  months  TotalFee  Gender
0        260             2017      24       100    male
1        260             2018      12       140    male
2        274             2016      36       300    male
3        274             2017      24       340  female
4        274             2018      12       200   other
5        285             2017      24       300   other
6        285             2018      12       200    male

EDIT:
For replace only one column is better cᴏʟᴅsᴘᴇᴇᴅ's answer. If want replace multiple columns, better is applymap.


text:
Q: jQuery to check empty string var id = "<?php echo $val->id; ?>";

var myRadio = $('input[name=<?php echo "mala".$val->id; ?>]').val();

if (myRadio.val.length > 0){
   $("#anketa").load('http://www.svastara.rs/anketa/anketa_m1_data',
       { answer: myRadio, id: id });
   }
});

Why this  if (myRadio.val.length > 0)  returns it looks like false, when i am sure that there is something in the string. If its not a good way, how to check that the string is empty or not?

A: No need in val, since you should already get the value with val() method in the previous line:
if (myRadio.length > 0) { ... }

A: if(myRadio)
return true;
else
return false;

A: You don't need to use myRadio.val.length due to myRadio is already the value of that input. So all you need is to check this variable with length.
var id = "<?php echo $val->id; ?>";
var myRadio = $('input[name=<?php echo "mala".$val->id; ?>]').val();
if (myRadio.length > 0){
     $("#anketa").load('http://www.svastara.rs/anketa/anketa_m1_data', { answer: myRadio, id: id });
}

You can have a better explanation at http://www.w3schools.com/jsref/jsref_length_string.asp
Good luck!


text:
Q: Generating stored procedures for insert,update and delete automatically How can I generate insert and update stored procedures for specific or all tables automatically in SQL Server ?
Is it possible ? thanks in advance

A: There are tons of tools that can do this for you, some free, some that you pay for. Here is a simple one with source you can adapt:
http://www.codeproject.com/Articles/19280/Stored-Procedure-Generator
and here is an SSMS addin, that is also free (or for a small fee depending on the version you choose).
http://www.ssmstoolspack.com/

A: -- It is for std table
create proc std_delete
@id int
as begin
delete from std  where id=@id
end

execute  std_delete  2
-- SP for delete

--Now u can c
select * from std


text:
Q: Check firebug from page to get results of net panel How can I access the Firebug API from my webpage to get output of the net panel?
My intention is to embed a small script in my webpage to show the time taken for DomContentLoaded

A: The only Firebug API you can access from a web page is the console object.
http://getfirebug.com/wiki/index.php/Console_API
This object is explicitly injected into every web page for logging into the Console panel.
If you want to access information in the Net panel you need to create a Firefox/Firebug extension or use an existing extension such as NetExport that allows to export all data collected by the Net panel: http://www.softwareishard.com/blog/netexport/
There are other options:
1) You can register a listener for "DOMContentLoad" event and measure the time yourself
2) You can use web timing specification http://dev.w3.org/2006/webapi/WebTiming/
This already works in Chrome and implementation for Firefox is in progress, see:
https://bugzilla.mozilla.org/show_bug.cgi?id=570341
Honza


text:
Q: Automatically set value of a managed bean variable with JSF I would like to pass an value to a managed bean under the hood. So I have this managed bean:
@ManagedBean(name = "mbWorkOrderController")
@SessionScoped
public class WorkOrderController {

    // more attributes...

    private WorkOrder workOrderCurrent;

    // more code here...

    public WorkOrder getWorkOrderCurrent() {
        return workOrderCurrent;
    }

    public void setWorkOrderCurrent(WorkOrder workOrderCurrent) {
        this.workOrderCurrent = workOrderCurrent;
    }
}

It holds a parameter workOrderCurrent of the custom type WorkOrder. The class WorkOrder has an attribute applicant of type String.
At the moment I am using a placeholder inside my inputtext to show the user, what he needs to type inside an inputText.
<p:inputText id="applicant"
    value="#{mbWorkOrderController.workOrderCurrent.applicant}"
    required="true" maxlength="6"
    placeholder="#{mbUserController.userLoggedIn.username}" />

What I want to do, is to automatically pass the value of mbUserController.userLoggedIn.username to mbWorkOrderController.workOrderCurrent.applicant and remove the inputText for applicant completely from my form.
I tried to use c:set:
<c:set value="#{mbUserController.userLoggedIn.username}" target="#{mbWorkOrderController}" property="workOrderCurrent.applicant" />

But unfortunatelly I get a javax.servlet.ServletException with the message:
The class 'WorkOrderController' does not have the property 'workOrderCurrent.applicant'.
Does anybody have an advice?

A:
The class 'WorkOrderController' does not have the property 'workOrderCurrent.applicant'.

Your <c:set> syntax is incorrect.

<c:set value="#{mbUserController.userLoggedIn.username}"
       target="#{mbWorkOrderController}"
       property="workOrderCurrent.applicant" />

You seem to be thinking that the part..
value="#{mbWorkOrderController.workOrderCurrent.applicant}"

..works under the covers as below:
WorkOrderCurrent workOrderCurrent = mbWorkOrderController.getWorkOrderCurrent();
workOrderCurrent.setApplicant(applicant);
mbWorkOrderController.setWorkOrderCurrent(workOrderCurrent);

This isn't true. It works under the covers as below:
mbWorkOrderController.getWorkOrderCurrent().setApplicant(applicant);

The correct <c:set> syntax is therefore as below:
<c:set value="#{mbUserController.userLoggedIn.username}"
       target="#{mbWorkOrderController.workOrderCurrent}"
       property="applicant" />

That said, all of this isn't the correct solution to the concrete problem you actually tried to solve. You should perform model prepopulating in the model itself. This can be achieved by using @ManagedProperty to reference another bean property and by using @PostConstruct to perform initialization based on it.
@ManagedBean(name = "mbWorkOrderController")
@SessionScoped
public class WorkOrderController {

    @ManagedProperty("#{mbUserController.userLoggedIn}")
    private User userLoggedIn;

    @PostConstruct
    public void init() {
        workOrderCurrent.setApplicant(userLoggedIn.getUsername());
    }

    // ...
}

A: Perhaps you could explain the context a bit more, but here's another solution. If you're navigating from another page, you can pass some identifier of work WorkOrder in the URL, like this http://host:port/context/page.xhtml?workOrderId=1.
Then, you can set the identifier in the managed bean like this:
<h:html>
    <f:viewParam name="workOrderId" value="#{mbWorkOrderController.id}"/>
</h:html>

You'll have to add a new property to your bean:
public class WorkOrderController {
    private long id;
    public long getId() { return id; }
    public void setId(long id) { this.id = id; }

    // ...
}

And then, after the property has been set by JSF, you can find the work order in a lifecycle event:
<h:html>
    <f:viewParam name="workOrderId" value="#{mbWorkOrderController.id}"/>
    <f:event type="preRenderView" listener="#{mbWorkOrderController.findWorkOrder()}"/>
</h:html>

public class WorkOrderController {
    private long id;
    public long getId() { return id; }
    public void setId(long id) { this.id = id; }

    public void findWorkOrder() {
        this.workOrderCurrent = null /* some way of finding the work order */
    }

    // ...
}

This strategy has the advantage of letting you have bookmarkable URLs.


text:
Q: Update table in MySQL with subquery I would like to update my table with WHERE clause equals to result in my Subquery as you can see in the query below. The result after executing of query should be that the row with name Robert will have value to 1
CREATE TABLE `table1`(
  `name` varchar(30),
  `surname` varchar(30),
  `nextname` varchar(30),
  `value` bit(1)
);

INSERT INTO `table1`
VALUES
  ('Daniel', 'Hanks', 'Robert', 0),
  ('Robert', 'Pitt', 'Angelina', 0),
  ('Angelina', 'Jolie', 'Monica', 0),
  ('Monica', 'Red', null, 0);

UPDATE `table1` SET `value` = 1
WHERE `name` IN (SELECT `nextname` FROM `table1`
WHERE `name` = 'Daniel')¨

Thanks

A: You can't UPDATE and SELECT from the same table in one query. But MySQL does support UPDATE with JOIN syntax:
UPDATE table1 AS t1
INNER JOIN table1 AS t2 ON t1.name = t2.nextname
SET t1.value = 1
WHERE t2.name = 'Daniel'

A: You can also do it with an ugly trick:
UPDATE `table1` SET `value` = 1
WHERE `name` IN (SELECT `nextname` FROM(SELECT `nextname` FROM `table1`
WHERE `name` = 'Daniel')x)

A: Your syntax for using a subquery in the WHERE clause is correct. However what are you trying to do exactly? You can achieve the same result without the subquery.
UPDATE `table1` SET `value` = 1 WHERE `name` = 'Daniel'


text:
Q: compiler is printing Strange value in c# I am using methods in c#. i returned something but compiler is not printing which i am expecting. It is printing (system.string[]). i dont know why Please help on this.
class Program
{
    static void Main(string[] args)
    {
        string[] sub = subjects();
        Console.WriteLine(sub);
    }
    public static string[] subjects()
    {
        Console.WriteLine("Please Enter How many Subject Do you Want to input");
        int limit = System.Convert.ToInt32(Console.ReadLine());
        string[] Subjects = new string[limit];
        for (int i = 0; i < limit; i++)
        {
            Console.WriteLine("Please Enter Subject Name " + i);
            Subjects[i] = Console.ReadLine();
        }
        return Subjects;

    }
}

A: The reason that Program is printing system.string[] is because class string[] does not override ToString method, so the default one is used and the default ToString returns type name, not the "value" inside type.
You can use for example String.Join method to build one string from array of strings and put given delimiter between each string:
Console.WriteLine(String.Join(", ", sub));

A: Console.WriteLine(sub)

wont show you anything of value (it prints the sub type), since you are not referencing any value of the sub array, e.g sub[0]. Try this:
foreach (string s in sub)
{
  Console.WriteLine(s);
}

A: Console.WriteLine(String.Join(", ", sub));


text:
Q: Function To Perform Calculations Based Off Variable I saw an answer by @ypercubeᵀᴹ that gave a great answer on how to calculate what appeared to be a quantity ordered by 3 and give whole number answers. Which that got me thinking, how would you handle a situation if there was a variable number of times to split?
Meaning this was the OP where you would always split by 3 (Original Poster
Create Table #Orders
(
    id int IDENTITY(1,1) PRIMARY KEY NOT NULL
    ,partid varchar(100) NOT NULL
    ,qtyordered int DEFAULT '0'
    ,orderedby varchar(100) NOT NULL
    ,ordereddate date DEFAULT GETDATE()
) ;

Insert Into #Orders (partid, qtyordered, orderedby) VALUES
('SS100', 10, 'James'), ('RR200', 5, 'Bob'), ('NN300', 3, 'Jake'), ('OO400', 5, 'Blue') ;

SELECT
   partid,
   qtyordered,
   [First],
   [Second],
   [Third]
FROM
    #Orders
  CROSS APPLY
    ( SELECT [Third]  = (qtyordered)                      / 3 )  AS q3
  CROSS APPLY
    ( SELECT [Second] = (qtyordered - [Third])            / 2 )  AS q2
  CROSS APPLY
    ( SELECT [First]  = (qtyordered - [Third] - [Second]) / 1 )  AS q1;

dbfiddle here
However, what if instead of always splitting by 3, you had an int variable that stated how many times to split, say same DDL but instead of splitting by 3 you use
Declare @TTS int = 5

And now you split each scenario 5 ways instead of 3.  Basically a re-usable function that can "on-the-fly" split based off a variable?

A: Basically, we're just looking to spread the remainder from the division out over the values. This procedure does exactly that; it will return a table with the result vals from the split. I assume we do not want to return a variable number of columns (depending on the divisors we receive), and I decided that actually generating the text "First", "Second", etc. wasn't really a part of the question, so I'm returning each value in its own row.
CREATE PROCEDURE split_into_ints(@dividend int, @divisor int)
AS
BEGIN
    WITH result_rows AS
         (SELECT TOP (@divisor) ROW_NUMBER() OVER (ORDER BY o1.object_id)
                 as result_num
            FROM sys.objects o1 CROSS JOIN sys.objects o2
         )
        ,base_vals AS
         (SELECT @dividend / @divisor as base_result
                ,@dividend % @divisor as remainder
         )
    SELECT r.result_num
          ,CASE WHEN r.result_num <= remainder THEN 1 ELSE 0 END
           + v.base_result as result_val
      FROM base_vals v CROSS JOIN result_rows r
     ORDER BY result_num
END;
GO

The following:
EXECUTE split_into_ints 10,3;
EXECUTE split_into_ints 49,6;
EXECUTE split_into_ints 2000,11;

Yields these results:
result_num           result_val
-------------------- -----------
1                    4
2                    3
3                    3

result_num           result_val
-------------------- -----------
1                    9
2                    8
3                    8
4                    8
5                    8
6                    8

result_num           result_val
-------------------- -----------
1                    182
2                    182
3                    182
4                    182
5                    182
6                    182
7                    182
8                    182
9                    182
10                   181
11                   181

Alternately, you could make this an inline table-valued function:
CREATE FUNCTION fn_split_into_ints(@dividend int, @divisor int)
RETURNS TABLE
AS
RETURN
(
    WITH result_rows AS
         (SELECT TOP (@divisor) ROW_NUMBER() OVER (ORDER BY o1.object_id)
                 as result_num
            FROM sys.objects o1 CROSS JOIN sys.objects o2
         )
        ,base_vals AS
         (SELECT @dividend / @divisor as base_result
                ,@dividend % @divisor as remainder
         )
    SELECT r.result_num
          ,CASE WHEN r.result_num <= remainder THEN 1 ELSE 0 END
           + v.base_result as result_val
      FROM base_vals v CROSS JOIN result_rows r
);
GO

You run the same queries as above thusly:
SELECT * FROM fn_split_into_ints(10,3);
SELECT * FROM fn_split_into_ints(49,6);
SELECT * FROM fn_split_into_ints(2000,11);

Results are the same. To answer one comment: this would allow you to pull result_val into a variable:
SELECT @result_val = result_val
  FROM fn_split_into_ints(49,6)
 WHERE result_num = 6
;

EDIT: Changed function name, so function and procedure can co-exist (if you'd want them to, for some reason).

A: UPDATE
I've used a recursive function to calculate each int item, and a dynamic query to pivot the result.

Declare @TTS int = 5

--= Add divisors
;with AddDiv as
(
    SELECT partid, qtyordered, t.divisions
    FROM   #Orders
    CROSS APPLY (SELECT TOP (@TTS) ROW_NUMBER() OVER (ORDER BY S.[object_id]) [divisions]
                 FROM    sys.all_objects S) t
)
    --= Recursively calc every int item
    , CalDiv as
    (
        SELECT partid, qtyordered, divisions,
               part = qtyordered / divisions, rest = qtyordered - (qtyordered/divisions)
        FROM   AddDiv WHERE divisions = @tts
        UNION ALL
        SELECT ad.partid, ad.qtyordered, ad.divisions,
               part = rest / ad.divisions, rest = rest - (rest / ad.divisions)
        FROM   AddDiv ad
        INNER JOIN CalDiv cd
        ON ad.partid = cd.partid
        WHERE ad.divisions = cd.divisions - 1
    )
    SELECT *
    INTO   Results
    FROM   CalDiv;

And now the dynamic PIVOT:

DECLARE @col AS nvarchar(MAX),
        @cmd AS nvarchar(MAX);

SET @col = STUFF((SELECT distinct ',' + QUOTENAME(divisions)
            FROM Results
            FOR XML PATH(''), TYPE
            ).value('.', 'nvarchar(MAX)')
           ,1,1,'')

SET @cmd =   'SELECT partid, qtyordered, ' + @col
           + ' FROM'
           + ' (SELECT partid, qtyordered, divisions, part'
           + ' FROM Results) src'
           + ' PIVOT (MAX(part) FOR divisions IN (' + @col + ')) pvt';

EXECUTE (@cmd);

And this is the final result:

partid | qtyordered | 1  | 2  | 3  | 4  | 5
:----- | ---------: | :- | :- | :- | :- | :-
NN300  |          3 | 1  | 1  | 1  | 0  | 0
OO400  |          5 | 1  | 1  | 1  | 1  | 1
SS100  |         10 | 2  | 2  | 2  | 2  | 2
RR200  |         15 | 3  | 3  | 3  | 3  | 3

dbfiddle here
This is my first answer, It uses a function to build a comma delimited string with all int items.

Create Table #Orders
(
    id int IDENTITY(1,1) PRIMARY KEY NOT NULL
    ,partid varchar(100) NOT NULL
    ,qtyordered int DEFAULT '0'
    ,dividedBy int DEFAULT 1
    ,orderedby varchar(100) NOT NULL
    ,ordereddate date DEFAULT GETDATE()
) ;

Insert Into #Orders (partid, qtyordered, dividedBy, orderedby) VALUES
('SS100', 10, 3, 'James'), ('RR200', 15, 6, 'Bob'), ('NN300', 3, 2, 'Jake'), ('OO400', 5, 4, 'Blue') ;
GO

CREATE FUNCTION fnCF(@Qty decimal, @TTS int)
RETURNS varchar(1024)
AS
BEGIN
    DECLARE @step int = 0;
    DECLARE @sv varchar(1024) = '';
    DECLARE @Q0 int;
    DECLARE @Q1 decimal;

    SET @step = @TTS
    SET @Q1 = @Qty

    WHILE  @step > 0
    BEGIN
        SET @Q0 = @Q1 / @step;
        SELECT @sv = @sv + CAST(@Q0 AS varchar(100))
        SET @step = @step -1
        SET @Q1 = @Q1 - @Q0
        IF @step > 0
        SET @sv = @sv + ', '
    END

    return @sv;
END

GO

✓

SELECT
   partid,
   qtyordered,
   dividedBy,
   dbo.fnCF(qtyordered, dividedBy) divInt
FROM
    #Orders;
GO

partid | qtyordered | dividedBy | divInt
:----- | ---------: | --------: | :---------------
SS100  |         10 |         3 | 3, 3, 4
RR200  |         15 |         6 | 2, 2, 2, 3, 3, 3
NN300  |          3 |         2 | 1, 2
OO400  |          5 |         4 | 1, 1, 1, 2

dbfiddle here


text:
Q: Enable push notifications on instant app Im trying to integrate fcm in my instant app but it dosnt works.
I have 4  manifest files
:
/app /base /module1 /module2
The APP manifest only contains this code:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.stackoverflow.app"/>

In the base manifest is declared my application and my configuration for push notifications.
Any idea whats going wrong?

A: Instant Apps don't support push notifications currently. In Google I/O 2018, a Beta program for selected Instant Apps to enable notifications was announced: https://www.youtube.com/watch?v=tXqat1JOmS8&feature=youtu.be&t=743

A: Instant apps still do not support push notifications in 2023. They are able to generate FCM registration token, launch services and foreground services, but the problem is that the generated token is rejected with HTTP 400 when you try to use it. Once you install the same app as a regular app it works fine with no code or configuration changes.


text:
Q: How do I store a .Net MemorySteam value in DynamoDB? I am using AWS KMS Encrypt API to encrypt a text. The Encrypt API returns a EncryptResponse object that has a MemoryStream attribute which is the encrypted value.
I am using the AWS .Net SDK and trying to save this value to DynamoDB.
How can I save this value? I tried converting this to a String but while the conversion saving DynamoDB and retrieval gave me back the MemoryStream object, the resultant cipher text from the recreated MemoryStream object cannot be decrypted with an error "Invalid ciphertext."
Here is the code used to save and retrieve the string
// convert stream to string
StreamReader reader = new StreamReader(ciphertextBlob);
string text = reader.ReadToEnd();

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(text);
MemoryStream stream = new MemoryStream(byteArray);

When retrieving the stream it was noticed that the ciphertext was different for the object before saving and that during retrieval.

*

*The EncryptFunction

*The EncryptResponse

A: This issue was solved by converting the memory stream object into a byte[] and saving it as a String in DynamoDB.
byte[] byteArray = ReadFully(ciphertextBlob);
                    string AccessKeycipherText = Convert.ToBase64String(byteArray);

The base64 encoding was used to get a String representation of the byte array.
The memory stream object was retrieved using the reverse.
byte[] temp_backToBytes = Convert.FromBase64String(AccessKey);
                 MemoryStream stream = new MemoryStream(temp_backToBytes);


text:
Q: Do Device.getSystemColors() need to be disposed in SWT? I understand that colors creating using new Color() need to be disposed manually. What about colors obtained via Device.getSystemColor( SWT.COLOR_... )? do they need to be disposed as well?

A: No, you must not dispose of these colors.

A: Just look at the Javadoc:

Returns the matching standard color for the given constant, which should be one of the color constants specified in class SWT. Any value other than one of the SWT color constants which is passed in will result in the color black. This color should not be freed because it was allocated by the system, not the application.


text:
Q: I have a very long 934 entries list and want to display it in a 6 multicolumn menu This is the php code that generates the list and queries the db, I already have some css, but I want to split the list in 6 columns, 16 rows each and add a more ... link at end
<?php

$show_manufacturers= true;

// for large lists of manufacturers uncomment this section

/*  if (($_GET['main_page']==FILENAME_DEFAULT and ($_GET['cPath'] == '' or    $_GET['cPath'] == 0)) or  ($request_type == 'SSL')) {
$show_manufacturers= false;
} else {
$show_manufacturers= true;
}
*/

// Set to true to display manufacturers images in place of names
define('DISPLAY_MANUFACTURERS_IMAGES',false);
if ($show_manufacturers) {

// only check products if requested - this may slow down the processing of the    manufacturers sidebox
if (PRODUCTS_MANUFACTURERS_STATUS == '1') {
$manufacturer_sidebox_query = "select distinct m.manufacturers_id, m.manufacturers_name, m.manufacturers_image
                        from " . TABLE_MANUFACTURERS . " m
                        left join " . TABLE_PRODUCTS . " p on m.manufacturers_id = p.manufacturers_id
                        where m.manufacturers_id = p.manufacturers_id and p.products_status= 1
                        order by manufacturers_name";
} else {
$manufacturer_sidebox_query = "select m.manufacturers_id, m.manufacturers_name, m.manufacturers_image
                        from " . TABLE_MANUFACTURERS . " m
                        order by manufacturers_name";
}

$manufacturer_sidebox = $db->Execute($manufacturer_sidebox_query);

if ($manufacturer_sidebox->RecordCount()>0) {
$number_of_rows = $manufacturer_sidebox->RecordCount()+1;

// Display a list
$manufacturer_sidebox_array = array();
//      kuroi: commented out to avoid starting list with text scrolling list    entries such as "reset" and "please select"
//    if (!isset($_GET['manufacturers_id']) || $_GET['manufacturers_id'] == '' ) {
//      $manufacturer_sidebox_array[] = array('id' => '', 'text' => PULL_DOWN_ALL);
//    } else {
//      $manufacturer_sidebox_array[] = array('id' => '', 'text' =>  PULL_DOWN_MANUFACTURERS);
//    }

while (!$manufacturer_sidebox->EOF) {
  $manufacturer_sidebox_name = ((strlen($manufacturer_sidebox- >fields['manufacturers_name']) > MAX_DISPLAY_MANUFACTURER_NAME_LEN) ?  substr($manufacturer_sidebox->fields['manufacturers_name'], 0,  MAX_DISPLAY_MANUFACTURER_NAME_LEN) . '..' : $manufacturer_sidebox- >fields['manufacturers_name']);
  $manufacturer_sidebox_image = $manufacturer_sidebox->fields['manufacturers_image'];
  $manufacturer_sidebox_array[] =
    array('id' => $manufacturer_sidebox->fields['manufacturers_id'],
          'text' => DISPLAY_MANUFACTURERS_IMAGES ?
            zen_image(DIR_WS_IMAGES . $manufacturer_sidebox_image,     $manufacturer_sidebox_name) :
            $manufacturer_sidebox_name);
  $manufacturer_sidebox->MoveNext();
}

}

} // $show_manufacturers This is where I need to make changes
for ($i=0;$i<sizeof($manufacturer_sidebox_array);$i++) {
      $content = '';
  $content .= '
';
  $content .= $manufacturer_sidebox_array[$i]['text'];
  $content .= '
' . "\n";
  echo $content;
}
?>

A: If you're looking for a pure CSS solution, you have 2 options:
Use the CSS3 columns property, but it only works in modern browsers (some require a prefixed version).  You're guaranteed to get 6 columns no matter what.  Your elements will be presented like a newspaper article (reads top to bottom).
http://caniuse.com/#feat=multicolumn
http://jsfiddle.net/funag/
Use floats.  Float has been around forever, but if you're looking at content that will potentially wordwrap, it might take more effort to line up a specific way.  The up side is that if your device is too narrow to support 6 columns, it will gracefully wrap to however many columns make sense for that width without scrolling.  Your elements will be presented like a paragraph (reads left to right).
http://jsfiddle.net/funag/2/
If you're looking to break up your elements via PHP, what you want is the modulus operator:
if ($i % 6 == 0) {
    // insert html tags to force a break
}


text:
Q: Android achartengine How to get 0 on Y axis have padding at bottom I have a problem whereby my Y axis minimum is 0, this is good, but I need it to be offset from the bottom a bit, because when there's a sequence of zero values, my X labels are slightly covered by the dot. Also, the X axis line is running through all the points, which looks bad.
Is this possible with achartengine? How can I acheive it? Thank you


text:
Q: How to share split APKs created while using instant-run, within Android itself? Background
I have an app (here) that, among other features, allows to share APK files.
In order to do so, it reaches the file by accessing the path of packageInfo.applicationInfo.sourceDir (docs link here), and just shares the file (using ContentProvider when needed, as I've used here).
The problem
This works fine in most cases, especially when installing APK files from either the Play Store or from a standalone APK file, but when I install an app using Android-Studio itself, I see multiple APK files on this path, and none of them are valid ones that can be installed and run without any issues.
Here's a screenshot of the content of this folder, after trying out a sample from "Alerter" github repo  :

I'm not sure when this issue has started, but it does occur at least on my Nexus 5x with Android 7.1.2. Maybe even before.
What I've found
This seems to be caused only from the fact that instant run is enabled on the IDE, so that it could help updating the app without the need to re-build it all together :

After disabling it, I can see that there is a single APK, just as it used to be in the past:

You can see the difference in file size between the correct APK and the split one.
Also, it seems that there is an API to get the paths to all of the splited APKs:
https://developer.android.com/reference/android/content/pm/ApplicationInfo.html#splitPublicSourceDirs
The question
What should be the easiest way to share an APK that got to be split into multiple ones ?
Is it really needed to somehow merge them?
It seems it is possible according to the docs :

Full paths to zero or more split APKs that, when combined with the
  base APK defined in sourceDir, form a complete application.

But what's the correct way to do it, and is there a fast and efficient way to do it? Maybe without really creating a file?
Is there maybe an API to get a merged APK out of all the split ones? Or maybe such an APK already exist anyway in some other path, and there is no need for merging?
EDIT: just noticed that all third party apps that I've tried are supposed to share an installed app's APK fail to do so in this case.

A: I am the tech lead @Google for the Android Gradle Plugin, let me try to answer your question assuming I understand your use case.
First, some users mentioned you should not share your InstantRun enabled build and they are correct. The Instant Run builds on an application is highly customized for the current device/emulator image you are deploying to. So basically, say you generate an IR enabled build of your app for a particular device running 21, it will fail miserably if you try to use those exact same APKs on say a device running 23. I can go into much deeper explanation if necessary but suffice to say that we generate byte codes customized on the APIs found in android.jar (which is of course version specific).
So I do not think that sharing those APKs make sense, you should either use a IR disabled build or a release build.
Now for some details, each slice APK contains 1+ dex file(s), so in theory, nothing prevents you from unziping all those slice APKs, take all the dex files and stuff them back into the base.apk/rezip/resign and it should just work. However, it will still be an IR enabled application so it will start the small server to listen to IDE requests, etc, etc... I cannot imagine a good reason for doing this.
Hope this helps.

A: To merge multiple split apks to an single apk might be a little complicated.
Here is a suggestion to share the split apks directly and let the system to handle the merge and installation.
This might not be an answer to the question, since it's a little long, I post here as an 'answer'.
Framework new API PackageInstaller can handle monolithic apk or split apk.
In development environment

*

*for monolithic apk, using adb install single_apk

*for split apk, using adb install-multiple a_list_of_apks
You can see these two modes above from android studio Run output depends on your project has Instant run enable or disable.
For the command adb install-multiple, we can see the source code here, it will call the function install_multiple_app.
And then perform the following procedures
pm install-create # create a install session
pm install-write  # write a list of apk to session
pm install-commit # perform the merge and install

What the pm actually do is call the framework api PackageInstaller, we can see the source code here
runInstallCreate
runInstallWrite
runInstallCommit

It's not mysterious at all, I just copied some methods or function here.
The following script can be invoked from adb shell environment to install all split apks to device, like adb install-multiple. I think it might work programmatically with Runtime.exec if your device is rooted.
#!/system/bin/sh

# get the total size in byte
total=0
for apk in *.apk
do
    o=( $(ls -l $apk) )
    let total=$total+${o[3]}
done

echo "pm install-create total size $total"

create=$(pm install-create -S $total)
sid=$(echo $create |grep -E -o '[0-9]+')

echo "pm install-create session id $sid"

for apk in *.apk
do
    _ls_out=( $(ls -l $apk) )
    echo "write $apk to $sid"
    cat $apk | pm install-write -S ${_ls_out[3]} $sid $apk -
done

pm install-commit $sid

I my example, the split apks include (I got the list from android studio Run output)
app/build/output/app-debug.apk
app/build/intermediates/split-apk/debug/dependencies.apk
and all apks under app/build/intermediates/split-apk/debug/slices/slice[0-9].apk

Using adb push all the apks and the script above to a public writable directory, e.g /data/local/tmp/slices, and run the install script, it will install to your device just like adb install-multiple.
The code below is just another variant of the script above, if your app has platform signature or device is rooted, I think it will be ok. I didn't have the environment to test.
private static void installMultipleCmd() {
    File[] apks = new File("/data/local/tmp/slices/slices").listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.getAbsolutePath().endsWith(".apk");
        }
    });
    long total = 0;
    for (File apk : apks) {
        total += apk.length();
    }

    Log.d(TAG, "installMultipleCmd: total apk size " + total);
    long sessionID = 0;
    try {
        Process pmInstallCreateProcess = Runtime.getRuntime().exec("/system/bin/sh\n");
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(pmInstallCreateProcess.getOutputStream()));
        writer.write("pm install-create\n");
        writer.flush();
        writer.close();

        int ret = pmInstallCreateProcess.waitFor();
        Log.d(TAG, "installMultipleCmd: pm install-create return " + ret);

        BufferedReader pmCreateReader = new BufferedReader(new InputStreamReader(pmInstallCreateProcess.getInputStream()));
        String l;
        Pattern sessionIDPattern = Pattern.compile(".*(\\[\\d+\\])");
        while ((l = pmCreateReader.readLine()) != null) {
            Matcher matcher = sessionIDPattern.matcher(l);
            if (matcher.matches()) {
                sessionID = Long.parseLong(matcher.group(1));
            }
        }
        Log.d(TAG, "installMultipleCmd: pm install-create sessionID " + sessionID);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }

    StringBuilder pmInstallWriteBuilder = new StringBuilder();
    for (File apk : apks) {
        pmInstallWriteBuilder.append("cat " + apk.getAbsolutePath() + " | " +
                "pm install-write -S " + apk.length() + " " + sessionID + " " + apk.getName() + " -");
        pmInstallWriteBuilder.append("\n");
    }

    Log.d(TAG, "installMultipleCmd: will perform pm install write \n" + pmInstallWriteBuilder.toString());

    try {
        Process pmInstallWriteProcess = Runtime.getRuntime().exec("/system/bin/sh\n");
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(pmInstallWriteProcess.getOutputStream()));
        // writer.write("pm\n");
        writer.write(pmInstallWriteBuilder.toString());
        writer.flush();
        writer.close();

        int ret = pmInstallWriteProcess.waitFor();
        Log.d(TAG, "installMultipleCmd: pm install-write return " + ret);
        checkShouldShowError(ret, pmInstallWriteProcess);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }

    try {
        Process pmInstallCommitProcess = Runtime.getRuntime().exec("/system/bin/sh\n");
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(pmInstallCommitProcess.getOutputStream()));
        writer.write("pm install-commit " + sessionID);
        writer.flush();
        writer.close();

        int ret = pmInstallCommitProcess.waitFor();
        Log.d(TAG, "installMultipleCmd: pm install-commit return " + ret);
        checkShouldShowError(ret, pmInstallCommitProcess);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

private static void checkShouldShowError(int ret, Process process) {
    if (process != null && ret != 0) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String l;
            while ((l = reader.readLine()) != null) {
                Log.d(TAG, "checkShouldShowError: " + l);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Meanwhile, the simple way, you can try the framework api. Like the sample code above, it might work if the device is rooted or your app has platform signature, but I didn't get a workable environment to test it.
private static void installMultiple(Context context) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();

        PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);

        try {
            final int sessionId = packageInstaller.createSession(sessionParams);
            Log.d(TAG, "installMultiple: sessionId " + sessionId);

            PackageInstaller.Session session = packageInstaller.openSession(sessionId);

            File[] apks = new File("/data/local/tmp/slices/slices").listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.getAbsolutePath().endsWith(".apk");
                }
            });

            for (File apk : apks) {
                InputStream inputStream = new FileInputStream(apk);

                OutputStream outputStream = session.openWrite(apk.getName(), 0, apk.length());
                byte[] buffer = new byte[65536];
                int count;
                while ((count = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, count);
                }

                session.fsync(outputStream);
                outputStream.close();
                inputStream.close();
                Log.d(TAG, "installMultiple: write file to session " + sessionId + " " + apk.length());
            }

            try {
                IIntentSender target = new IIntentSender.Stub() {

                    @Override
                    public int send(int i, Intent intent, String s, IIntentReceiver iIntentReceiver, String s1) throws RemoteException {
                        int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE);
                        Log.d(TAG, "send: status " + status);
                        return 0;
                    }
                };
                session.commit(IntentSender.class.getConstructor(IIntentSender.class).newInstance(target));
            } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                e.printStackTrace();
            }
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In order to use the hidden api IIntentSender, I add the jar library android-hidden-api as the provided dependency.

A: Those are called split apks. Which is mainly used in the PlayStore. As you may know, PlayStore only shows apps to the user if it's compatible with the device. Same in this case. The split has files varies from devices. Like if you used Different resources for Different devices which makes app really heavy. By making splits, it saves space for downloading and running for the user by only downloading the usable split apks.
Is it possible to merge them into single apk?
Yes. I used an app called Anti Split which allows that. Plus Apk Editor Ultra has same.
Can we save it into a single file?
Yes you can. As like for Anti Split, you have to first backup the app. Like in this case you have to back it up as apks file or xapk which is called bundled app in Android Studio. I have created a library for doing this. It's working perfectly for me. Am using it to backup apps into xapk which can later be installed using SIA app or XAPK Installer or we can use xapk file to merge it and make apk

A: For me instant run was a nightmare, 2-5 minute build times, and maddeningly often, recent changes were not included in builds. I highly recommend disabling instant run and adding this line to gradle.properties:
android.enableBuildCache=true

First build often takes some time for large projects (1-2mins), but after it's cached subsequent builds are usually lightnight fast (<10secs).
Got this tip from reddit user /u/QuestionsEverythang which has saved me SO much hassling around with instant run!


text:
Q: how to .mkt file in python mkt file but not able to open in python.
Please help
i not able to attach file here is some part of content in file when i open with notepad.
"""
 "^N ÓE    ñ 4    Ae 4 Ø q 'þ  l P ¿ P  1        "^N †8Œ   "Õ Œ           ò= Œ   Œ   Œ   Œ   x       ÿàõ                 "^N <&  c   ý%  T  &  MÍ ‹&  <(  Z(  î%  ì'  &  ý%  ý%  &  ç        "^N R¯  å   ¥  a   ¯  «¬ ö  ê  ê  n  c  ´  ¯  ´  ¯  ×        "^N €>
   Y=  .  €>  n  >  Ï?  G@  ~;  M?  €>  €>  €>  €>          "^N ‰Ú      Æ  *   Ú  ³• ox  ht  Ž€  Hq  ]p   €  X  v  Ú  ë       "^N u
ê  PF    p  ï                      ê      ÿàõ                 "^N x^¥
    ¥
    & ·é  H ´! ´! » ~% 5 –
 –
 ¥
         ó
"^N 0c   ,   s  ¥      ¢4  ^        °  â              é       "^N ³;åG     åG
   ïG  h  »G  {H  8J  ´F  IH  åG  åG  åG  åG    "


text:
Q: Can progressive tense be used for the progress of developing habits? I have a question about what expressions are more accurate when trying to describe the development of habits in progress.
For example:
1. I am now getting used to getting up at 7:30 am.
2. I get used to getting up at 7:30 am.
3. I get up at 7:30 am.
I think the first one should be correct but we usually use 'get used to' to describe some habits that have already been formed. Can it be used in the progressive tense? Or there is another expression that is more accurate? Thanks!

A: As has been told you in the comments, "2" is not correct; it would be if you'd used the past.

*

*I got used to getting up at 7:30 am. (correct)

Why is not the present correct? ( I get used to getting up at 7:30 am.)
This is not too easy to understand; when you use the present in that way the particular form of that present is called habitual present (CoGEL § 4.6 p. 179), a type of use of the simple present.
Examples from CoGEL § 4.6

*

*We go to Brussels every year.

*She makes her own dresses.

*Bill drinks heavily.

(CoGEL) when they are used with the simple present, dynamic verb meanings, like stative verb meanings, usually imply an inherently unrestricted time span. But in this case the verb refers to a whole sequence of events repeated over the period in question.

In the first instance, the people the author is talking about went to Brussels several times and will keep on repeating this action for an undetermined time to come. The same idea of repeated action is found in "She makes her own dresses.": She has made several dresses (presumably over the years) and she will go on repeating this action as long as she finds this activity satisfying.
In the context of the sentence "2", there is not the possibility of a repetition with the action of "getting used to sth"; it takes place over a certain period of time, once, and as soon as the getting used to is fully acquired it stops and is not repeated; repeating it would have no meaning.
However, it is not quite simple and changing the context can make the habitual present correct for the verbal form "ge used to"; for instance, the following sentence is correct.

*

*When I start a new design I get used to handling the various techniques needed  by brushing up on the use I have made of them formerly.

CoGEL: A comprehensive grammar of the English language


text:
Q: Changing SSRS parameter values after the report is run. Is this possible? I'm trying to change SSRS parameter values after the report is run. Is this possible? Reason is that I have seven params with two set before running the report. The user can then click on a URL value from the report list to go to a drilldown report. Depending on the selection the user clicks the remaining five params will have different values, but I don't know how to change them to match where the use clicks. Thanks.

A: If you are using the Go to Report action, you would add the parameters and set them to whatever field, parameter or other value that you want.
If you are using Go to URL you need to add them into the URL text string.
At the end of the URL for the report, add the &rs:Command=Render then add an ampersand, your parameter name, and an equals sign. Then escape out of the string and add your value. Here's a sample that passes fields, parameters and hard coded values to the drill down report parameters.
="javascript:void window.open('" & Globals!ReportServerUrl & "?"
& Globals!ReportFolder & "/ClaimsRecoveriesDetails&rs:Command=Render"
& "&YYYYMM=" & CSTR(Fields!RECOVERY_YEAR.Value) & CSTR(Fields!RECOVERY_MONTH.Value)
& "&PARTICIPATION_TYPE=" & Parameters!PARTICIPATION_TYPE.Value
& "&ISRECOVERIESSUBMITTED=" & "YES"
+ "&rs:Command=Render','_blank','resizeable=1,toolbar=0,status=0,menu=0,top=20,left=15,width=1500,height=700,scrollbars=1')"

The javascript is used to open a separate window for this one.
Here's some (lame) advice from Microsoft:
https://learn.microsoft.com/en-us/sql/reporting-services/pass-a-report-parameter-within-a-url?view=sql-server-2017


text:
Q: How prove $e^x|f(x)|\le 2$ if $f(x)=\int_{x}^{x+1}\sin{(e^t)}dt$ let $$f(x)=\int_{x}^{x+1}\sin{(e^t)}dt$$
show that:
$$e^x|f(x)|\le 2$$
My idea: let $$e^t=u$$
then
$$|f(x)|=|\int_{e^x}^{e^{x+1}}\dfrac{1}{u}d\cos{u}|$$

A: Consider integrating by parts once $\displaystyle f(x) = \int_{e^x}^{e^{x+1}} \dfrac{\sin u}{u}\,du = \left[\dfrac{-\cos u}{u}\right]_{e^x}^{e^{x+1}} - \int_{e^x}^{e^{x+1}} \dfrac{\cos u}{u^2}\,du$
Use, $|\cos u| \le 1$ to infer:
$$\cos e^x - 1 + \frac{1}{e}\left(1- \cos e^{x+1}\right) \leq e^xf(x) \leq \cos e^x + 1 - \frac{1}{e}\left(\cos e^{x+1} + 1 \right)$$
Thus, $|e^xf(x)| < 2$


text:
Q: Struts 2 Avoid duplicate action Consider below sample in a struts 2 application. This is a page which shows a grid and user can export SAME grid to PDF.
We develop a class with two actions, one action returns a grid as JSON and the other one export the SAME grid to PDF.
The structure of code is as below:
Two different action maps has been defined /ShowGrid and /ExportGrid
@Action (name="ShowGrid") // Result will be set to JSON
@validation ( @Required (..... // Validation Rules for fromDate toDate etc
public String showGrid(){
gird = serviceFacade.getGrid(fromDate,toDate);
return SUCCESS;
}

@Action (name="ExportGrid" ) //Result will be set as stream
@validation ( @Required ..... // Validation Rules for fromDate toDate etc
public String exportGrid(){
grid = serviceFacade.getGrid(fromDate,toDate);
inputStream = convertGridToStream(grid); // By using jasper report or other tools
return SUCCESS;
}

As you can see the above methods has lots of common structure,

*

*The validation is duplicated ( In my use case the validation rules are LOT)

*Calling the service method is duplicated

Is there any way to avoid this ?!

A: You can map many actions to the same method, using @Actions annotation. Inside the actions method you can get the name from the action context and define the logic.
@Actions({
  @Action ("ExportGrid"), //Result will be set as stream
  @Action ("ShowGrid") // Result will be set to JSON
})
@validation ( @Required ..... // Validation Rules for fromDate toDate etc
public String doGrid(){
  grid = serviceFacade.getGrid(fromDate,toDate);
  if (ActionContext.getContext().getName().equals("ExportGrid")
    inputStream = convertGridToStream(grid); // By using jasper report or other tools
  return SUCCESS;
}


text:
Q: Filtering non-primitive types with hibernate In my database I do not delete objects. Instead a soft delete is done. Means a delted flag is set to true. This should be filtered by hibernate using the @Filter annotation.
This works but I have the problem that fields are not filtered.
For example I have a child class and a parent class which contains a child. If the child gets deleted and the parent gets loaded the parent object contains the child object (although the deleted flag is set correctly). But I want the child object to be filtered like it works with collections.
Is there any way to do that?
I tried treating the field like a collecting but this didn't work for me.
@Entity
@FilterDef(name = deletedFilter, parameters = @ParamDef(name = deletedParam, type = "boolean"))
@Filter(name = deletedFilter, condition = ":deletedParam = deleted")
public class Child {}

@Entity
public class Parent {
    @OneToOne
    @Filter(name = deletedFilter, condition = ":deletedParam = deleted")
    private Child child = new Child();
}

A: Hibernate filters are not working on @OneToOne relations.
https://hibernate.onjira.com/browse/HHH-4026
The explanation is on the comments to the issue: filters would change the cardinality of the relation.

A: If the boolean flag doesn't work you can use Integer value instead. And can check accordingly.


text:
Q: How to Serialize with field from reverse related model - Django rest framework I have an api that retrieves all items related to a project through a manytomany model with an extra order field. I am now trying to serialize the items with the order value on it.
One solution would be to serialize the through model, but that gives a result like this:
{
    "order": 1,
    "item": {
        "id": 3031,
        "name": "Miami"
    }
},

I would like to serialize the item instead and get an output like so:
{
    "order": 1,
    "id": 3031,
    "name": "Miami"
}

I can't add the order as an Attribute to the item model, as it's a manytomany field. Or I guess I could but would have to take the first object of a list, which is not a solution I think is very clean and would probably add a separate database call.
All the items are fetch like so:
ProjectItem.objects.filter(project_id=self.kwargs['project_pk']).select_related('item')

Any ideas?

A: If you have a through model, then you should serialize it and use the source extra argument to "flatten" the representation.
For example, for name, it would be
name = serializers.CharField(source='item.name')

You probably will have to write the serializer create / update methods to make this work for writable.

A: If you for some reason don't want to go through the through model like @Linovia suggests, then you can prefetch the through model and use a RelatedField with an overwritten to_representation.
This is what I did:
from django.db.models import Prefetch

Item.objects.filter(projectitem_set__project_id=self.kwargs['project_pk'])
    .prefetch_related(
        Prefetch('projectitem_set', queryset=ProjectItem.objects.filter(project_id=self.kwargs['project_pk']), to_attr='order'))

Then added this to the ItemSerializer (don't add many=True):
order = ProjectItemSerializer(read_only=True)

And overwrite the to_representation in the ProjectItemSerializer:
class ProjectItemSerializer(serializers.RelatedField):
    def to_representation(self, value):
        return value[0].order

value[0] gets the first object of the prefetched values


text:
Q: Creating Routes using the second NIC in the box OS: Linux
I need some advice on how to set up the routing table. I have a box with two physical NIC cards eth0 & eth1 with two associated IPs IP1 & IP2 (both of the same subnet). I need to setup a route which will force all messages from IP1 towards IP3 (of the same subnet) to go via IP2.
I have a raw socket capture program listening on IP2 (This is not for malicious use).
I have set up the routing table as
Destination  Gateway       Genmask        Flags  Metric  Ref  Use  Iface
   IP3         IP2      255.255.255.255    UGH    0       0    0    eth1

If I try to specify eth0 while adding the above rule, I get an error "SIOCADDRT: Network is unreachable". I understand from the manpage of route that if the GW specified is a local interface, then that would be use as the outgoing interface.
After setting up this rule, if i do a traceroute (-i eth0), the packet goes first to the default gateway and then to IP3.
How do I force the packet originating from eth0 towards IP3 to first come to IP2. I cannot make changes to the routing table of the gateway.
Please suggest.

A: If I understand you correctly you need policy based routing, particularly, source based routing.  Here is a simple howto to do just that.
The idea is that traditional routing makes its routing choice by looking at the destination address field in the IP header and comparing it to its routing table.  Policy based routing can look at other fields, or even other items such as TCP ports.  In the case of source based routing, it looks at the source address field in the IP header.


text:
Q: ios7: how to track system internals like notifications We are developing application which rely on new IOS7 functionality - remote-notification background updates.
According to docs system can "skip" calls to didReceiveRemoteNotification:fetchCompletionHandler: if it finds that background processing power-consuming and lengthy, etc and we see this in practice - user can get push notification on the screen, but calls to didReceiveRemoteNotification:fetchCompletionHandler: are simply not happening at all
The question is - how we can check what happeping in ios with push? is there some ways to see internal system logs with real information from ios services? We need this for debug purposes of course, not in released application. just to double-check and fine tune our background processing. There is should be the way for developer to see what is really happening on device.
I found application "appswitcher" that shows similar stuff, but on ios7 it shows only active application logs (appswitcher itself), not system-wide. so it is useless for us...
To be clear: push notifications are working correctly, they are always received by the program in Debug mode for example. But in release/adhoc build we see that some notifications are sent to applications (waking it from background) and some are not. Documentation stating that fetch callback is used to calculate cpu/data usage and ios reserve right to "skip" notifications when it feels to do so, we just want to find the way to see is this is the case
Any help is welcome

A: I've never tried it but I saw this a while back. By looking at it, it seems like it will help your case but unfortunately, you gotta give it a try to find out if its worth it or not.
https://developer.apple.com/downloads/index.action
Go to that website, and login using your developer account.
Go to page 2 (or find Oct 4, 2013 post Bug Reporter Logging Profiles (iOS)).
In the description, Apple has a link that tells you how to use these profiles. As the title of that post suggest that it is used for bug reporting, hopefully it gives you some details so you could fix your bugs.
Try it and see if it works and let other people know if it's useful or not. Since it says 'Logging', my guess is that it will output detail info on the console about push messages and not secretly log and sends the log to apple.

A: Firstable you need to check if your push notification working correctly. What i would do is temporary disable background fetching, and simply check if i get push.
If everything is ok i will turn background fetch back in Capabilities and try to send one in Debug. Even app is in background you can still have a breakpoints. If method is not called try look at the console.
I think you have a problem with push notification other than backgroundFetching.
If you are willing to try what happen when application is not in background mode but wass 9-killed you should put NSLogs in method. If you see NSLog in console then (Xcode -> ⌘⇧2 -> your device (connected) -> Console) you're good to go.
The production console is in background fetching useless to you unless you put NSLogs in your methods. But then you can only check if you successfully enter method and log a parameters.


text:
Q: reduce the number of loops when using ListView c# I have a listView looks like this:

and I would like to iterate each item as many as in the quantity column. I have written a code that do this:
            foreach (ListViewItem item in listView1.Items)
        {

            for (int quantity = 1; quantity < (Convert.ToInt32(item.SubItems[1].Text) + 1); quantity++)
            {
                 //do something
            }
        }

I'm wonder if I can do this in just one loop instead of two.
Thanks

A: I'm not sure why you want to do that, but if you think it's necessary and helps, you could do some linq like that:
var items = listView1.Items.OfType<ListViewItem>();
var query = items.SelectMany(item =>
               Enumerable.Range(1, Convert.ToInt32(item.SubItems[1].Text))
                         .Select(i => new { Item = item, Index = i});
foreach(var element in query)
{
    Console.WriteLine("Book: {0}, i: {1}", element.Item.Text, element.Index);
}

Result:
Book: book1, i: 1
Book: book1, i: 2
Book: book1, i: 3
Book: book1, i: 4
Book: book2, i: 1
...
Book: book2, i: 11
Book: book3, i: 1
...
Book: book3, i: 13

But as you mentionend readability in a comment, I really think that your two nested loops are readable enough, or at least more readable than this link.
And a note to be clear: this does not reduce the number of iterations, it just reduces the nesting of loops.

A more readable approach would be encapsulating some functionality in extra methods:
foreach(ListViewItem item in ListViewItems)
    HandleItem(item);

private void HandleItem(ListViewItem item)
{
    for (int i=1; i<Convert.ToInt32(item.SubItems[1].Text)+1; i++)
        HandleItemWithIndex(item, i);
}
private void HandleItemWithIndex(ListViewItem item, int index)
{
    // Do something
}

This way (if you name the methods appropriately) it's easy to follow what happens and what purpose each method has.


text:
Q: Работа с экраном блокировки Здравствуйте, такой вопрос: как происходит работа с экраном блокировки, а именно: какая блокировка установлена, сколько попыток ввода пароля уже было. Заранее благодарю.
A: Насколько я знаю в "родном" Android'е на экран блокировки нет пароля. Пример блокировки и разблокировки экрана здесь
Обычно производители телефонов сами пишут локи/анлоки экранов в составе своих оболочек, как например HTC Sense и Samsung TouchWiz. Смотрите документацию по ним. У обоих есть свои API (правда, довольно куцые).


text:
Q: Store external page source in Javascript variable? Strictly using Javascript, is it possible to call a remote URL and store it in a variable?  To specify, this would not be on the same domain. Basically, what i am trying to figure out the best solution for scraping/parsing data in a chrome extension.

A: If you're trying to load the page from an external domain, you'll run into the same-origin policy. You can get around this limitation by setting up a simple proxy on your own site. This would be a bit of server-side code whose function is to make the http request to the external page on your behalf, retrieve the response, then serve that content back to the on-page asynchronous JavaScript code making the original request.
So if you set up your proxy at /your_internal_proxy.foo, and you're using jQuery, you could build a JS function something like this:
var foreignContent = {};
var loadPage = function(pageURL,varName) {
  $.ajax({
    type: 'get',
    url: '/your_internal_proxy.foo',
    data: {
      url_to_get: pageURL
    },
    success: function(result) {
      foreignContent[varName] = do_something_to( result );
    }
  });
};

Then, to load content into JS variables:
loadPage('http://www.google.com/','goog');
loadPage('http://stackoverflow.com','stack');

A: While Ajax may be the way to go it depends on what you mean by "remote URL".  Ajax will only work for url's with the same domain as the domain where the javascript originated from, due to Javascript cross-domain restrictions. There are various work arounds but most require the co-operation of the remote domain.  I've have heard of using YQL as an intermediary but have never tried it. Easiest is to host a proxy on your own server.

A: If you are allowed to use jQuery you can have something like:
  $.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

Also the $.get() can be used to achieve this

http://api.jquery.com/jQuery.get/

$.get("test.html",
   function(data){
   // do something with response data
   });


text:
Q: UNIX domain datagram - "Invalid argument" on sendto I am constructing UNIX domain datagram sockets to pass messages from one thread to another thread in the same program.  The socket code is written in C and it's called from NASM.
Sendto returns (through perror) "socket: Invalid argument."
Here is the code for sendto:
ssize_t client_send(int64_t sfd, const void * buf, int64_t msgLen, const void * svaddr)
{
    ssize_t result = sendto(sfd, buf, msgLen, 0, (struct sockaddr *) &svaddr, sizeof(struct sockaddr_un));
     perror("socket");
    if (result != msgLen)
        return -1;

    return result;
}

Here is how I call client_send from NASM:
mov rdi,[socket_client_fd]      ; int64_t sfd
lea rsi,[socket_buffer]     ; const void * buf
mov rdx,720             ; msgLen
lea rcx,[socket_server_addr]    ; (struct sockaddr *) &svaddr
mov r8,r15
call client_send wrt ..plt

The server socket is constructed like this:
int64_t * create_socket_server()
{
    struct sockaddr_un svaddr, claddr;
    int sfd, j;
    ssize_t numBytes;
    socklen_t len;
    char buf[BUF_SIZE];
    static int64_t retvals[2];

    retvals[0] = 0;
    retvals[1] = 0;

    sfd = socket(AF_UNIX, SOCK_DGRAM, 0); /* Create server socket */

    if (sfd == -1)
         return retvals;

    /* Construct well-known address and bind server socket to it */

    if (remove(SV_SOCK_PATH) == -1 && errno != ENOENT)
           return retvals;

    memset(&svaddr, 0, sizeof(struct sockaddr_un));
    svaddr.sun_family = AF_UNIX;
    strncpy(svaddr.sun_path, SV_SOCK_PATH, sizeof(svaddr.sun_path) - 1);

    if (bind(sfd, (struct sockaddr *) &svaddr, sizeof(struct sockaddr_un)) == -1)
           return retvals;

    retvals[0] = sfd;
    retvals[1] = (int64_t)&svaddr;

     return retvals;
}

At the point of the call to sendto, the two endpoints are connected because socket_server_fd (file descriptor) is 4 and  socket_client_fd is 5.
; Open the Socket Server
call create_socket_server wrt ..plt
mov rdi,rax
mov rax,[rdi]
mov [socket_server_fd],rax
mov rax,[rdi+8]
mov [socket_server_addr],rax

The socket server is initialized like this:
Open_Socket_Server:
call create_socket_server wrt ..plt
mov rdi,rax
mov rax,[rdi]
mov [socket_server_fd],rax
mov [rdi+8],rax
mov [socket_server_addr],rax

Debugging with gdb at the point of the call, perror returns "socket: Invalid argument."
The message being passed is a qword array of 90 elements (720 bytes).
I can't spot the invalid argument in the client_send code above.  Thanks for any help with this.


text:
Q: How to retrieve code from database with php ? I want to store HTML code in mysql database. If I want to store the following code into database

 this is a paragraph </p

they store as they are. But when I retrieve them and echo with php the tag get vanished. But I want to echo them as they are above. I also want to store and show not only HTML but other code (c,java,php) also. Anyone have any idea?

A: you can use htmlentities () php function to echo html codes
    $str = "

 this is a paragraph </p

";

echo htmlentities($str);

You can also use     htmlspecialchars();

A: You can use htmlentities($str) for that, another nice thing to use is

Putting those tags around the code will preserve newlines, tabs and spaces. In case you want to showcase it.


text:
Q: SQLite / Geopackage and saving Geometry in ArcGIS Has anyone successuflly created a layerfile (ArcGIS 10.4) to a dataset/table stored in a SQLite or Geopackage file?
Process of creating Layerfile: ArcMap TOC > Change Symbology > Right click > Create Layer file
It seems that everytime I drag in layerfile thats connected to either database, breaks or shows up but the attribue table wont work.
Adding the geometry straight in from either an SQLite of Geopackage doesnt seem to be an issue, its when I want to create symbology or categories that I would like saved for later use. Ideally I would like to create a layerfile for the Query Featureclass, though doesnt seem to ever want to work more than twice.
Seems to work no problem in QGIS as it looks better suppored, but ArcGIS is having a harder time using it.
Would love to hear from anyone who has done this succuessfully in ArcGIS 10.X


text:
Q: Appending items to list in for cycle I'm trying to append items to an empty list in for cycle:
pointList = {};
For[n = 1, n <= 10, n++, Append[pointList, {n, Sum[(-1)^(i + 1) * Binomial[n, i] * (n - i)! / n!, {i, 1, n}]}]];

But the pointList after the for loop is empty. What am I doing wrong? :(

A: you want AppendTo[], however you can do better here with a table :
pointlist=Table[{n, Sum[(-1)^(i + 1) * Binomial[n, i] * (n - i)! / n!, {i, 1, n}]},{n,10}]

A: Please note that by definition of the Binomial function Binomial[n,i]*(n-i)!/n!=1/i!. Moreover, the sum simplifies via FullSimplify[Sum[(-1)^(i+1)/i!,{i,1,n}],Assumptions->n>0] to 1-Subfactorial[n]/n!. Hence,
pointlist=Table[{n,1-Subfactorial[n]/n!},{n,1,10}]


text:
Q: Change another div's background color on click of div with angular2 I have a component on the page which has following divs

I have another div on the same page as

When i click on any of the div above, i want to get the selected color and apply as a background-color for the 2nd div.
How to do with angular2?

A: You can use the below code

 XYZ

blue

green

black

some text here

Typescript method
 readColor(value){
    this.color=value.srcElement.style['background-color'];
    console.log(value.srcElement.style['background-color']);
  }

LIVE DEMO


text:
Q: A weaker concept of graph homomorphism In the category $\mathsf{Graph}$ of simple graphs with graph homomorphisms we'll find the following situation (the big circles indicating objects, labelled by the graphs they enclose, arrows indicating the existence of a homomorphism):

Speaking informally, the "obvious" structural relatedness between the two circle graphs $C_3$ and $C_4$ reduces to its two common subgraphs $P_3$ and $P_4$, with $P_3$ being a subgraph of $P_4$.
But even though there is an "undeniable" structural relatedness between $C_3$ and $C_4$, there is no single graph homomorphism between the two. This in complete contrast to the category $\mathsf{Top}$, where they are even isomorphic. (Instead of this: no arrows between $P_i$ and $C_j$!)
But why is there no graph homomorphism between $C_3$ and $C_4$? There are two interrelated reasons:

*

*If all vertices of a graph were forced to have a self-loop, there would be a homomorphism from $C_4$ to $C_3$, since two adjacent vertices $x,y$ were allowed to be mapped onto the same vertex $f(x)=f(y)$. Furthermore, there would also be a homomorphism from $P_4$ to $P_3$.

*If one insists on graphs to be loop-less (as in topological graph theory?), one might instead weaken the definition of a graph homomorphism. Instead of defining $f:G\rightarrow G'$ to be a homomorphism when $(x,y) \in E(G)$ implies $(f(x),f(y)) \in E(G')$, one might define it like this:

$f:G\rightarrow G'$ is a (weak) homomorphism when $(x,y) \in E(G)$ implies  $f(x) = f(y) \vee (f(x),f(y)) \in E(G')$.

My questions are:

*

*In which contexts does this definition of a (weak) homomorphism between simple graphs have drawbacks other than not being standard, e.g. technical ones?

*Is there a known or imaginable "problem" that might be easier to handle with weak homomorphisms (other than the missing homomorphism between $C_4$ and $C_3$ which isn't really a problem)?

*Might weak homomorphisms be conceptually more appropriate, i.e. catch the "meaning" of structure preserving better?

*Where can I find weak homomorphisms in the literature, maybe under another name?

A: What you call a weak homomorphism is just a simplicial map where we view graphs as 1-dimensional simplicial complexes. In my opinion these are very natural and important outside of the coloring context. Here are my reasons:

*

*The endomorphism monoid is much richer if you allow simplicial maps. The endomorphism of the complete graph are only automorphisms under the rigid definition. Using simplicial maps it is all maps on the vertices.

*You cannot contract a spanning tree with the rigid definition.

*I defined orbital graphs for transformation monoids to generalize D. Higman's theorem but the monoid must be allowed to crush edges for it to work.
Adding loops is not a good solution in my opinion because it changes the fundamental group and homology. For instance, if a monoid acts on a graph by simplicial maps, then the chain groups become modules. Adding loops gives the wrong effect since crushing an edge should give the zero map.

A: What you are describing is sometimes goes under the phrase reflexive vs. irreflexive graphs. What you seem to be describing are two categories:

*

*Irreflexive graphs: the objects are sets with irreflexive symmetric relations, the morphisms are relation-preserving functions on the underlying sets.

*Reflexive graphs: the objects are sets with reflexive symmetric relations, the morphisms are relation-preserving functions on the underlying sets.
It is fun to compute cartesian products in both of these and to discover the two well-known kinds of graph products. Graph theorists could benefit from a bit of category theory.
There are actually many variations on categories of graphs. Here are some others.
Graphs as relations
The categories of relations and relation-preserving functions are categories of simple graphs. We can require various additional properties. Symmetric relations give us symmetric graphs, reflexive relations give us graphs in which morphisms are allowed to squish edges, etc.
Directed graphs
This is perhaps the most straightforward example. Let $\mathcal{C}$ be the category with two objects, called $\mathsf{E}$ and $\mathsf{V}$ and two arrows $\mathsf{s}, \mathsf{t} : \mathsf{E} \to \mathsf{V}$. Then the (covariant) presheaf category $\mathbf{Set}^\mathcal{C}$ is just the category of directed graphs. An object of the category can be viewed as a pair of sets $(E, V)$ together with two maps $s, t : E \to V$.
Reflexive directed graphs
We can play with directed graphs. For example, if we add an arrow $\mathsf{r} : \mathsf{V} \to \mathsf{E}$ which is a common right inverse of $\mathsf{s}$ and $\mathsf{t}$, we obtain directed graphs with chosen loops.
Symmetric graphs
Another option is to add an arrow $\mathsf{o} : \mathsf{E} \to \mathsf{E}$ satisfying $\mathsf{t} \circ \mathsf{o} = \mathsf{s}$ and $\mathsf{o} \circ \mathsf{o} = \mathsf{o}$ (yes, I am using different kinds of circles on purposes to confuse you). The presheaf category then corresponds to directed graphs in which each edge $e : a \to b$ has an opposite $o(e) : b \to a$, and "opposite" is an involution. It may happen that a loop is its own opposite.
Graphs as monoid actions
To get more fun out of categories of graphs we can do the following. Let $M$ be the monoid of functions $\lbrace 0, 1 \rbrace \to \lbrace 0, 1 \rbrace$. There are four elements, the identity $1$, the map $t$ which swaps $0$ and $1$, and the two constant maps $0$ and $1$. The category of right $M$-actions can be seen as a category of graphs.
Suppose $(X, m : X \times M \to X)$ is a right action on $X$. This is a graph in the following sense. The vertices are those elements of $X$ that are fixed by the action of $0$, or equivalently by the action of $1$. We do not have edges, but rather "half-edges". A half-edge is an element of $X$ which is not a vertex. Each half edge $e$ has its mate $e \cdot t$, and together you can think of them as a wholesome edge (unordered). A half-edge $e$ is attached to the vertex $e \cdot 0$, while its mate is attached to $e \cdot 1$.
We almost get the usual symmetric (non-simple) graphs, except that there can be degenerate half-edges that are their own mates (and therefore necessarily loop-like).
The relevant reference for this answer is Bill Lawvere's Categories of spaces may not be generalized spaces as exemplified by directed graphs.


text:
Q: How do I run a query in Cloud Spanner and download the results to a pandas DataFrame? I have a tool that processes data in-memory with pandas DataFrames, and I'd like to be able to use Spanner as a data source for some of that processing. How can I use Python to run a query in Spanner and then download all the query results to a pandas DataFrame?

A: A quick and dirty way to get spanner results into a pandas data frame.
import pandas as pd
from google.cloud import spanner

# Initialize client
client = spanner.Client()

# Get a Cloud Spanner instance by ID.
instance = client.instance('instance-name')

# Get a Cloud Spanner database by ID.
database = instance.database('database-name')

with database.snapshot() as snapshot:
    result = snapshot.execute_sql("SELECT * FROM somewhere")

    # Stream in rows
    rows = list()
    for row in result:
        rows.append(row)

    # Get column names
    cols = [x.name for x in result.fields]

    # Convert to pandas dataframe
    result_df = pd.DataFrame(rows, columns = cols)

This likely won't scale and you may run into issues with Spanner types vs pandas types, but it will solve the immediate problem of "I want to analyze data from Spanner in pandas."

A: Pandas lib is using sqlalchemy, so we can use this doc: https://cloud.google.com/spanner/docs/use-sqlalchemy
pip install sqlalchemy-spanner

then in python code (if sqlalchemy version >= 1.4):
import pandas as pd

url = 'spanner+spanner:///projects/project-id/instances/instance-id/databases/database-id'
sql = 'SELECT * FROM my_table;'

df = pd.read_sql(sql, url, index_col='id_column')

or in case it's sqlalchemy version 1.3:
...
url = 'spanner:///projects/project-id/instances/instance-id/databases/database-id'
...

A: To use Python to query your data in Cloud Spanner yoou need to install and use the Python Cloud Spanner client library.
As of now there is no a straightforward way to download data from Spanner to Pandas DataFrame.
I would suggest to use the "StreamedResultSet API" to export your data to Pandas.
Also please take a look at this post about streaming data from Cloud Spanner to Panda dataframe, as it may be proven helpful implementing your use case as well.


text:
Q: React Native - Send Cookies to WebView So there's a very simple example in the documentation that shows how you can pass cookies to a Webview:
const App = () => {
  return (
    <WebView
      source={{
        uri: 'http://example.com',
        headers: {
          Cookie: 'cookie1=asdf; cookie2=fdsa; cookie3=aaaa',
        },
      }}
    />
  );
};

How can I pass some attributes to each cookie?
If I open the Console in Google Chrome I can paste the following:
document.cookie ='cookie1=asdf;domain=.mydomain.com;path=/;'
document.cookie ='cookie2=fdsa;domain=.mydomain.com;path=/;'
document.cookie ='cookie3=aaaa;domain=.mydomain.com;path=/;'

This sets 3 cookies in the browser. Which is cool. If I try in React Native
const App = () => {
      return (
        <WebView
          source={{
            uri: 'http://example.com',
            headers: {
              Cookie: 'cookie1=asdf;domain=.mydomain.com;path=/;cookie2=fdsa;domain=.mydomain.com;path=/;cookie3=aaaa;domain=.mydomain.com;path=/;',
            },
          }}
        />
      );
    };

this will probably set 5 different cookies in the WebView: cookie1, cookie2, cookie3, domain, path