text:
Q: How do I record audio on Android and change the pitch? I am trying to learn Android Development and I was wondering how I can capture audio from a microphone and then change the voice in the audio so that it sounds thicker or sharper etc.
In short: How do I record and change the parameters of a sound? (In java, of course)

A: I'm actually working on an android app that involves audio. Recording the audio is the easy part, and you can mostly copy my code for that. Writing an audio filter is a much harder task, and requires knowledge of digital signal processing and the Fast Fourier Transform (FFT)
You could start by reading about audio processing in java here.
Meanwhile, here's the code to record audio on android:
public String record() {

                // please note: the emulator only supports 8 khz sampling.
                // so in test mode, you need to change this to
                //int frequency = 8000;

                int frequency = 11025;

                int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
                int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
                File file = new File(Environment.getExternalStorageDirectory()
                                .getAbsolutePath() + "/reverseme.pcm");

                // Delete any previous recording.
                if (file.exists())
                        file.delete();

                // Create the new file.
                try {
                        file.createNewFile();
                } catch (IOException e) {
                        throw new IllegalStateException("Failed to create "
                                        + file.toString());
                }

                try {
                        // Create a DataOuputStream to write the audio data into the saved
                        // file.
                        OutputStream os = new FileOutputStream(file);
                        BufferedOutputStream bos = new BufferedOutputStream(os);
                        DataOutputStream dos = new DataOutputStream(bos);

                        // Create a new AudioRecord object to record the audio.
                        int bufferSize = 2 * AudioRecord.getMinBufferSize(frequency,
                                        channelConfiguration, audioEncoding);
                        AudioRecord audioRecord = new AudioRecord(
                                        MediaRecorder.AudioSource.MIC, frequency,
                                        channelConfiguration, audioEncoding, bufferSize);

                        short[] buffer = new short[bufferSize];
                        audioRecord.startRecording();

                        Log.e(tag, "Recording started");

                        long start = SystemClock.elapsedRealtime();
                        long end = start + 15000;
                        while (SystemClock.elapsedRealtime() < end) {
                                int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
                                for (int i = 0; i < bufferReadResult; i++)

                                        if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
                                                dos.writeShort( EndianUtils.swapShort(buffer[i]));
                                        } else {
                                                dos.writeShort( buffer[i] );
                                        }
                        }

                        Log.e(tag, "Recording stopped");

                        audioRecord.stop();
                        bos.flush();
                        dos.close();
                        isRecording = false;
                        return file.getAbsolutePath();

                } catch (Exception e) {
                        Log.e(tag, "Recording Failed:" + e.getMessage());
                        throw new RuntimeException("Failed to create " + e.getMessage());

                }
        }

A: You can use Android SoundPool to chnage the pitch of audio file check answers of THIS question.
And to record audio when someone speaks near MIC check this LINK.


text:
Q: Android, YUI, Moodle The problem I'm having is the following:
I have an app with two separate modes: A WebView for browsing and a custom Canvas. The custom Canvas captures handwriting samples for language placement exams. Here's how it works. A user logs in to Moodle via the WebView. After they log in, they navigate to a Quiz inside Moodle. They click a link on one of the Quiz's questions and this launches an Intent which hides the WebView and shows the Canvas. The user then writes (using a stylus) on the Canvas. When a user is finished writing their essay (or whatever), they press a button that uploads an image file to Moodle. I am able to upload images to a point, it's getting them to show up in the HTML page that the user clicked the link in originally (see above) and to get Moodle to commit them to permanent storage that is the problem. Normally this is all accomplished through AJAX (really AJAJ since it's JavaScript and JSON) and when the user drops a file on this one component, the component refreshes and uploads the file.
Here is the problem: I need the WebView so that students can log in to Moodle through Shibboleth. But because the underlying JavaScript in the browser makes AJAX calls to the Moodle server and since the Java side of Android doesn't have access to the DOM, I have use the Apache HTTP components library to make some of the connections below basically to preserve the state of the HTML page in WebView.
In a desktop browser on, say, Windows, I use WebScarab to monitor the browser's requests and this is what I see: the browser uploads a file to Moodle via five successive calls to the following scripts:

*

*POST https://[moodle website]/repository/repository_ajax.php [posts multipart form data]

*POST https://[moodle website]/repository/draftfiles_ajax.php [posts some params]

*GET https://[moodle website]/draftfile.php/[some_id]/user/draft/[some_id]/[somefilename.png] [returns an icon of the image for a filepicker from YUI]

*POST https://[moodle website]/mod/quiz/processattempt.php [returns HTML page]

*GET https://[moodle website]/mod/quiz/summary.php [returns HTML page]

Some of these scripts return, as you'd expect, JSON data since they're AJAX and not HTML. The final two calls (4 & 5) return HTML. Now, I can make all of those calls in succession in either the WebView or the Apache HTTP library, but if I do so with WebView, only JSON data is returned to the WebView in calls 1-3 (WebView treats the JSON data as a page and displays it wiping out whatever HTML page was displayed in it). If I capture and process the JSON data using the Apache HTTP library in Java, then the JavaScript components internal to the page do not get updated. If I split the calls so that I send only calls 4 & 5 to the WebView, the HTML merely returns WebView to the first question of the exam and Moodle acts as if I haven't uploaded anything.
I can verify that files are uploading if I manually refresh (press a link) the JavaScript UI elements in the page. I can't expect students to do this, though, because the link to do so is very tiny and it's not obvious that it does a refresh. I need a way to programmatically refresh this one element (it's part of YUI) or to get Android and the Java side to play more nicely with the JavaScript/DOM side.
My question is: does anyone know a way to 1) fire off a drag and drop event using YUI to an element inside an HTML page or 2) a way to consume the JSON data and pass it to an element inside the HTML page.
I'm banging my head against a wall trying to figure this out.

OK, so I figured out that: javascript:document.getElementsByClassName(\"[name of link here]\")[0].click() works in Chrome on the desktop but doesn't work if I pass it to WebView.loadURL(). I just need to be able to simulate that click event reliably in WebView. It appears not to support click(). Anyone have any ideas?

A: The winning code is:
el = document.getElementsByClassName("[some element]")[0];
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, true);
el.dispatchEvent(event);

This selects the link at [some element] and thereby fires an AJAX request that refreshes the FilePicker. For those working with Moodle, I had to add the above code to the same quiz question that handles so it is invoked by putting that code in its own function and calling it with WebView.loadURL("javascript:myRefreshFunction()").

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the missing field from a mongo record I have the data in my record:
{
"test" : "388383",
"geo1" : "[-75.603554,35.888575]",
"zip" : "[27959]"
}

var det = new Schema({  test: String})

I have zip field in my record but when I console it its not coming up.
Data.find({}).exec(function(err,data){
      console.log(data[0].zip)  ------> 'undefined'
      console.log(data[0].geo1) ------> "[-75.603554,35.888575]"

});

I did not declared it in my model (both the fields) but I an get geo1 not zip.

A: Have your schema defined completely.
instead of this
  var det = new Schema({  test: String})

try
  var det = new Schema({  test: String,geo1:[Number],zip:[Number]});

Because if you wont have your schema defining each and every field, you wont be able to fetch all the data from a collection of a DB.


text:
Q: How to disable all the TextBox in GroupBox in vb.net form I have a vb.net form in which i added a GroupBox including 10 TextBox. I want to disable 9 TextBox at the load time and a single TextBox should be enable.

A: Normally you would be required to show what you have tried. Next time please do that.
Create an array of the text boxes you want to disable. Then loop to the array setting each box's enabled property to False.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim boxes = {TextBox1, TextBox2}
    For Each tb In boxes
        tb.Enabled = False
    Next
End Sub


text:
Q: INS-30131 Initial setup required for the execution of installer validations failed i just uninstall oracle 12c manually on windows 10 and now am reinstalling it shows errors:

Cause - Failed to access the temporary location. Action - Ensure that
  the current user has required permissions to access the temporary
  location. Additional Information:
   - Framework setup check failed on all the nodes
   - Cause: Cause Of Problem Not Available
   - Action: User Action Not Available Summary of the failed nodes desktop-81i87ss
   - Version of exectask could not be retrieved from node "desktop-81i87ss"  - Cause: Cause Of Problem Not Available
   - Action: User Action Not Available

A: In some cases, there is a possibility that your computer name contains some special character, unique installer throws same error in that case. Try removing any special character by renaming your system to a new name and then try installation again.
For Example: My system had name "LAPTOP-GENCONIAN". Problem was solved for me after renaming to "GENCONIAN"

A: I come across similar issue and was able to resolve with this method

*

*Open CMD

*CD into the folder in which  setup file exits

3.Run the command -   setup.exe -ignorePrereq -J"-Doracle.install.client.validate.clientSupportedOSCheck=false"

*Now the intallation window will open without validation check and you can continue


text:
Q: Python read website data line by line when available I  am using urllib2 to read the data from the url, below is the code snippet :
data = urllib2.urlopen(urllink)
for lines in data.readlines():
  print lines

Url that I am opening is actually a cgi script which does some processing and prints the data in parallel. CGI script takes around 30 minutes to complete. So with the above code, I could see the output only after 3o minutes when the execution of CGI script is completed.
How can I read the data from the url as soon as it is available and print it.

A: Just loop directly over the file object:
for line in data:
    print line

This reads the incoming data stream line by line (internally, the socket fileobject calls .readline() every time you iterate). This does assume that your server is sending data as soon as possible.
Calling .readlines() (plural) guarantees that you read the whole request before you start looping, don't do that.
Alternatively, use the requests library, which has more explicit support for request streaming:
import requests

r = requests.get(url, stream=True)

for line in r.iter_lines():
    if line: print line

Note that this only will work if your server starts streaming data immediately. If your CGI doesn't produce data until the process is complete, there is no point in trying to stream the data.


text:
Q: Incoherencia de tipo y metodo Buenas tardes llevo varios dias con este problema y no puedo resolverlo, este es mi codigo, me marca que el apartado
public UserController es menos accesible que el metodo IUserService le agradeceria si alguien pudiera ayudarme
public class UserController : ControllerBase
{
    private IUserService _userService;

    public ***UserController***(IUserService userService)
    {
        _userService = userService;
    }

A: El constructor de UserController es público (public) pero recibe un parámetro de tipo IUserService que es privado (private), posiblemente sea una clase anidada.
Dado que privado (private) es menos accesible que público (public) el compilador se queja; para solucionarlo IUserService debe ser igual o más accesible que UserController.


text:
Q: Oracle find record if the given date is within the range I need to get the daily schedule for the tasks done by people.
The data in my db is stored like this
sno | start_date_time       |  end_date_time      |
---------------------------------------------------
1   |06-10-2016 09:30:00    | 06-10-2016 17:00:00 |
2   |12-10-2016 08:00:00    | 15-10-2016 13:00:00 |

My question is if i give a date for  example 14-10-2016 I would like to get the second record.
I dont know how to query it since the given date does not fall into start_date_time or end_date_time
Is it possible to do that in oracle?

A: Try between
select * from your_table
    where your_date between start_date_time and end_date_time

Example:
select * from (
    select '2016-01-05' as t1, '2016-02-05' as t2
    union all
    select '2016-05-05' as t1, '2016-08-05' as t2
  ) a
  where '2016-02-01' between t1 and t2

gives
t1          t2
2016-01-05  2016-02-05

Of course this also works not only for dates but also for timestamps.
Keep in mind that when comparing dates and timestamp the date is casted as a
timestamp like this '2016-01-01' -> '2016-01-01 00:00:00'

A: Usually start and end dates allow null values, so apart from between in PhillipsD answer you might also need nvl:
select * from your_table
where your_date between nvl(start_date_time, your_date) and nvl(end_date_time, your_date)


text:
Q: Telnet client console: SEND invalid command - Only for Spanish version I've developed an application in QT C++ (server with listening sockets) waiting for clients to connect and send commands.
It was developed and tested in Windows XP Professional Version 2002 SP3 English version and tested in Windows seven 64 bits using telnet client sending strings to server from command prompt using reserved word SEND without problems.
Actually I am testing this app from another Windows XP Professional Version 2002 SP3 Spanish version machine and I'm having problems with sending strings.
Telnet client connects correctly, receives data from server, but when I move to command prompt and try to send strings I receive and error.
Microsoft Telnet> send MYSTRING
Invalid command. type ?/help for help
Microsoft Telnet> ?
Commands may be abbreviated. Supported commands are:
c – close close current connection
d – display display operating parameters
o – open hostname [port] connect to hostname (default port 23).
q – quit exit telnet
set – set set options (type 'set ?' for a list)
sen – send send strings to server
st – status print status information
u – unset unset options (type 'unset ?' for a list)
?/h – help print help information
Microsoft Telnet> d
Escape Character is 'CTRL+}'
Will auth(NTLM Authentication)
Local echo off
New line mode – Causes return key to send CR & LF
Current mode: Console
Will term type
Preferred term type is ANSI
Note: Above transcription is translated, I get this message in Spanish
I need to know if this problem, telnet not recognizing a reserved word is a configuration or security problem.
Windows Firewall is deactivated.
EDIT1:
To clear situation on problem with Telnet Client:
I develop an App in Windows XP 2002 SP3 English version. This app is a server in a network listening in port 6000. Waits for clients to connect (through Telnet client for example) over lan.
The pc running my app has IP1 and its working.
From PC2 with same os I connect using >telnet IP1 6000 and after I connect and receive data from my app (server). Then I press 'ctrl+}' and get to Telnet prompt Microsoft Telnet> send AnyString AnyString has been sent to server. My app receives data correctly, process it and works fine.
From PC3 using W7 and Ubuntu virtual machines, same procedure than PC2 and it works fine.
From PC4 os Windows XP SP3 2002 Spanish i connect using >telnet IP1 6000 and after I connect and receive data from my app (server). Then I press 'ctrl+}' and get to Telnet prompt Microsoft Telnet> send AnyString Invalid command. type ?/help for help
That's why I suppose Telnet client on XP can be "configured?"

A: To send a text message over TCP/IP using telnet client you need just to call telnet with address (and port if not default 23 should be used), i.e:
> telnet 192.168.1.1 13   // tell me your time
> string to be sent       // type windows's enter
>                         // should be sent as a text to 192.168.1.1 on port 13

when i move to command prompt and try to send strings i receive and
  error.
Microsoft Telnet> send MYSTRING
Invalid command. type ?/help for help

The command is named sen,  not send. Maybe a send is also sen but in help only sen is showed so better stick with it.
You can move to telnet mode by typing escape character that might be i.e. '^]' then type sen:
> telnet 192.168.1.1 13
> ctrl+]
Microsoft Telnet> sen my string here
>                         // should be sent as a text to 192.168.1.1 on port 13

Microsoft telnet client sen command terminates strings with null: when you type 5 characters p i o t r it terminates these 5 bytes with 00 byte ( '\0')  so there are 6 bytes sent:
p  i  o  t  r  .
70 69 6f 74 72 00

In case of problems with Microsoft Telnet you can always install a putty or write a simple telnet client:
void
str_cli(FILE *fp, int sockfd) {
    char buf[MAXLINE];
    int n;

    for ( ;;) {
        if ((n = Read(fileno(fp), buf, MAXLINE)) < 0) {
            err_quit("str_cli:");
        }
        Writen( sockfd, buf, n);
    }
}

int main( int argc, char** argv) {
    int         sockfd;
    struct sockaddr_in  servaddr;

    if (argc != 2)
        err_quit("usage: tcpcli <IPaddress>");

    sockfd = Socket(AF_INET, SOCK_STREAM, 0);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons( SERV_PORT);
    Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

    Connect(sockfd, (SA *) &servaddr, sizeof(servaddr));

    str_cli( stdin, sockfd);        /* do it all */

    close( sockfd);

    exit(0);
}


text:
Q: Toggle CoreLocation using Swift I'm trying to toggle CoreLocation on and off when you press a button in my swift app. When the app loads, this is how I turn it on
let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()

if CLLocationManager.locationServicesEnabled() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()
}

This works great. It prompts the user and then updates my location on the map. However, if you were to choose "No" when it requests, I want to be able to then turn it back on again. I thought this would be as easy as just requesting for authorization again but it isn't working. I have a method that gets called when a button is pressed to turn the location on.
The code for this method is essentially exactly the same. Is there something different I need to do once the authorization status has been set initially?

A:
if you were to choose "No" when it requests, I want to be able to then turn it back on again

Once the user has chosen to refuse you authorization, you cannot magically contradict the user, and (alas) you cannot make the system's authorization dialog appear ever again.
The best you can do is put up your own dialog (i.e. an alert) begging the user to go to Settings and flip the switch to give you authorization. You can even take the user to Settings (new in iOS 8). But you can't get that system authorization dialog again.


text:
Q: How to execute a command when a player is at a specific coordinate? (1.14+) How do i execute a command whenever a player is at a specific coordinate in 1.14+ Minecraft commands?
Im trying to execute a tellraw when they are at a specific coordinate
I tried doing this in a repeating/always active/unconditional command block
 execute if entity @p positioned x y z
then i would put a comparator for power to the impulse/need redstone/unconditional command block with the command
tellraw @p "Example"
but nothing would happen.
I tried putting the tellraw with the execute command block but it would just repeat the tellraw, or making the command block not on repeat does nothing.

A: execute if entity @p[x=87,y=77,z=20,dx=0,dy=0,dz=0] run tellraw @p "Example"

This will run if the player is in the 87, 77, 20 block.


text:
Q: Assembly -- syscall write returning -38, no output I'm trying to learn some assembly, and I'm starting out by outputting text to the screen. I'm starting to think it might be my environment and/or compilation: by now, I'm so frustrated that I've literally copy-pasted assembly code but it just won't call the system calls. Here is the source code (mainly adapted from https://en.wikibooks.org/wiki/X86_Assembly/Interfacing_with_Linux)
.section .data
msg: .ascii "Hello World\n"
.section .text

.global main
main:
    movq $1, %rdi   # write to stdout
    movq $msg, %rsi # use string "Hello World"
    movq $12, %rdx  # write 12 characters
    syscall         # make syscall

    movq $60, %rax  # use the _exit syscall
    movq $0, %rdi   # error code 0
    syscall         # make syscall

I'm on a 64-bit machine running Kali Linux, and am compiling with GCC. Like so:
gcc -c test.s
gcc test.o -no-pie

I've debugged the program with GDB and the syscall instruction always sets the eax register to 0xffffffffffffffda (-38) which does not seem right...
Can anyone give an insight?

A: Syscalls usually return a negative value in case of error, the absolute value being the errno value itself.
In your case 38is ENOSYS: Function not implemented.
But what syscall function are you calling? Let's see, the function number is stored into rax (eax in 32-bits) before issuing the syscall and your program loads... nothing!
It looks like you lost one line in your copy/paste:
movq $1, %rax   ; use the write syscall

A: Your code is missing the first instruction from the sample code:
movq $1, %rax   ; use the write syscall

Without this code, it ends up executing an unexpected (and probably invalid) system call, based on whatever happened to be in %rax when main was called.


text:
Q: apache runs on a different version then shown and shows/uses a wrong version of php I am having a strange problem with PHP on a raspberry Pi lately.
It occurred as i tried to run the "password_hash" function and wonderd why it didn't work. The script didn't even throw an error or something, it just didn't continue.
The specs first:

*

*PC = Raspberry Pi I

*OS = Raspbian

*Installed Apache Version = 2.4.12

*Installed PHP Version = 5.6.15

All these specs are coming from the console.
So it turned out, that the PHP version used by apache is different from the one i got from the console. Installed is PHP 5.6.15 but used is (acording to phpinfo() ) PHP 5.4.45. The php.ini is correctly located.
The more weird part is, that the apache version (also acording to phpinfo() ) seems to be Apache/2.2.22 (Debian) and i can't figure out why.
So intuitive i removed and reinstalled php and apache, checked the versions in the console, where it was correct (again), run another script with only phpinfo() and got the same sobering results. I also tried to install it manualy. And to get this out of the way, i did not upgrade the PHP version, it was a clean install on a clean, recently installed OS.
Had any of you ever run into something similar and knows a way to fixed it?


text:
Q: Invalid literal for int - Getting raw data from CSV file I have a CSV file where one of their lines is a list of strings:
['1', '2', '3', '4']

I read through the file like this:
data = sys.argv[1]
with open(data, 'rb') as csvfile:

    query = csv.reader(csvfile, delimiter=',', skipinitialspace=True)

    for row in range(23):
            if row == 1:
            date = next(query)
        elif row == 11:
            cores = next(query) # Problem in this line
        elif row == 13:
            time_interval = next(query)
        elif row == 17:
            number_cores = next(query)
        else:
            next(query)

But when I do this, I don't get the exact line. Instead I get:
["['1'", "'2'", "'3'", "'4']"]

This way, I have the problem that I can not convert each element into an int with map for example.
I get the following error:
ValueError: invalid literal for int() with base 10: 2['1'"

I supposed I need to get rid of the quotation marks "" and the first and last [] symbol. I have been trying, but with no success.
Hope I have explained myself correctly.
Thanks in advance.

A: Your CSV parser is (correctly) treating the square brackets and single quotes as part of the fields. The line you shared is a valid CSV line, but not in the way you want. The line you want is:
1,2,3,4

Note that there are no square brackets, and no quotes. For this row, your CSV parser would probably return the list:
['1', '2', '3', '4']

If you are unable to change the format of your input CSV, I would recommend not using a CSV parser.
Just to emphasize: the problem is likely in how the CSV is being created, not in how you are reading it.


text:
Q: Squash merge commit I have pull request on github to which I pushed some commits. It's been idle for some time and now it has merge conflicts.
So I merged my feature branch with the master branch, resolved the conflicts and pushed it.
Now I want to squash/remove the merge commit that has been created.
I tried git rebase -i but there are some commits between my last commit and the merge commit.
Any help is appreciated.

A: I think that you're on the right track, and now have 2 options Look at the picture:
A1 — A2 — A3 — A4
 \
  F1 — F2 — F3

where A1..A4 is the mainline of the project and F1..F3 is your feature branch submitted in the PR. Now however F3 can't be easily merged with A4 due to conflicting changes.
You could create merging commit F4:
A1 — A2 — A3 — A4
 \              \
  F1 — F2 — F3 — F4

and then submit F4 as PR. In this case the repo owner could take F4 and merge it to the mainline, so the project history will look like this:
A1 — A2 — A3 — A4 — A5
 \              \ /
  F1 — F2 — F3 — F4

Essentially, A5 sourcetree will be equal to F4 and in some workflows A5 is exactly F4.
Alternatively, you could checkout F3 (git checkout <feature_branch>; git reset --hard F3;) and then use git rebase -i A4 to reapply changes from your feature branch over the current project HEAD. You need to resolve all the conflicts one by one and in the end you'll get the following commits structure:
A1 — A2 — A3 — A4
                 \
                  F1' — F2' — F3'

and then you may forcibly update your repository fork with git push -f ... and then re-new the PR.


text:
Q: Conversion failed when converting date and/or time from character string I'm trying to execute the following query, and it shows me the error in the title,I'm not converting date or time here.Not sure why its showing the error.
select *
from [dbo].[Data]
where [Report Month] between '2015-05-01' and '2015-06-31'
  and [FTE Status]='Inactive'

Thanks in Advance!

A: There is no such day as June 31st.


text:
Q: How to use natural language processing to map text to a preset list of topics I'm interested in being able to use a service such as Google's Natural Language API to classify random user questions into a preset list of topics.  I have an advanced level of programming experience, and want to use Google's service as a base and if necessary build a codebase around it to accomplish our goal.  An example use case would be:
Hardcoded preset list of topics:
Baseball
Football
Soccer
Sample user questions and expected results:
How do I cook pasta?  RESULT: No results
What is a referee?  RESULT: Baseball/Football/Soccer
What is a home run?  RESULT: Baseball
1) Does anything like this already exist to classify random user text into preset list of topics?
2) If not, is there a programming concept that already exists that shows ways to implement this, or allow me to learn the concepts around this? (I searched on Google and couldn't find anything -- I may simply not know what to look for)
3) If not, any guidance on this could be implemented?

A: This sounds like a basic classification problem, or more specifically maybe intent classification.
Google has a guide to creating a classification program. You should start with that.
The output of the classifier there will give you a list of topics with a probability for each. If you want to allow multiple probabilities, which is harder to get right, you can take all topics with a probability above a threshold. You'll have to determine the threshold with experimentation.
The default model has a fixed list of categories, but this guide walks you through setting up custom categories.

If you are willing to look outside Google Cloud it may be easier to find guides to text classification. spaCy has an excellent guide you can use to get rolling quickly.


text:
Q: defer function if it's already running on statechange - js I feel like the answer is out there but I don't know what to look up.  I've looked into defer and promise but I'm not sure how to apply that if I want it to apply to itself.
If update_content() is running, I don't want it to be called again until it's finished the first time.
History.Adapter.bind(window, 'statechange', function() {

    var event_state = History.getState();

    // bad pseudo code
    if(update_content() is running, wait till it is finished(function() {
         update_content(event_state.data.html);
    }

});

As you can see by my horrible pseudo code, I want it to wait to run update_content() if it's already running. As soon as it's done, it will run again.  It takes 1-3 seconds to complete from fadeIn/Outs etc, and I want each statechange to wait till the previous request is complete.
There is no AJAX, by the way.  I want it to be synchronous in that sense.
How do I delay a function from running until its done running?
Here is the update_content() code:
// this function updates page content with ajax and cool effects!
function update_content(data) {
    if(data == null) return;

var id = $(data).prop('id'),
    content = "#" + id,
    header = 0;

    // if the header is full, header = 0.  if it's tiny, header = 1
    if($('#navbar.affix').length) { header = 1; }

    // if the page that needs to be loaded is NOT on the page
    // this could be #main, #content, etc
    if(!$(content).length) {
        $(data).hide().appendTo('#main_wrapper');
    }

    // show the homepage $('#main')
    // fades the content viewer out. no positioning is done on the homepage.
    if(id == "main") {

        if(header == 1) { $('body, html').scrollTop(55); } else { window.scrollTo(0,0); }

        $('#main').siblings(':visible').center(header); // puts visible content on TOP of page

        $('#main')// /.center(header)
            .show();  // home page goes behind content
        $('#main').siblings().fadeOut(600, function() { // fadeout content overlay, and ON COMPLETE
                $(this).hide(); // hide that shit
            });
        if(header == 1) { $('body, html').scrollTop(55); } else { window.scrollTo(0,0); }

        return;

}

    // show the content viewer $('#content')
    // fades content viewer in
    if(id = "content") {

        $('#content')
            .center(header) // place on top and center
            .fadeIn(function() { // fade in, and ON COMPLETE
                $('#main').hide(); // quickly remove siblings - DO NOT USE FADE
                $(this).uncenter(); // places it static so it is normal

                if(header == 1) { $('body, html').scrollTop(55); } else { window.scrollTo(0,0); }
        });

        return;
    }

}

A: First, you need to know when update_content() is done.  For that you can use some promises on your two animations and return a promise that is resolved when any animations started in this function are done (which could be immediately resolved if no animations are started):
// this function updates page content with ajax and cool effects!
// it returns a promise that is resolved when any animations started in this
// function are done
var updateRunning = 0;
function update_content(data) {
    if(data == null) [
        // return an already resolved promise
        return $().promise();
    }

    ++updateRunning;

    var id = $(data).prop('id'),
    content = "#" + id,
    header = 0, p1, p2;

    // if the header is full, header = 0.  if it's tiny, header = 1
    if($('#navbar.affix').length) { header = 1; }

    // if the page that needs to be loaded is NOT on the page
    // this could be #main, #content, etc
    if(!$(content).length) {
        $(data).hide().appendTo('#main_wrapper');
    }

    // show the homepage $('#main')
    // fades the content viewer out. no positioning is done on the homepage.
    if(id == "main") {

        if(header == 1) { $('body, html').scrollTop(55); } else { window.scrollTo(0,0); }

        $('#main').siblings(':visible').center(header); // puts visible content on TOP of page

        $('#main')// /.center(header)
            .show();  // home page goes behind content
        p1 = $('#main').siblings().fadeOut(600, function() { // fadeout content overlay, and ON COMPLETE
                $(this).hide(); // hide that shit
            }).promise();
        if(header == 1) { $('body, html').scrollTop(55); } else { window.scrollTo(0,0); }

    } else {

        // show the content viewer $('#content')
        // fades content viewer in
        if(id == "content") {

            p2 = $('#content')
                .center(header) // place on top and center
                .fadeIn(function() { // fade in, and ON COMPLETE
                    $('#main').hide(); // quickly remove siblings - DO NOT USE FADE
                    $(this).uncenter(); // places it static so it is normal

                    if(header == 1) {
                        $('body, html').scrollTop(55);
                    } else {
                        window.scrollTo(0,0);
                    }
            }).promise();

    }
    // note that either p1, p2 or both might be undefined here, but
    // $.when() should still work for us
    return $.when(p1, p2).always(function() {
        --updateRunning;
    });
}

FYI, I also changed if (id = "content") to if (id == "content") because I think what you had was a coding mistake.
Then, create a queue and a wrapper for update_content() that you call instead of update_content and the idea with this wrapper is that whenever update_content() finishes, it processes the next queued item.  You can tell if update_content() is running by maintaining a flag.
var queue = [];
function update_content_wrapper(data) {
    if (updateRunning !== 0) {
        // just queue the data if update already running
        queue.push(data);
    } else {
         update_content(data).always(function() {
             // if items in the queue, get the oldest one
             if (queue.length) {
                 update_content_wrapper(queue.shift());
             }
         });
    }
}

Then, you can just call the wrapper function on your statechange event and it will do all the dirty work for you:
History.Adapter.bind(window, 'statechange', function() {
    var event_state = History.getState();
    update_content_wrapper(event_state.data.html);
});

Anywhere else you were calling update_content(), you should switch it to calling update_content_wrapper().


text:
Q: PHP string comparison between two different types of encoding I am attempting to match a string I know to a web page title in php.
I have the following string:
ℛobinhood
I have a page title that looks like this:
ℛobinhood
but is actually encoded like this if I look at the <title> element:
ℛobinhood

I'm not sure how to compare these two strings. How do I either convert the ℛ to ℛ or the other way so that I can do a proper comparison?

A: Use the multibyte string functions:

*

*mb_convert_encoding() to convert both versions to something sane (UTF8, internal encoding)

*mb_strstr() to do the comparison

mb_* will have an encoding for HTML entities and (most likely) whatever encoding your string is in.

A: You can use htmlentites ( http://php.net/manual/en/function.htmlentities.php ) to convert to the entity version.


text:
Q: Create nested-list from unique values of first value I'm trying to make a list of mutations of genes.
For that, I made a list which contains lists of two values: Gene and Alteration, which results in this:
Gene_names = ['GPL2', 'GWEL', 'VREI', 'GPL2', 'GPL2', 'VREI']
Mutation_names = ['R278W', 'L72K', 'M939I', 'I354S', 'F472M', 'H8F']

my_list = []
for i in range(len(Gene_names)):
    my_list.append([Gene_names[i], Mutation_names[i]])

print(my_list)
[[GPL2, R278W], [GWEL, L72K], [VREI, M939I], [GPL2, I354S], [GPL2, F472M], [VREI, H8F]]

As you can see, some Gene names are repeated with new alterations. What I would like to get from this previous list is another list of lists with Genes and their Alterations, like so:
new_list = [[GPL2, R278W, I354S, F472M], [GWEL, L72K], [VREI, M939I, H8F]]

In this manner, the inside lists are composed of 'First value = Gene_names', and 'Next values = Mutation_names'
That would be sort of ideal, for my particular purposes, but anything similar may also work.

A: As @PeterWood suggested in comment you could create dictionary to group items and later you can convert it to list.
You can use collections.defaultdict to make it simpler
from collections import defaultdict

my_list = [
    ['GPL2', 'R278W'],
    ['GWEL', 'L72K'],
    ['VREI', 'M939I'],
    ['GPL2', 'I354S'],
    ['GPL2', 'F472M'],
    ['VREI', 'H8F']
]

my_dict = defaultdict(list)

for gene, mutation in my_list:
    my_dict[gene].append(mutation)

print(my_dict)

Result:
defaultdict(<class 'list'>, {'GPL2': ['R278W', 'I354S', 'F472M'], 'GWEL': ['L72K'], 'VREI': ['M939I', 'H8F']})

And convert to list (I use [gene] to create list becaues all_mutations is also list)
result = [ [gene]+all_mutations for gene, all_mutations in my_dict.items() ]

print(result)

Result
[['GPL2', 'R278W', 'I354S', 'F472M'], ['GWEL', 'L72K'], ['VREI', 'M939I', 'H8F']]

Full example
from collections import defaultdict

my_list = [
    ['GPL2', 'R278W'],
    ['GWEL', 'L72K'],
    ['VREI', 'M939I'],
    ['GPL2', 'I354S'],
    ['GPL2', 'F472M'],
    ['VREI', 'H8F']
]

my_dict = defaultdict(list)

for gene, mutation in my_list:
    my_dict[gene].append(mutation)

print(my_dict)

result = [ [gene]+all_mutations for gene, all_mutations in my_dict.items() ]

print(result)

and the same with normal dict instead of defaultdict
my_list = [
    ['GPL2', 'R278W'],
    ['GWEL', 'L72K'],
    ['VREI', 'M939I'],
    ['GPL2', 'I354S'],
    ['GPL2', 'F472M'],
    ['VREI', 'H8F']
]

my_dict = dict()

for gene, mutation in my_list:
    if gene not in my_dict:
        my_dict[gene] = []

    my_dict[gene].append(mutation)

print(my_dict)

result = [ [gene]+all_mutations for gene, all_mutations in my_dict.items() ]

print(result)

EDIT:
Example using pandas and groupby
import pandas as pd

my_list = [
    ['GPL2', 'R278W'],
    ['GWEL', 'L72K'],
    ['VREI', 'M939I'],
    ['GPL2', 'I354S'],
    ['GPL2', 'F472M'],
    ['VREI', 'H8F']
]

# convert list to dataframe
df = pd.DataFrame(my_list, columns=['gene', 'mutation'])

print(df)

# group by `gene`
groups = df.groupby('gene')
# convert every group to list `all_mutations`
df_groups = groups['mutation'].apply(list).reset_index(name='all_mutations')

print(df_groups)

# convert two columns to one column
data = df_groups.apply(lambda row: [row['gene']] + row['all_mutations'], axis=1)
# convert dataframe back to list
result = data.to_list()

print(result)


text:
Q: AIC of a weighted cox regression model (coxphw) I have to compare three cox-regression models.
However, one of these violates the PH assumption. Stratfying the variable did not work because it is already categorical. Thus, weighted cox regression would be suitable.
I was wondering wether one can extract AIC of a coxphwmodel from the package coxphw?
Using extractAIC(model3)just gave 5.
Also, is it even possible to compare the models because they employ different methods?
Update:
I found this article by Smith, Betts, Forbes et al. (2011). They mention this article by Chou and Bentler (1996) and write

Because of the weighting, the weighted Cox hazards model is not a true likelihood approach; therefore, we used the Wald χ2 statistic as a large sample approximation to the likelihood, and used −χ2 + 2 * (number of parameters) of the model, as an approximation of AIC (Chou and Bentler 1996).

Any suggestions?

A: I don't think it's wise to compare standard Cox models with coxphw-weighted models via AIC. With AIC comparisons among models you need to watch out for possible offsets of reported AIC values by a constant. See the Wikipedia entry. Although I haven't thought this through carefully, I fear that the estimated likelihood implied in the work-around proposed by Smith et al might not be comparable to the partial likelihood from a standard Cox model, particularly with respect to that constant offset. You could examine that issue with models of simulated data, I suppose.
For comparing models with different predictors on the same data set, it's probably best to stick with the same model-fitting approach: all standard Cox or all coxphw. If proportional hazards hold for one Cox model then the coxphw weighting shouldn't matter, as the event-average (standard Cox) and weighted-average (coxphw) models should be pretty much the same. If PH doesn't hold for a Cox model it won't for the coxphw-weighted model either. You just get what might be considered a better "average HR" estimate--of something that, absent PH, isn't really an HR.


text:
Q: What does "desert island band" mean? What does "desert island band" mean? I've seen a lot of mentions of this term, but I've never found exact definition. They call a lot of bands that term. Black Sabbath, Misfits, Dare to Defy.

A: This probably has to do with the idea of a deserted island.

A desert island, deserted island or uninhabited island is an island that is not populated by humans. Uninhabited islands are often used in movies or stories about shipwrecked people, and are also used as stereotypes for the idea of "paradise".

This "desert island" is popular in hypothetical games where it is asked

If you were on a deserted island and you could on do/bring X number of things, what would you do/bring?

So in this instance, one example would be

If you were stuck on a deserted island, and you could only listen to one band for the rest of your life, which band would it be?

As you can image, many people would choose famous, successful bands like Black Sabbath and Misfits. So, you might call them "desert island" bands.
"Desert island" is not limited to bands. There are desert island books and even desert island celebrities.

Here is an example I found on Reddit:

Ever played the game "desert island"? Premise being that you're stuck on a desert island for an indefinite amount of time, and you can only bring a handful of items. I'm curious to know what you'd bring.
  Categories (answer all or some):

*

*You can bring 3 books.

*You can bring 3 movies.

*You can bring 3 food items.

*You can bring an ipod with 1 genre of music on it.

*You can bring 3 personal items (such as photos, things that are meaningful to you)

*You can bring 3 survival items (such as matches, etc)

*You can bring 1 person to keep you company (can be a celebrity, someone dead or alive, someone you know,


text:
Q: DNN Appplication_start in global.asax not firing I have configured some methods to be called in Application_start but Application_start does not seem to be firing at all. Any Info would be greatly appreciated.
I am using DNN 9
Thanks in advance!

A: have you recently done any renaming in your solution?
"clean solution" and "rebuild" doesn't delete assemblies
check Global.asax Inherits="" attribute
something old may be referenced.

A: DNN takes over the application instance and this is required for the functionality of DNN. Therefore you can't override Application_Start, it already overrides it with its own inherited class.
I would use an HTTPModule or create scheduled process with the DNN scheduler.
Check these blogs on how to use the HTTP Module which worked for me:
https://erraticdev.blogspot.com/2010/08/writing-ihttpmodule-thats-able-to.html
https://erraticdev.blogspot.com/2011/01/how-to-correctly-use-ihttpmodule-to.html


text:
Q: Circular ripple issue
*

*I am trying to create a circular ripple effect on a CircularProgressIndicator but ripple effect goes outside over the View.

*I want it to be on the CircularProgressIndicator and not going outside it. An help will be appreciated.

Here is my code:
 <RelativeLayout
                android:id="@+id/play_container"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toEndOf="@id/play_prev"
                android:background="@drawable/btn_ripple_circular">

                <com.google.android.material.progressindicator.CircularProgressIndicator
                    android:id="@+id/progress_circular"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentStart="true"
                    android:layout_centerVertical="true"
                    android:indeterminate="false"
                    android:max="100"
                    app:indicatorColor="@color/colorAccent"
                    app:indicatorSize="44dp"
                    app:trackColor="@color/colorAccentOpacity"
                    tools:progress="50" />

                <ImageButton
                    android:id="@+id/btn_play"
                    android:layout_width="32dp"
                    android:layout_height="32dp"
                    android:layout_centerInParent="true"
                    android:background="@color/colorTransparent"
                    android:clickable="false"
                    android:contentDescription="@string/cover"
                    android:focusable="false"
                    android:src="@drawable/ic_play"
                    app:tint="@color/colorAccent" />

            </RelativeLayout>

btn_ripple_circular.xml:
<?xml version="1.0" encoding="utf-8"?>

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/colorAccentOpacity"
    android:radius="36dp">

    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorAccentOpacity" />
            <corners android:radius="36dp" />
        </shape>
    </item>

    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <corners android:radius="36dp" />
            <solid android:color="@color/colorTransparent" />
        </shape>
    </item>
</ripple>

A: app:tabRippleColor="@color/transparent"


text:
Q: Conditionally coloring a cell in htmlTable for R I'm using the excellent htmlTable package for printing some results in rmarkdown. One of my tables shows values between 0 to 1. I have generated a vector of a 100 colors interpolated between white (#FFFFFF) and red (#FF5555) that I'd like to match to each cell's background depending on it's value.
The logical part is clear to me (multiply the cell's value by 100, than round and extract color from the corresponding index of the color vector).
What I'm not sure about is, having a matched a color for each cell, how do I make htmlTable to paint it?
Thanks!

A: I think you can do it using rgb colors
like:
paste0("background-color:RGB(255, ",value*255," , ",value*255 ," )"

where value its your cell value from 0 to 1
Example( 0 red,1 white)
 df = as.data.frame(matrix(round(runif(15, 0, 1), 1),ncol = 3 ))

htmlTable::htmlTable(df,css.cell=apply(df,c(1,2),function(i)paste0("background-color:RGB(255, ",round(i*255,0)," , ",round(i*255,0) ," )")))


text:
Q: JPA 2.0 metamodel in Netbeans? I've read that since version 6.9, Netbeans includes annotation processing support, a feature needed, for instance, to generate JPA 2.0 entities' metamodels.
However, I couldn't find any examples or documentation that shows exactly how to do it. Have any of you guys succeed on this?

A: I didn't experiment this feature in NetBeans 6.9 but according to the release notes (and to Bug 178108), my understanding is that this is supposed to work out of the box if you are using EclipseLink (and if you add eclipselink-jpa-modelgen.jar to the classpath):

Java Persistence
Creation of new persistence unit was
  simplified in all wizard, in Entity
  From Database wizard the most suitable
  persistence unit will be created by
  default.
Now metamodel classes will be
  generated for project entities if
  persistence unit will be created with
  eclipselink provider (supported in
  j2se, web, ejb and application client
  projects). Automatic processor
  addition is temporary disabled because
  of an issue in eclipselink, you can
  add eclipselink-jpa-modelgen jar from
  eclipselink distribution to your
  project manually to enable metamodel
  generation.
The entity from DB wizard was enhanced
  to allow regeneration. It allows user
  to regenerate the entity from scratch
  after structural DB change or update
  the entity class by adding the code
  for the new DB fields.

For other persistence providers, did you actually try to add their metamodel generator JAR and to declare the annotation processor as suggested in part I and part II of the link you provided?
Related question

*

*How to generate JPA 2.0 metamodel?

A: maven compiler plugin has problems with annotation processors. it's not straightforward to do with maven ans sometimes it fails. Applies not only to the JPA but also to netbeans' own annotations and processors that generate code. Even if not hit by any of the issues you might need to configure the compiler plugin to work with ann processors.. make sure to use the latest and greatest of m-c-p, some issues were fixed there.
http://jira.codehaus.org/browse/MCOMPILER-122
http://jira.codehaus.org/browse/MCOMPILER-97
http://jira.codehaus.org/browse/MCOMPILER-71
http://jira.codehaus.org/browse/MCOMPILER-66

A: Milos is correct - use the latest Maven compiler plugin, and also the latest EclipseLink. Plus, the eclipselink-jpa-modelgen.jar file must be in your dependencies.
The easiest way to set up the project is to download the latest nightly build of NetBeans 6.10 from http://bits.netbeans.org/netbeans/trunk/nightly/ and create the project in this build - everything should work well. Then you can continue editing this project in NetBeans 6.9.1.


text:
Q: Flutter equivalent of string validation on key up The scenario is as follows:
I have a TextFormField and a FlatButton. I want to enable the FlatButton only when the TextFormField is valid, and I would like to check the validation after each character is typed.
I am using a Form with a GlobalKey. I have tried using onChanged and the value that is passed to the callback function is correct, but for some reason the validation that occurs when I run $_globalKey.currentState.validate() is always one character behind. So to make it really simple, I only validated if the string was empty. When it was actually empty (after deleting the last character) validate() returned true but after typing one character it returned false.
Using autovalidate and that worked for the validation part alone but I don't know how to attach the enabling of a button to that. Does anyone know how to get validation to work "correctly" in this scenario? Thanks!

A: create a key for form
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

after add to addlistener this code.
if (!_formKey.currentState.validate())
{
    return;
}

this is your listener
myController.addListener((){
    setState(() {
        if(_isValidText(myController.text) && _formKey.currentState.validate())
            isValid = true;

        else
            isValid = false;
    });
});


text:
Q: Testing the parameters of a method in a factory Good morning,
I am trying to test the values of some fields of a method defined in a AngularJS's factory.
My code is the following :

'use strict';

services.factory('toto', ['$resource', function ($resource) {
    return  $resource('abc',
        {},
        {
            method1: {
                method: 'POST',
                url: 'urlXYZ'
            }
        })
}]);

I would like to check the value of method and url in method1.
I tried many things but none is ok :

beforeEach(function(){
    module('myApp');
});

describe('tests', function () {
    var toto;

    beforeEach(function () {
        inject(function (_toto_) {
            toto = _toto_;
        });
    });

    // check to see if it has the expected function
    describe('toto service has the expected properties', function() {

        it('should have a method1 function', function () {
            expect(angular.isFunction(toto.method1)).toBe(true);
        });

        it('should have a method1 function with the field method defined', function () {
            expect(toto.method1.url).toBeDefined();
        });

    });

});

It only says me that " Expected undefined to be defined." for the second test.
Do you have any idea of how I could manage to do whant I want ?
EDIT : I am not sure I was very understandable ...
What I want to do is checking the values of the url and method parameters of method1 in order to know if someone does not modify them by mistake.
EDIT 2 : Here is a solution with the help of qwetty.

it('should perform POST request to the expected url', function () {
            $httpBackend
                .expectPOST('the expected url')
                .respond({});
            toto.paginate();
            $httpBackend.flush();

        });

A: In test I would call "additional" method defined in Your $resource factory.
it('should perform POST request and method should be available', function () {
    $httpBackend
            .expectPOST('some expected url')
            .respond({}); // does not matter what You return here ...
    toto.method1();

});

A: As you can see, the resource object method toto.method1 is a function, not an object as you defined in $resource().
I think you can change the return of factory
services.factory('toto', ['$resource', function ($resource) {
    var action = {
         method1: {
            method: 'POST',
            url: 'urlXYZ'
        }
    };
    return  {
         resource: $resource('abc',{}, action),
         action: action
     };
}]);

Of course, you will also need to change the way you use the factory.
Or use defineProperty:
services.factory('toto', ['$resource', function ($resource) {
    var action = {
         method1: {
            method: 'POST',
            url: 'urlXYZ'
        }
    };
    var resource = $resource('abc',{}, action);
    Object.defineProperty(resource, 'method1', {
        value: action.method1
    });
    return resource;
}]);

Although it seems too much effort just for testing purpose. :)


text:
Q: Use JavaScript to automatically submit form I'm have a simple form, when clicking the submit button the backend php file gets executed by my JavaScript file, results are returned via ajax, everything works great when manually clicking the button. However, when trying to use javascript to automatically submit the form every 120 seconds it is not working. The javascript never get's called which in turn causes the php to not execute...
html
<form id="send-with-ajax" name="ping">
    <input type="submit" value="Execute Ping" />

</form>

Again, there are not issues with my portal.js file or my php file -- The main thing to note here is that the document.getElementById("send-with-ajax").submit(); does not do anything... Any ideas?

A: Try using the submit() method. Or use AJAX.

A: If you are doing things on onsubmit event, document.getElementById("send-with-ajax").submit() doesn't trigger this event.

A: Assuming that js\portal.js just executes a function when a POST event occurs, you could simply call that function from inside your interval.
If that won't work for some reason (maybe there's a lot of other stuff happening on your page that you didn't show us), and your call to submit() isn't working properly, you could also trigger a button click with $('input[type=submit]').click(); (assuming you only have one submit button on the page - otherwise add a class or an id and trigger on that instead).


text:
Q: How to create a trigger in such that entire old record (existing table) goes to another table before updates happen in the existing table I'm new to Postgres and trigger functions. I'm trying to create a trigger in postgres where the table schema_name1.table_name_abc gets inserted or updated every minute. Now before it gets inserted/updated, I want to capture the entire old records (including the newly inserted rows) and move it to another table schema_name1.table_name_xyz
Is it possible to move entire records before update happens also the newly inserted row to another table using trigger?
Below is the query that I'm trying to run. I'm unable to get any logic for the "Insert into" inside if conditions
CREATE OR REPLACE FUNCTION schema_name1.table_name_abc()
  RETURNS trigger AS
$BODY$
BEGIN
BEFORE UPDATE ON schema_name1.table_name_abc
FOR EACH ROW
BEGIN
    IF UPDATING THEN
        INSERT INTO  schema_name1.table_name_xyz VALUES(<no idea what to provide here>);
    END IF;
END;

BEFORE INSERT ON schema_name1.table_name_abc
FOR EACH ROW
BEGIN
    IF INSERTING THEN
        INSERT INTO  schema_name1.table_name_xyz VALUES(<no idea what to provide here>);
    END IF;
END;

$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION schema_name1.table_name_abc()
  OWNER TO sys_object_owner;

A: The values you need are available as OLD (eg: the value of FIELD_NAME is in OLD.FIELD_NAME).
See https://www.postgresql.org/docs/10/static/plpgsql-trigger.html (specifically, look at Example 42.4)


text:
Q: Как в PHP строку разбить на массив Как разбить строку:
|ele1||ele2||ele3||ele4||var5||nubmr|

На массив вида:
[0]=>ele1
[1]=>ele2
[2]=>ele3
[3]=>ele4
[4]=>var5
[5]=>nubmr

как вариант хотелось бы удалить первый и последний элемент строки с помощью preg_replace (не знаю как если знаете то подскажите)
а потом разбить через explode
A: .
preg_replace('/^\|(.+)\|$/','$1','|ele1||ele2||ele3||ele4||var5||nubmr|');

A: Проще.

explode('||', "ele1||ele2||ele3||ele4||var5||nub")

И потом удалить из массива


text:
Q: three.js yii2 widget not displaying Hie. I am trying to develop a simple three.js widget that I can use in my Yii2 project. The intention of creating the widget is to draw wireframes of (Nurbs based) IGES CAD models, for example:

This is screenshot of a wireframe displayed by the same app but using traditional php without any framework. I am refactoring this code using the yii2 framework. I followed a tutorial creating an advanced votewidget to code the widget and the folder structure is as follows:

The challenge I am facing is that the three.js canvas is not displayed. For the sake of testing I copied an example for drawing a cube from here into _igesdisplay.php view file so that i verify whether other code works but still nothing is displayed.
The code for the widget asset file: IgesDisplayWidgetAsset.php
<?php

namespace frontend\widgets\igesdisplaywidget;

use frontend\widgets\igesdisplaywidget\IgesDisplayWidget;

use yii\web\AssetBundle;

class IgesDisplayWidgetAsset extends AssetBundle
{
    public $js = [
        // 'js/votewidget.js',
        // 'js/three.js',
        'js/three.min.js',
        'js/curves/NURBSCurve.js',
        'js/curves/NURBSUtils.js',
        'js/renderers/Projector.js',
        'js/renderers/CanvasRenderer.js',
        'js/libs/stats.min.js',
        'js/controls/TrackballControls.js',
        'js/controls/OrbitControls.js',
        'js/Detector.js',
        'js/libs/stats.min.js',
    ];

    public $css = [
         // CDN lib
        'css/viewport.css'
    ];

    public $img = [
        // 'img/100.jpg'
    ];

    public $depends = [
        'yii\web\JqueryAsset'
    ];

    public function init()
    {
        // Tell AssetBundle where the assets files are
        $this->sourcePath = __DIR__ . "/assets";
        // echo $this->basePath;
        parent::init();
    }
}

Code for _igesdisplay.php
<?php

use yii\helpers\Html;

?>

<?= Html::encode($display->title) ?>

        <canvas id="debug" style="position:absolute; left:100px"></canvas>

code for : IgesDisplayWidget.php
<?php

namespace frontend\widgets\igesdisplaywidget;

use yii\base\Widget;
use yii\helpers\Html;

class IgesDisplayWidget extends Widget
{
    public $model;

    public function init()
    {
        parent::init();
    }

    public function run()
    {
         // Register AssetBundle
        IgesDisplayWidgetAsset::register($this->getView());
        return $this->render('_igesdisplay', ['display' => $this->model]);
    }
}
?>

code for the file that uses the widget : Display.php
<?php

use frontend\widgets\igesdisplaywidget\IgesDisplayWidget;

$cadModel = (object)['title'=> 'Model Wireframe', 'wireframe' => $edgetype];
?>

<?= IgesDisplayWidget::widget(['model' => $cadModel]) ?>

The viewport.css file contains a style for changing the cursor style.

cursor: crosshair;

When I hover over the left half of the web page the crosshair cursor is shown but no cube is displayed. If I open the view page source window I can access both js and css files so the IgesDisplayWidgetAsset.php code is ok. I would like to know what could be the problem.
Thanks in advance.


text:
Q: Meteor CollectionFS:S3 GraphicsMagick Does Not Resize Image I'm using Meteor-CollectionFS and GraphicsMagick 1.3.22 to resize an image uploaded to Amazon S3. The image does not resize, it just appears in S3 full-sized. I also tried putting the resized images in a seperate store, but the image still appeared full-sized in the new store.
Here is my server/collections.js
FS.debug = true;

var imageStore = new FS.Store.S3("images", {
    bucket: "meteor-s3-test-data",
    accessKeyId: "XXX",
    folder: "images",
    secretAccessKey: "XXX",
    transformWrite: createThumb
});

var createThumb = function(fileObj, readStream, writeStream) {
    gm(readStream, fileObj.name()).resize('100', '100').stream().pipe(writeStream);
};

ProfileCollection = new Mongo.Collection('ProfileCollection');

PhotoCollection = new FS.Collection("PhotoCollection",
{
    stores: [
        imageStore,
    ],
    filter: {
      maxSize: 3145728,
      allow: {
        contentTypes: ['image/*'],
        extensions: ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG']
      }
    }
});

and my client/collections.js
var imageStore = new FS.Store.S3("images");

ProfileCollection = new Mongo.Collection('ProfileCollection');

PhotoCollection = new FS.Collection("PhotoCollection",
{
    stores: [
        imageStore,
    ],
    filter: {
      maxSize: 3145728,
      allow: {
        contentTypes: ['image/*'],
        extensions: ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG']
      }
    }
});

and my FS.debug log
FileWorker ADDED - calling deleteChunks for i5BrCN6rZwLoPuXy4
Meteor._wrapAsync has been renamed to Meteor.wrapAsync
TempStore is mounted on storage.gridfs
FileWorker ADDED - calling deleteChunks for 8BFzyhkoLyE4RGPES
FS.HTTP.unmount:
{}
Registered HTTP method URLs:
/cfs/files/:collectionName/:id/:filename
/cfs/files/:collectionName/:id
/cfs/files/:collectionName
token: eyJhdXRoVG9rZW4iOiJyYmx0cFd3YzUxVUlqd0JfaVhrck1RSVdmbE5wRmFKdXZFYjZvRXBWek5kIn0=
GET FILERECORD: 8BFzyhkoLyE4RGPES
Read file "me.jpg" bytes 0-14428/14429
createReadStream images
createReadStreamForFileKey images
Insertion in security = true
token: eyJhdXRoVG9rZW4iOiJyYmx0cFd3YzUxVUlqd0JfaVhrck1RSVdmbE5wRmFKdXZFYjZvRXBWek5kIn0=
HTTP PUT (update) handler received chunk:  0
GET FILERECORD: eLdMFShwMftTZAL4r
Insertion in security = true
createWriteStream _tempstore, internal: true
createWriteStreamForFileKey _tempstore
SA GridFS - DONE!
-----------STORED STREAM _tempstore
-----------CLOSE STREAM _tempstore
TempStore progress: Received 1 of 1 chunks for me.jpg
UPDATE: {"$set":{"uploadedAt":"2015-10-30T01:02:35.356Z"},"$unset":{"chunkCount":1,"chunkSum":1,"chunkSize":1}}
me.jpg was successfully uploaded. You are seeing this informational message because you enabled debugging and you have not defined any listeners for the "uploaded" event on the PhotoCollection collection.
FileWorker ADDED - calling saveCopy images for eLdMFShwMftTZAL4r
saving to store images
createWriteStream images, internal: false
createWriteStreamForFileKey images
FS.TempStore creating read stream for eLdMFShwMftTZAL4r
createReadStream _tempstore
createReadStreamForFileKey _tempstore
GRIDFS { _id: 5632c1ab10a4ad2c48853ad5, root: 'cfs_gridfs._tempstore' }
FileWorker CHANGED - calling saveCopy images for eLdMFShwMftTZAL4r
saving to store images
createWriteStream images, internal: false
createWriteStreamForFileKey images
FS.TempStore creating read stream for eLdMFShwMftTZAL4r
createReadStream _tempstore
createReadStreamForFileKey _tempstore
GRIDFS { _id: 5632c1ab10a4ad2c48853ad5, root: 'cfs_gridfs._tempstore' }
FileWorker REMOVED - removing all stored data for 8BFzyhkoLyE4RGPES
---SA REMOVE
-----------FINISH STREAM images
-----------FINISH STREAM images
-----------FINISH STREAM images
-----------FINISH STREAM images
SA S3 - DONE!!
-----------STORED STREAM images
-----------STORED STREAM images
SA images stored PhotoCollection/eLdMFShwMftTZAL4r-me.jpg
FS.File._saveChanges: images
UPDATE: {"$set":{"copies.images":{"name":"me.jpg","type":"image/jpeg","size":14429,"key":"PhotoCollection/eLdMFShwMftTZAL4r-me.jpg","updatedAt":"2015-10-30T01:02:35.790Z","createdAt":"2015-10-30T01:02:35.790Z"}}}
FS.File._saveChanges: _original
UPDATE: {"$set":{"original":{"name":"me.jpg","updatedAt":"2015-10-23T19:33:23.512Z","size":14429,"type":"image/jpeg"}}}
me.jpg was successfully saved to the images store. You are seeing this informational message because you enabled debugging and you have not defined any listeners for the "stored" event on the PhotoCollection collection.
FileWorker ADDED - calling deleteChunks for eLdMFShwMftTZAL4r
---SA REMOVE
SA S3 - DONE!!
-----------STORED STREAM images
-----------STORED STREAM images
SA images stored PhotoCollection/eLdMFShwMftTZAL4r-me.jpg
FS.File._saveChanges: images
UPDATE: {"$set":{"copies.images":{"name":"me.jpg","type":"image/jpeg","size":14429,"key":"PhotoCollection/eLdMFShwMftTZAL4r-me.jpg","updatedAt":"2015-10-30T01:02:35.884Z","createdAt":"2015-10-30T01:02:35.884Z"}}}
FS.File._saveChanges: _original
UPDATE: {"$set":{"original":{"name":"me.jpg","updatedAt":"2015-10-23T19:33:23.512Z","size":14429,"type":"image/jpeg"}}}
me.jpg was successfully saved to the images store. You are seeing this informational message because you enabled debugging and you have not defined any listeners for the "stored" event on the PhotoCollection collection.
token: eyJhdXRoVG9rZW4iOiJyYmx0cFd3YzUxVUlqd0JfaVhrck1RSVdmbE5wRmFKdXZFYjZvRXBWek5kIn0=
GET FILERECORD: eLdMFShwMftTZAL4r
Read file "me.jpg" bytes 0-14428/14429
createReadStream images
createReadStreamForFileKey images
token: eyJhdXRoVG9rZW4iOiJDMTFjd3lwUnJVU3NKRlZNUXNodWxQblJScXkyOXFxZklZcjc4bVBTT2pJIn0=
GET FILERECORD: eLdMFShwMftTZAL4r
Read file "me.jpg" bytes 0-14428/14429
createReadStream images
createReadStreamForFileKey images
^C[ec2-user@ip-10-0-0-5 udormio_build]$ [ec2-user@ip-10-0-0-5 udormio_build]$ no bundle/main.js
FileWorker ADDED - calling deleteChunks for-bash: [ec2-user@ip-10-0-0-5: command not found
i5BrCN6rZwLoPuXy4
Meteor._wrapAsync has been renamed to Meteor.wrapAsync
TempStore is mounted on storage.gridfs
FileWorker ADDED - calling deleteChunks for 8BFzyhkoLyE4RGPES
FS.HTTP.unmount:
{}
[ec2-user@ip-10-0-0-5 udormio_build]$ FileWorker ADDED - calling deleteChunks for i5BrCN6rZwLoPuXy4
Registered HTTP method URLs:
/cfs/files/:collectionName/:id/:filename
/cfs/files/:collectionName/:id
/cfs/files/:collectionName
token: eyJhdXRoVG9rZW4iOiJyYmx0cFd3YzUxVUlqd0JfaVhrck1RSVdmbE5wRmFKdXZFYjZvRXBWek5kIn0=
GET FILERECORD: 8BFzyhkoLyE4RGPES
Read file "me.jpg" bytes 0-14428/14429
createReadStream images
createReadStreamForFileKey images
Insertion in security = true
token: eyJhdXRoVG9rZW4iOiJyYmx0cFd3YzUxVUlqd0JfaVhrck1RSVdmbE5wRmFKdXZFYjZv-bash: FileWorker: command not found
RXBWek5kIn0=
HTTP PUT (update) handler received chunk:  0
GET FILERECORD: eLdMFShwMftTZAL4r
Insertion in security = true
createWriteStream _tempstore, internal: true
createWriteStreamForFileKey _tempstore
SA GridFS - DONE!

Thanks.

A: I had to have both GraphicsMagick and ImageMagick installed at the same time.


text:
Q: Can't print from Libre Office 4 Recently I bought a new printer, a Canon Pixma iP7250 which connects
via wi-fi. I installed it using the supplied Canon drivers for Linux
and I can print wirelessly without problem from every program in
Ubuntu except Libre Office. When I try to print a document (either
existing or new, either a .odt or a .doc) the printer icon shows for
about 10 seconds and then disappears. Going into 'view print queue'
and looking at the document I just tried to print, it says 'job
completed', but when I press the refresh button it momentarily says
'printer not found'. If I save the document as a pdf, it prints fine
from pdf viewer, but this can only be a temporary workaround. I also
have the same version of Libre Office on an old Windoze machine
running XP and I can print from that without any problem, so this must
be an Ubuntu issue. I am running 13.04.
I have looked both in the printer settings and the printer settings
within Libre Office and cannot see anything untoward. In have also
searched the internet via Duck Duck Go and even, in desperation, used
Messrs Page & Brin's search engine, but I could not find anything on
this particular issue.
I would be very grateful for any advice on this issue, as I tend to
print more from Libre Office than any other program.
Thanks

A: After having said that everything else prints except LO, I discovered that I could not print a photograph today and the problem was the same - 'printer not connected'. I solved it by deleting the printer, connecting it via USB and re-installing it as a local printer. Now it prints from LO, photos, Firefox etc. Wi fi connection just doesn't work on Ubuntu.


text:
Q: Pyshark FileCapture doesn't work I'm new with pyshark, and I write a sample code by searching on the tutorial
import pyshark
cap = pyshark.FileCapture("input.cap")
cap_1 = cap[0]

and then it give me an error
/Users/tingyugu/anaconda3/bin/python /Users/tingyugu/PycharmProjects/final/test.py
Traceback (most recent call last):
File "/Users/tingyugu/anaconda3/lib/python3.6/site-packages/pyshark/capture/file_capture.py", line 70, in __getitem__
next(self)
File "/Users/tingyugu/anaconda3/lib/python3.6/site-packages/pyshark/capture/file_capture.py", line 60, in __next__
packet = self._packet_generator.send(None)
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/tingyugu/PycharmProjects/final/test.py", line 5, in <module>
cap_1 = cap[0]
File "/Users/tingyugu/anaconda3/lib/python3.6/site-packages/pyshark/capture/file_capture.py", line 73, in __getitem__
raise KeyError('Packet of index %d does not exist in capture' % packet_index)
KeyError: 'Packet of index 0 does not exist in capture'

I know the reason is that there is no packets in the cap, but my friend can read the file by pyshark
I use the python 3.6.0 anaconda and the pyshark is 0.3.7 in anaconda

A: if you are on jupyter see this issue on PyShark Repo. I had the same problem, seems like pyshark does not go well with jupyter. I'm gonna assume it might have same issues with ipython as well.
there are some pull requests like this one on their repo too as a fix but nothing merged yet.


text:
Q: Jquery appending input values - Not displaying entered values after validation I have registration form on my website that, using jquery I append default values to, and onFocus/blur the default values hide and show accordingly.
My problem is that when the form is submitted and has kicked back errors using php validation, I am unable to show the posted values in the fields. The javascript seems to write over the posted data that is echoed using php in the input value.
When I look at the page source after posting my form I see that in the value of the input I do appear to have the posted value, the value that I want shown. Example:
<input type="text" name="first_name" value="Harry"  />

PHP has done it's work in echoing the posted data into the value of my input. Then Javascript changes it so that instead of the user seeing their name (Harry in this example) they once again see the default jquery appended "First name".
This happens even though I have a value in the input.
How can I modify my Javascript to take note of the value of my input and not write over it?
This is the code so far:
$(document).ready(function() {

 $('input[name=first_name]').val('First name');
  $('input[name=last_name]').val('Last name');
   $('input[name=email_address]').val('Email address');

    // cache references to the input elements into variables
    var passwordField = $('input[name=password]');
    var emailField = $('input[name=email_address]');
       var firstnameField = $('input[name=first_name]');
          var lastnameField = $('input[name=last_name]');

    // get the default value for the fields
    var emailFieldDefault = emailField.val();
        var firstnameFieldDefault = firstnameField.val();
        var lastnameFieldDefault = lastnameField.val();

    // add a password placeholder field to the html
    passwordField.after('<input id="passwordPlaceholder" type="text" value="Password" autocomplete="off" />');
    var passwordPlaceholder = $('#passwordPlaceholder');

    // show the placeholder with the prompt text and hide the actual password field
    passwordPlaceholder.show();
    passwordField.hide();

    // when focus is placed on the placeholder hide the placeholder and show the actual password field
    passwordPlaceholder.focus(function() {
        passwordPlaceholder.hide();
        passwordField.show();
        passwordField.focus();
    });
    // and vice versa: hide the actual password field if no password has yet been entered
    passwordField.blur(function() {
        if(passwordField.val() == '') {
            passwordPlaceholder.show();
            passwordField.hide();
        }
    });

    // when focus goes to and moves away from the fields, reset it to blank or restore the default depending if a value is entered
    emailField.focus(function() {
        if(emailField.val() == emailFieldDefault) {
            emailField.val('');
        }
    });
    emailField.blur(function() {
        if(emailField.val() == '') {
            emailField.val(emailFieldDefault);
        }
    });

        firstnameField.focus(function() {
        if(firstnameField.val() == firstnameFieldDefault) {
            firstnameField.val('');
        }
    });
    firstnameField.blur(function() {
        if(firstnameField.val() == '') {
            firstnameField.val(firstnameFieldDefault);
        }
    });
            lastnameField.focus(function() {
        if(lastnameField.val() == lastnameFieldDefault) {
            lastnameField.val('');
        }
    });
    lastnameField.blur(function() {
        if(lastnameField.val() == '') {
            lastnameField.val(lastnameFieldDefault);
        }
    });

});

A: $('input[name=first_name]').val('First name');

This unconditionally sets the value of that element to First Name. It's not a "only set the value if it's empty", it's "set the value to First Name, regardless of what it's in there".
You'd need something like this to preserve what's in there:
if ($('input[name=first_name]').val() == '') {
    $('input[name=first_name]').val('First name');
}

instead, which would only reset the field's value if it starts out empty.

A: Just get some placeholder plugin, your code repeat itself too much and still does not do what you need
This is just what you need:
http://plugins.jquery.com/project/input-placeholder
With it your code will look very clear and simple, like:
<input type="text" name="first_name" placeholder="First Name" />
<input type="text" name="last_name" placeholder="Last Name" />
<input type="text" name="email_address" placeholder="Email" />

<script>
   $(function(){
      $('input[placeholder]').placeholder();
   })
</script>

Instead all of your javascript

A: on ready function your are setting some values before your default values
$('input[name=first_name]').val('First name');
$('input[name=last_name]').val('Last name');
$('input[name=email_address]').val('Email address');

so your defalut values cannot be empty

A: This is how i would do it so it would be more dynamic and less code.
<input type="text" name="first_name" rel="First Name" value="<?=$first_name?>"  />
<input type="text" name="last_name" rel="Last Name" value="<?=$last_name?>"  />
<input type="text" name="email" rel="Email" value="<?=$email?>"  />

$(function(){
    $('input').each(function(){
        var val = $(this).val(),
            rel = $(this).attr('rel');
        $(this).focus(function(){
            if(val === rel){
                $(this).val('');
            }
        });
        $(this).blur(function(){
            if(val === ''){
                $(this).val(rel);
            }
        });
        if(val === ''){
            $(this).val(rel);
        }
    });
});

A: With the minimum changes:
if($('input[name=first_name]').val()!='')
    $('input[name=first_name]').val('First name');
if($('input[name=last_name]').val()!='')
    $('input[name=last_name]').val('Last name');
if($('input[name=email_address]').val()!='')
    $('input[name=email_address]').val('Email address');

Another cool way:
if($('input[name=first_name]').val()!='') {
    $('input[name=first_name]').val('First name');
    $('input[name=first_name]').class('init');
}
if($('input[name=last_name]').val()!='') {
    $('input[name=last_name]').val('Last name');
    $('input[name=last_name]').class('init');

}
if($('input[name=email_address]').val()!='') {
    $('input[name=email_address]').val('Email address');
    $('input[name=email_address]').class('init');
}

var initVals = new Array();
$("form input").each( function (i) { initVals[i] = this.value; } );
$("form  input").focus( function () {
    if ( $(this).hasClass("init")  ){
        $(this).removeClass("init");
        $(this).val("");
    }
} );
$("form input").blur( function (i) {
    if ( $(this).val() == "" || $(this).val() == initVals[$("form input").index(this)] ){
        $(this).addClass("init");
        $(this).val( initVals[$("form input").index(this)] );
    };
} );

Don't forget to use hasClass("init") or similar to avoid sending inputs with its default value.


text:
Q: How can we monitor a HTTPS URL? A couple of our recent customers have had their applications configured for HTTPS only. Currently we are using a tool which does a good job of monitoring customers' app-server state. For the existing customers, HTTP URLs also work, so the tool can monitor the health. But the recent one have only the HTTPS enabled so the tool fails automatically.
To this end, I am looking for a tool which would monitor the app-server state and send email to the group.
Simple monitoring like checking to see if the app-server is up or not is all I would need. But more features are also definitely helpful.
Thanks!

A: I generally just create a login with no real privileges and then script that check to log in to the website.  Often it can be done with a simple POST request.  What monitoring application do you use? For Nagios the only real difference when using HTTPS is that you have to add a switch to the check_http command (and maybe add another to accept a bad cert, that is kind of a bad idea though).

A: Circonus (http://circonus.com/) supports HTTPS checks.  Here are some of the metrics it returns (that you can graph or set alerts on).  This is a real example.

*

*bytes [0] - Bytes received

*cert_end [1293988511] - SSL Expire on (epoch)

*cert_end_in [20190421] - Certificate time until expire (seconds)

*cert_error [] - SSL Error

*cert_issuer [/C=US/O=Equifax/OU=Equifax Secure Certificate Authority] - SSL Issuer

*cert_start [1228238111] - SSL Issued on (epoch)

*cert_subject [/C=US/ST=New Jersey/L=Secaucus/O=Etsy, Inc./CN=*.etsy.com] - SSL Subject

*code [302] - Response Code

*duration [170] - Duration, total (ms)

*tt_connect [9] - Duration, initial connect (ms)

*tt_firstbyte [168] - Duration, first byte (ms)

As you can see, not only are typical HTTP metrics returned, but you also get stuff like SSL Expire on (monitor your cert expiration), SSL Subject (monitor for changes), Response Code and Total Duration.

A: Monitoring HTTPS should be the same as monitoring HTTP other than the port and the SSL encryption.  The monitors I have used all supported HTTPS either through a switch or a dedicated plugin.  SSL doesn't work with some of the lightwieght monitors.


text:
Q: How to build boost foreach cycle I have some abstract class called IClass (has pure virtual function). There are some classes which inherit IClass: CFirst, CSecond.
I want to add objects of classes which inherit into boost::ptr_vector:
class IClass { virtual void someFunc() = 0; };
class CFirst : public IClass { };
class CSecond : public IClass { };

boost::ptr_vector<IClass> objectsList;

objectsList.push_back(new CFirst());
objectsList.push_back(new CSecond());

And now my goal is to call function (which is declarated in IClass) from all objects in objectsList. I'd prefer to use BOOST_FOREACH:
foreach(IClass tempObj, objectsList)
{
    tempObj.someFunc();
}

The problem is that IClass - abstract class, so I can't make instance of it for the foreach-cycle. What should I do?

A: Use a reference to IClass instead:
foreach(IClass& tempObj, objectsList)
{
    tempObj.someFunc();
}


text:
Q: c++ reading (.cso) compiled shader object returning \0 I've tried two different methods to read from this cso file. Which is microsofts compiled shader
HRESULT BasicReader::ReadData(_In_z_ wchar_t const* fileName, _Inout_ std::unique_ptr<uint8_t[]>& data, _Out_ size_t* dataSize) {
ScopedHandle hFile(safe_handle(CreateFileW(fileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)));
    LARGE_INTEGER fileSize = { 0 };
    FILE_STANDARD_INFO fileInfo;
    GetFileInformationByHandleEx(hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo));
    fileSize = fileInfo.EndOfFile;
    data.reset(new uint8_t[fileSize.LowPart]);
    DWORD bytesRead = 0;
    ReadFile(hFile.get(), data.get(), fileSize.LowPart, &bytesRead, nullptr);
    *dataSize = bytesRead;
}

GetFileInformationByHandleEx returned true
and ReadFile returned true
HRESULT BasicReader::ReadData(_In_z_ wchar_t const* fileName, _Inout_ std::unique_ptr<uint8_t[]>& data, _Out_ size_t* dataSize) {
    std::ifstream fstream;
    fstream.open(fileName, std::ifstream::in | std::ifstream::binary);
    if (fstream.fail())
        return false;
    char* val;
    fstream.seekg(0, std::ios::end);
    size_t size = size_t(fstream.tellg());
    val = new char[size];
    fstream.seekg(0, std::ios::beg);
    fstream.read(val, size);
    fstream.close();
    auto f = reinterpret_cast<unsigned char*>(val);
    data.reset(f);
    *dataSize = size;
}

Both of these methods make data = \0
However; when I point to another file in the same directory, it gives me data. What is happening here?
Here's the file.
I read the first few bytes of the file and it's this:
0 2 254 255 254 255 124 1 68 66 85 71 40 0 0 0 184 5 0 0 0 0 0 0 1 0 0 0 144 0 0
0 72 0 0 0 148 0 0 0 4 0 0 0 104 5 0 0 212 2 0 0 67 58 92 85 115 101 114 115 92
106 97 99 111 98 95 48 48 48 92 68 111 99 117 109 101 110 116 115 92 86 105 115
117 97 108 32 8...

And the working file looks like this:
68 68 83 32 124 0 0 0 7 16 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
32 0 0 0 0 64 0 0 0 0 0 0 0 32 0 0 0 0 0 255 0 0 255 0 0 255 0 0 0 0 0 0 0 0 16
0 0 0 0 0 0 0 0 0 0...

A: Your code working as expected: char* data array contains file's data. What's going wrong here is that your char* data array is misinterpreted by your visualizers (whatever you use to visualize: debugger visualizer, std::cout, etc). They all try to print null-terminated (c-style) string, but it terminates instantly, as first char is 0. Raw arrays can also be visualized in debuggers as pointers: address and only first data member's value (because it cannot know where array ends). In C# situation is different as arrays are objects there, much like std::vectors, so their size is known.
Offtopic (sorry for that):
I would like to comment your second, native C++ BasicReader::ReadData method implementation, as it hurts my C++ feelings ;) You trying to write C code in C++11 style. "There is more than one way to skin a cat", but there are some advices:

*

*don't use raw pointers (char*), use STL containers instead (std::vector, std::string)

*have you really good reason to use std::unique_ptr<uint8_t[]> data + size_t dataSize instad of std::vector<uint8_t>?

*avoid using raw operator new(), use STL containers, std::make_shared, std::make_unique (if available)

*seekg()+tellg() file size counting can report wrong size in case of big files

Doesn't this code looks a little cleaner and more safe:
std::vector<uint8_t> ReadData(const std::string filename)
{
    std::vector<uint8_t> data;

    std::ifstream fs;
    fs.open(filename, std::ifstream::in | std::ifstream::binary);
    if (fs.good())
    {
        auto size = FileSize(filename);
            // TODO: check here if size is more than size_t
        data.resize(static_cast<size_t>(size));
        fs.seekg(0, std::ios::beg);
        fs.read(reinterpret_cast<char*>(&data[0]), size);
        fs.close();
    }
    return data;
}

And usage is even more cleaner:
std::vector<uint8_t> vertexShaderData = ReadData("VertexShader.cso");
if(vertexShaderData.empty()) {  /* handle it*/ }
auto wannaKnowSize = vertexShaderData.size();

As a bonus, you got a nice-looking debugger visualization.
And safe FileSize() implementation. You can use either boost::filesystem, of std::tr2 if your STL had implemented it.
#include <filesystem>
namespace filesystem = std::tr2::sys;
/* or namespace filesystem = boost::filesystem */

uintmax_t FileSize(std::string filename)
{
    filesystem::path p(filename);
    if (filesystem::exists(p) && filesystem::is_regular_file(p))
        return filesystem::file_size(p);
    return 0;
}

Hope it helps somehow.


text:
Q: FileProvider vs MediaStore content URI I am trying to build some basic file manager to browse external storage files on my Android P device. I have two methods that create intents to open files using outside apps. Both methods are the same except the Uri part.
One of them using FileProvider to create Uri from a file, which looks like this:
content://com.myapp.FILE_PROVIDER/external_files/6537-6630/DCIM/Camera/20180727_221149.jpg

The other one queries MediaStore and returns Uri that looks like this:
content://media/external/images/media/3273

The rest of the code is identical
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.setDataAndType(uri, mimeType);
startActivity(intent);

Both URIs are valid, however when I open images (random images from external storage) using the one that is created with FileProvider they are opened with read-only access in outside apps. I can tell that because I don't get the editing options. The image from the Uri using MediaStore is opened as expected, with write access and thus the editing options.
I also downloaded a couple of File Managers from the Play store. This one for example: File Manager - Local and Cloud File Explorer (I guess it is using FileProvider) has the same read-only access problem when opening images.
Code
    <provider
        android:name="com.myapp.files.MyFileProvider"
        android:authorities="${applicationId}.FILE_PROVIDER"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="." />
    <root-path name="external_files" path="/storage/" />
</paths>

My questions are:
1. Do I miss something when using FileProvider? Maybe it is not intended for external storage files?
2. Are there other methods to get valid URIs for existing files? Because MediaStore doesn't have all the files

A:
Maybe it is not intended for external storage files?

You are not using it for external storage. You are using it for removable storage.
<root-path> is undocumented and unsupported. FileProvider will not work reliably for removable storage, because your app does not have access to arbitrary filesystem locations on removable storage. My guess is that if you try writing to that file in your app — whether using the File or the Uri — you will fail with an error.
MediaStore has access to more of removable storage, because it is part of the OS.

Are there other methods to get valid URIs for existing files?

You are welcome to use ACTION_OPEN_DOCUMENT_TREE and ask the user to choose their removable storage. You can then:

*

*Use takePersistableUriPermission() to get long-term access to the document tree that the user chose

*Use DocumentFile to traverse that document tree and get Uri values for documents in it

Just bear in mind that the user does not have to choose their removable storage — they are welcome to choose any document tree that they want. Done properly, this can be a feature, not a bug, in your app.


text:
Q: Add logic to date deserialisation done by Joda for Jackson I have timestamps that can be floats. Before being parsed by Joda to be converted into a DateTime object, I want to parse the string of the timestamp, to round it down to an integer, so that Joda can process this timestamp successfully.
Wanted to check how to do that.
Note that I can not modify the message to add any annotation on the related field.


text:
Q: SQL join 4 tables (SELECT s.sid, s.sname, e.ccode
FROM student s INNER JOIN enrolled e
ON s.sid = e.sid
WHERE s.programme = 'IT')
WHERE EXISTS
(SELECT c.ccode, c.tid
FROM class c INNER JOIN tutor t
ON c.tid = t.tid
WHERE t.tname = 'Hoffman');

This is what i've got so far, doesn't work though. Need to get the names of IT students from the student table that are enrolled in a class by a tutor named Hoffman, all from the enrolled, class and tutor tables.
where am i going wrong?
Class:
ccode   | cname         | weekday | meets at | room  | tid
________________________________________________________________________
CIS166  | Intro to Comp | Tue     | 10:00:00 | MB300 | 1
________________________________________________________________________
CIS177  | Maths         | Mon     | 15:00:00 | MB100 | 6
________________________________________________________________________
CIS188  | Info Syst     | Thu     | 14:00:00 | MB230 | 5
________________________________________________________________________
CIS199  | Intro to Java | Fri     | 10:00:00 | MB300 | 4
________________________________________________________________________
CIS277  | Algorithmics  | Thu     | 14:00:00 | MB200 | 2
________________________________________________________________________
CIS288  | Database Syst | Mon     | 14:00:00 | MB142 | 1
________________________________________________________________________
CIS297  | Web Design    | Mon     | 16:00:00 | MB109 | 3
________________________________________________________________________
CIS298  | C++           | Fri     | 10:00:00 | MB110 | 8

Tutor:
tid | tname
_____________________
1   | Rob Hoffman
_____________________
2   | James Butler
_____________________
3   | Kathy Bond
_____________________
4   | Theodora Stewart
_____________________
5   | Mike Richie
_____________________
6   | John Kay
_____________________
7   | Mary Tregear
_____________________
8   | Mark Robinson

Enrolled:
sid | ccode
______________
211 | CIS288
203 | CIS298
214 | CIS297
105 | CIS177
215 | CIS297
104 | CIS188
210 | CIS297
338 | CIS320
102 | CIS177
338 | CIS399
204 | CIS288
204 | CIS277
102 | CIS199
203 | CIS297
105 | CIS199
331 | CIS320
202 | CIS299
205 | CIS299
210 | CIS298
331 | CIS399
321 | CIS399
210 | CIS288
210 | CIS277
204 | CIS297
321 | CIS320
328 | CIS388
327 | CIS388
211 | CIS297
333 | CIS399
215 | CIS288
104 | CIS199

Student:
sid | sname        | programme | level | age
____________________________________________
101 | Lorry Ross   | CS         | 1     | 18
102 | Lydia Ken    | CIS        | 1     | 18
103 | Bob Chung    | CS         | 1     | 18
104 | Sonia Morris | CIS        | 1     | 18
105 | Mark Poppy   | CS         | 1     | 19
106 | Megan Chi    | IT         | 1     | 20
218 | Diana McDon  | IT         | 2     | 20
219 | Nick Smith   | IT         | 2     | 21

A: Without seeing your schema, this is a guess, but should point you in the right direction:
select s.sid, s.sname, e.ccode
from student s
inner join enrolled e on s.sid = e.sid
inner join class c on e.ccode = c.ccode --may be incorrect
inner join tutor t on c.tid = t.tid
where s.programme = 'IT'
    and t.tname = 'Hoffman'

A: I would work the query in reverse from what Red offered... You know the tutor, and drill into for that person's students...  If one tutor is associated with say... 3 classes, why query a table of possibly 10,000 students
select
      s.id,
      s.sname,
      e.eccode
   from
      tutor t
         join class c
            on t.tid = c.tid
            join enrolled e
               on c.ccode = e.ccode
               join students s
                  on e.sid = s.sid
                 and s.programme = 'IT'
   where
      t.tname = 'Hoffman'

A: Your query doesn't work because there's no relationship expressed in the exists block with the top select statement. You need to find a way to relate the tutor and class tables back to the student and enrolled tables. In other words, you should be able to express your whole query using merely inner joins between the 4 tables and the appropriate where clauses.


text:
Q: Add IDs To HTML Table Code String I have an Excel spreadsheet that I have exported as an HTML file.  The Excel file has 'defined names' for some of the cells. I would like to somehow open the exported HTML file, then read through the Excel file defined names collection and give the corresponding HTML table cells an ID that I can parse back to the Excel file's defined name.  Once the cells have been given IDs (and a runat="server" attribute), I want to write the modified HTML out as a string/file so I can stuff it into my ASP page.
Can anybody tell me a way to go about this?  I thought I would be able to use the System.Web.UI.HtmlControls.HtmlTable class, then just stuff my exported HTML code into the InnerHtml property and be off to the races.  Alas, the InnerHtml property is not valid (write OR read) for the HtmlTable (or HtmlTableRow, but it IS valid for the HtmlTableCell for some reason).
There has to be a way to do this since, just pasting the exported HTML into an aspx page in the VS IDE, then adding id="MyTable" and runat="server" to the
 tag will immediately give me an HtmlTable object that I can use in the context of the page.
I'm obviously not asking for fully fleshed out and working code, just a few lines to get me started.  Please don't kill me for my crime of ignorance!
If it helps, which I seriously doubt, this is a sample of what comes out of Excel when exported:

  BLAH FORM

  Title:
  BLAH
  Management System

    Document Number:

    12.3.456A

There are ~4300 lines in the exported HTML - 2600 of those are style info.  They will be occasionally changing this form and I don't want to keep rebuilding it every time they do.

A: Not being one with the ability to wait around for the right way to do things, here is what I came up with.  As I noted, the VS IDE pretty obviously has an HTML parser built into it that would work perfectly well for my purpose if I could only figure out where it 'lived' outside of the VS IDE and how to access if from my code.  I decided to try to use that in the only way I know how at the moment.  I pasted my exported HTML code into a new aspx web form page.  Then I created the Page_Init event handling code shown below.
// This is not absolutely necessary, but you may want to include it
using System.Web.UI.HtmlControls;

  protected void Page_PreInit(object sender, EventArgs e)
  {
    StringWriter strWtr;
    StringBuilder sbldr;
    HtmlTextWriter htmlWtr;

    // Put in table modifying code here
    this.tbl_Mine.Rows[0].ID = "r1";
    this.tbl_Mine.Rows[0].Cells[0].ID = "r1c1";
    sbldr = new StringBuilder();
    strWtr = new StringWriter(sbldr);
    htmlWtr = new HtmlTextWriter(strWtr);

    this.tbl_Mine.RenderControl(htmlWtr);
    File.WriteAllText(@"C:\Temp\HtmlTblMod.htm", sbldr.ToString());
  }

When launched, the page will write out my desired updates so I can paste them in to the real aspx page.  While this works, there has GOT to be a better way to get it done...  Anybody suggesting a sane approach to this task will get their answer accepted.