text:
Q: How to use grepl and ifelse to create a new column based on the first column of the dataframe I am new to both R and SO and after figuring quite a few things in my dataset, I am kind of stuck on this new challenge. I am working on a .csv dataset and I am using r for datacleaning.
If you see, the first column label reads 'District/Subdistrict'. In that column, the District names start with a underscore and the sub district names are written as is. Now what I need to do is create a new column at the end, (column number 5) in my .csv with the label 'District'. I need to know how to use grepl and/or ifelse to populate that new column based on the first column as follows. I am going to use the example of the District name <_A>.
The new column should contain the values <_A> corresponding to the values of the District <_A> and values of Subdistricts under the District such as , ,  in the first column. Similarly, this should repeat for other districts such as the next District name <_E> and its subdistricts.
I know how to load the data in R and set the working directory etc. I just need specific help with the code for this output that I am looking for. Even some sort of a generic form would be helpful. Apologies for the shortcomings in this question.
Sample data:
    District/Subdistrict  X   Y   Z
           _A             10  12  13
            B             8   40  15
            C             21  22  23
            D             32  40  21
           _E             24  94  97
            F             56  72  12
            G             35  23  12
            H             54  23  17

Expected output
             District/Subdistrict  X   Y   Z   District
                   _A             10  12  13     _A
                    B             8   40  15     _A
                    C             21  22  23     _A
                    D             32  40  21     _A
                   _E             24  94  97     _E
                    F             56  72  12     _E
                    G             35  23  12     _E
                    H             54  23  17     _E

A: Maybe this tidyverse variant could help you.
library(tidyverse)

Just for my purpose to get your data sample I create a tibble via tribble(). Because you already have your data as data.frame (I suppose) you can ignore it.
df <- tibble::tribble(~`District/Subdistrict`, ~X,  ~Y,  ~Z,
                      "_A",                    10,  12,  13,
                      "B",                      8,  40,  15,
                      "C",                     21,  22,  23,
                      "D",                     32,  40,  21,
                      "_E",                    24,  94,  97,
                      "F",                     56,  72,  12,
                      "G",                     35,  23,  12,
                      "H",                     54,  23,  17)

Now the code that hopefully helps you:
df %>%
  mutate(District = if_else(grepl("^_", `District/Subdistrict`), `District/Subdistrict`, NA_character_)) %>%
  fill(District) %>%
  as.data.frame()

#       District/Subdistrict  X  Y  Z District
# 1                       _A 10 12 13       _A
# 2                        B  8 40 15       _A
# 3                        C 21 22 23       _A
# 4                        D 32 40 21       _A
# 5                       _E 24 94 97       _E
# 6                        F 56 72 12       _E
# 7                        G 35 23 12       _E
# 8                        H 54 23 17       _E

A: Are you looking for this?
 rep(grep("_",dat[,1],value = T),table(cumsum(grepl("_",dat[,1]))))
[1] "_A" "_A" "_A" "_A" "_E" "_E" "_E" "_E"

or even:
cut(m<-cumsum(s<-grepl("_",dat[,1])),length(unique(m)),dat[s,1])
[1] _A _A _A _A _E _E _E _E
Levels: _A _E

A: Here is another idea via ave,
with(df, ave(District.Subdistrict, cumsum(grepl('_', District.Subdistrict)),
                                                           FUN = function(i) head(i, 1)))
#[1] _A _A _A _A _E _E _E _E
#Levels: _A _E B C D F G H


text:
Q: Username entered in first instance prompt not showing up in the second chrome instance with SocketIO + NodeJS I am a newbie to socket IO and to "Stack overflow" as well. I am in the process of making my first ever runtime chat application with SocketIO + NodeJS. After coding up the server and client, everything works perfectly as expected but as I create two chrome instances and prompt the user to enter his name, the first instance is showing up with the name entered in the second instance perfectly but simultaneously the second instance doesn't show up with the name entered in the first one. I have been searching and finding the solution to it on the internet for about two days but there's not much info regarding this. I would appreciate it if someone helps me in coming up with a solution to this.
Here's my code
Server.JS
 const io = require('socket.io')(8000, {
    cors: {
        origin: "*"
    }
});

const users = {};
io.on('connection', socket => {
    socket.on('newuserjoined', name=>{
        console.log('New User', name);
        users[socket.id] = name;
        socket.broadcast.emit('user-joined', name);
    })
    socket.on('sendmessage', message => {
        console.log(message);
        socket.broadcast.emit('chat-message', message);
    })
});

Client.JS
const socket = io('http://localhost:8000');
const messageform = document.getElementById('form');
const inmessage = document.getElementById('messageinput');
const messagecontainer = document.querySelector('.container');

socket.on('chat-message', data =>{
    console.log(data);
});

messageform.addEventListener('submit', e=>{
    e.preventDefault()
    const message = inmessage.value
    socket.emit('sendmessage', message)
    inmessage.value = ''
});

const append = (message, position)=>{
    const messageElement = document.createElement('div');
    messageElement.innerText = message;
    messageElement.classList.add('message');
    messageElement.classList.add(position);
    messagecontainer.append(messageElement);

}
const uname = prompt("Enter your name?");
append(`You joined`, 'right')
socket.emit('newuserjoined', uname)

socket.on('user-joined', uname=>{
    append(`${uname} joined the chat`, 'right');
})

Index.HTML
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/x-icon" href="chat.png">
    <title>Node Application using NodeJs and Socket IO</title>

        <form id="form">
            <input type="text" id="messageinput">
            <button class="btn" type="submit">Send Now</button>
        </form>

redpajama_set_name: RedPajamaStackExchange


text:
Q: add parameter to part of URL and keeping rest of URL in tact On the following page, and others like it, where the "Donate" link is I need to add (? or &) pw_id=2461.
Page referenced:
http://fundraising.stjude.org/site/TR/Heroes/Heroes?px=2373525&pg=personal&fr_id=10850

Since the href doesn't have an id or class to it I could target it using .support_participant a and if you look at the URL for the donate link, it is:
/site/Donation2?df_id=2300&PROXY_ID=2373525&PROXY_TYPE=20&FR_ID=10850

From that URL, the following parameters will be consistent across these type pages where I want to modify this URL: df_id, proxy_type and fr_id.
To see why I need to add this parameter, you can see the difference of the donation form by going to the donate link with the parameter added: URL with parameter:
/site/Donation2?df_id=2300&PROXY_ID=2373525&PROXY_TYPE=20&FR_ID=10850&pw_id=2461

I'm a newbie when it comes to jquery although I am enjoying learning so any patience with me would be appreciated.


text:
Q: TImedate stamp in MPLAB In my code I put a time date stamp with the version number.
const char prog_id[] = { __TIME__ " " __DATE__ "Foo project V1.3" } ;

Output:
11:09:52 May 10 2016 Foo project V1.3

This is the line of code when I was using the Freescale IDE. Due to a change in chipsets I have had to change to the MPLAB X IDE and I cannot find equivalents for the __TIME__ and __DATE__  macros.
Are there equivalents in the MPL X IDE or is there a way I can replicate these functions in C.

A: Your compiler has __DATE__ only.
Take a look at page 246 of your compiler manual
To emulate them you could, I'm not an mplab expert, use a pre-build step where a custom little program create a time_date.h file where it defines those defines with the correct value. Obviously this heather have to be included into your project.


text:
Q: macOS document icon template? The original question below has been overtaken by time: these days you do not have to supply icons or icon sets for your documents any more, as macOS will generate a standard icon out of your application icon and the system document icon template. See https://developer.apple.com/news/?id=5i6jlf4d This seems a recent development, the document in the link is dated January 2021.
You still have to supply CFBundleDocumentTypes in your plist, to bind the document extension to your application, but leave out CFBundleTypeIconFile that you can use to attach your own iconset to your documents.
Original question:
Is there a template available for the Mac OS X document icon? It looks like a white piece of paper with the top right corner curled down. Lots of applications seem to use this icon as a base for their own custom document types. Does everyone use a template for the basic shape, or does every developer have to draw their own from scratch?
I know you can get the plain document icon here:
/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericDocument.icns

But that is in .icns format rather than a format I can easily edit. Also, it doesn't make it easy if you want the document background to be anything but white.
It would be great if there is a Photoshop (.psd) template available for each icon size (512, 256, 128, 32, 16).

A: You can turn a directory full of .PNG files into an .ICNS or vice-versa using iconutil.  It comes with OS/X and is a command-line program:
https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man1/iconutil.1.html
You can also use Preview to extract individual PNGs out of the file.  But to extract all the icons from the file you mention with their appropriate labels -- start up a command terminal in the directory where you want your output, and run this command:

iconutil -c iconset /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericDocumentIcon.icns -o ./GenericDocumentIcon.iconset

If you're going the reverse direction, note that when building an .ICNS the directory you are building it from must end in .iconset and the filenames are very specific.  The files in the directory must be named:

*

*icon_16x16.png

*icon_16x16@2x.png

*icon_32x32.png

*icon_32x32@2x.png

*icon_128x128.png

*icon_128x128@2x.png

*icon_256x256.png

*icon_256x256@2x.png

*icon_512x512.png

*icon_512x512@2x.png

For details on that and what the 2x is about, see High Resolution Guidelines for OS/X
The default page curl is rather "oppressive", especially at the small sizes like 16x16.  Perhaps it looks good on a blank document icon, but when you're putting an image on it gets in the way.  Document icons I looked at up close at that resolution often soften the gray edge on the curl and generally lighten up the darkness.
For instance, Google Chrome:

vs. the default:

I point it out just because I think it's a bit of a lost cause to make decent looking document icons at 16x16 if you follow their page curl there verbatim.

A: There is docerator tool which allows to

A: There are several tools, that converts your image (drawn in Photoshop) into an icon-format:

*

*Iconeer

*Img2icns

*IconBuilder

*Pic2Icon (seems to be not supported any longer)

*FastIcns
To convert an icon-format into another graphic-format (so you can easily modify) I can recommend:

*

*GraphicConverter

*PhotoLine
Greate sources for free icons are:

*

*freeiconsweb

*freeiconsdownload

*60 Icon Photoshop Templates
Please read the licence of the sets you download! You can download a lot of free icons there and reuse them or even modify them. Then you can convert them back into the icon-format with the tools mentioned above.

A: You can find various curl images in the QuickLook framework:
/System/Library/Frameworks/QuickLook.framework/Versions/A/Resources/
You can then composite your document icon over the generic document icon, which also gives you the mask for the curled page icon:
/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericDocumentIcon.icns


text:
Q: Building Apache Spark SQL Core I am trying to build Apache Spark SQL Core (1.4.1) and I get the following stack trace. But if I build the whole Spark Project everything's going well and the building finishes successfully. Any ideas?
The stack trace
[error] /home/ubuntu/Dev/spark/sql/core/src/main/scala/org/apache/spark/sql/DataFrameReader.scala:258: value globPathIfNecessary is not a member of org.apache.spark.deploy.SparkHadoopUtil
[error]         SparkHadoopUtil.get.globPathIfNecessary(qualified)
[error]                             ^
[error] /home/ubuntu/Dev/spark/sql/core/src/main/scala/org/apache/spark/sql/DataFrameReader.scala:263: value map is not a member of Array[Nothing]
[error]           globbedPaths.map(_.toString), None, None, extraOptions.toMap)(sqlContext))
[error]                        ^
[error] /home/ubuntu/Dev/spark/sql/core/src/main/scala/org/apache/spark/sql/execution/expressions/MonotonicallyIncreasingID.scala:22: object Nondeterministic is not a member of package org.apache.spark.sql.catalyst.expressions
[error] import org.apache.spark.sql.catalyst.expressions.{Nondeterministic, LeafExpression}
[error]        ^
[error] /home/ubuntu/Dev/spark/sql/core/src/main/scala/org/apache/spark/sql/execution/expressions/MonotonicallyIncreasingID.scala:36: not found: type Nondeterministic
[error] private[sql] case class MonotonicallyIncreasingID() extends LeafExpression with Nondeterministic {
[error]                                                                                ^
[error] /home/ubuntu/Dev/spark/sql/core/src/main/scala/org/apache/spark/sql/execution/expressions/SparkPartitionID.scala:22: object Nondeterministic is not a member of package org.apache.spark.sql.catalyst.expressions
[error] import org.apache.spark.sql.catalyst.expressions.{Nondeterministic, LeafExpression}
[error]        ^
[error] /home/ubuntu/Dev/spark/sql/core/src/main/scala/org/apache/spark/sql/execution/expressions/SparkPartitionID.scala:30: not found: type Nondeterministic
[error] private[sql] case object SparkPartitionID extends LeafExpression with Nondeterministic {
[error]                                                                       ^
[error] /home/ubuntu/Dev/spark/sql/core/src/main/scala/org/apache/spark/sql/sources/ddl.scala:252: value globPathIfNecessary is not a member of org.apache.spark.deploy.SparkHadoopUtil
[error]             SparkHadoopUtil.get.globPathIfNecessary(qualifiedPattern).map(_.toString).toArray
[error]                                 ^
[error] /home/ubuntu/Dev/spark/sql/core/src/main/scala/org/apache/spark/sql/sources/ddl.scala:279: value globPathIfNecessary is not a member of org.apache.spark.deploy.SparkHadoopUtil
[error]             SparkHadoopUtil.get.globPathIfNecessary(qualifiedPattern).map(_.toString).toArray
[error]                                 ^
[error] 8 errors found
[debug] Compilation failed (CompilerInterface)
[error] Compile failed at Jul 21, 2015 5:57:38 AM [29.605s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 38.435s
[INFO] Finished at: Tue Jul 21 05:57:38 UTC 2015
[INFO] Final Memory: 37M/609M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal net.alchim31.maven:scala-maven-plugin:3.2.0:compile (scala-compile-first) on project spark-sql_2.10: Execution scala-compile-first of goal net.alchim31.maven:scala-maven-plugin:3.2.0:compile failed. CompileFailed -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal net.alchim31.maven:scala-maven-plugin:3.2.0:compile (scala-compile-first) on project spark-sql_2.10: Execution scala-compile-first of goal net.alchim31.maven:scala-maven-plugin:3.2.0:compile failed.
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:225)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution scala-compile-first of goal net.alchim31.maven:scala-maven-plugin:3.2.0:compile failed.
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:110)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
Caused by: Compile failed via zinc server
    at sbt_inc.SbtIncrementalCompiler.zincCompile(SbtIncrementalCompiler.java:136)
    at sbt_inc.SbtIncrementalCompiler.compile(SbtIncrementalCompiler.java:86)
    at scala_maven.ScalaCompilerSupport.incrementalCompile(ScalaCompilerSupport.java:303)
    at scala_maven.ScalaCompilerSupport.compile(ScalaCompilerSupport.java:119)
    at scala_maven.ScalaCompilerSupport.doExecute(ScalaCompilerSupport.java:99)
    at scala_maven.ScalaMojoSupport.execute(ScalaMojoSupport.java:482)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    ... 20 more
[ERROR]
[ERROR]

A: Well there's no globPathIfNecessary in SparkHadoopUtil so it must be your own modification.  When you run the build from the top level, the Maven reactor has visibility to the whole project and can see your changes.  When you run the build from the subproject, Maven looks for everything from outside of the subproject in your local repo, so it can't see any modifications unless you've installed them.  So run your build again from the top level but do an install instead of a package to get your modifications installed into your local repo.  Once you do that, executing a build from sql/core should be able to resolve your changes successfully.


text:
Q: useEffect not dispatching action in react/redux project I am working on a React/Redux project and am attempting to remove a progress spinner that is getting stuck on my error page. I have confirmed my ClearAllSpinners action is working correctly, but I believe it is clearing the spinners prematurely, prior to the spinner showing up, since it is not working.
In my error page component, I have the following useEffect hook, which I have been trying to dispatch my action from anytime the page renders or there is a change to isAnySpinnerActive:
useEffect(() => {
  dispatch(ClearAllSpinners());
}, [dispatch, isAnySpinnerActive]);

I know the action clears the spinners as intended since the following function sets a spinner and then clears it after 5 seconds successfully (this function was used solely as a test):
const addSpinner = () => {
  dispatch(ShowSpinner('test-spinner'));
  setTimeout(() => {
    dispatch(ClearAllSpinners());
  }, 5000);
};

Is there any other way I can dispatch my action anytime the error page is rendered and then again after any spinners may possibly appear, other than the useEffect hook I am using?

A: you are using the useEffect hook which triggers to call after a variable or statement has changed or triggered by default as componnetDidMount. you can read more about that here.
these variables or states must be added as your dependencies array to useEffect work properly as your expectation.
you want to call your dispatch action in your useEffect, it's okay, but when?
your snippet tells that dispatch ClearAllSpinners when your component did mount!!
you can do this with your status variable(which controlling Spinner visibility) like this:
useEffect(() => {
    if(showSpinner) {
      // triggered when showSpinner is true
      setTimeout(() => {
         dispatch(ClearAllSpinners());
      }, 5000)
    } else {
      // triggered when your component did mount or when showSpinner was false!!
    }
}, [dispatch, showSpinner])


text:
Q: Zend Framework on shared hosting with PHP as CGI I have been reading a lot before coming to this situation of asking for help.
I have been speaking with the hosting company too about getting some help, but their technical support were as knowledgeable as I.
As many of the people around here writing on Zend Framework installation on a shared host, I have a deep problem with autoloading and class finding.
I have access to php.ini, .htaccess (obvious), the root directory and the public directory( of course).
The structure for my installation is the following:
/ - root, not accessible to public users)
   /application
         /config
          /controller
          /model
          /view
          /forms
              /decorators
              /cache
              /view_compiles
        /layout
  /library
      /Zend
      /(other libraries)
      /images
      /scripts
      /styles
 /public_html (public root)
       /css
       /js
       .htaccess (zend standard)
       index.php

in short, I use the standard Zend layout (as per Zend Tools).
So I have installed everything above the public area, and all the content of public is in the publicy accessible server.
On my local server, everything is working perfectly.
it runs from a folder inside the webroot and all is ok.
On the production server, PHP is installed as CGI, and there might be the problem.
First the SetEnv do not work anymore.
No matter what I do with the paths in index.php the auto-loader do not work.
When you start the app a login form must come on.
Due to the fact that the autoloader do not work,
the form cannot find the elements that have been created in a custome class, thus
the following message:

Fatal error: Class 'Model_Utils_FormElements' not found in
  /home/sites/ttonline.com/application/forms/Login.php on line 32

If I was to put a require_once (wich I do not want that solution), I then get an error that the composite decorator as not been found.
The entire system is working perfectly on my localhost...
I would appreciate if anybody could give me an input/ideas of the possible solution to the situation.
thx

A: This error is due to the fact that it was developed on windows machine and deployed on a linux/unix machine. Windows is loose on the capitalization of words and directories.
Conclusion: Capitalization error.


text:
Q: Py2exe does not include modules When I use py2exe the program does not include the modules of my project. It gives this error:
Traceback (most recent call last):
    File "volex7.py", line 5, in <module>
    File "OpenGL\GL\__init__.pyc", line3, in <module>
    File "OpenGL\error.pyc", line 12, in <module>
    File "OpenGL\platform\__init__.pyc", line 35, in <module>
    File "OpenGL\platform\__init__.pyc", line 29 in _load
TypeError: 'NoneType' object is not callable

Apparently the OpenGL modules are not included, but why not and what can I do to solve this?

A: Try adding this to your main python file:
# Hack to make it work with py2exe
try:
    from OpenGL.platform import win32
except AttributeError:
    pass

That sorted things out for me. If you need another platform than win32, make sure to import that instead.
It seems like py2exe have a hard time understanding some __import__ statements made from class methods (in OpenGL/plugins.py). Therefore you can solve it by explicitly import the required OpenGL platform plugins in your main file.


text:
Q: Fitted or equipped? On this question, I used this sentence:

There are two C-12 aircraft fitted with CEASAR.

Is fitted the correct word to use?
What I want to say in French:

Il y a deux appareils C-12 équipés avec/de CEASAR.

My bilingual dictionary suggests equipped instead, and fitted with seems related to harmony, like for clothes.

Still, fitted seems more familiar to me, from my technical readings. Am I wrong here?

A: Fitted implies the aircraft was created with CEASAR in mind, so that everything fits into place perfectly.
Equipped is similar, but implies you can 'equip' CEASAR into the aircraft at any point after construction.
Since I have no idea what CAESAR or a C-12 is, I'll use a more known example:

The bedroom is equipped with a 12-inch TV.
The kitchen is fitted with a gas stove.

An interesting note is that a person who works with mechnical parts like this is called a Fitter and Turner:

A fitter and turner refers to a person who manufactures mechanical parts (turner) and assembles (fitter) those parts together to manufacture a mechanical device.


text:
Q: How do I find out how many times each character of a string 's' repeats itself I have searched and found some similar questions, but just can't seem to figure out how to apply them to my problem.  Please bear with me, as this is my first post on the site.
I have to find out how many times a character of a string repeats itself.  For example, if given "launch at noon", the method should print:
"l" appears once in "launch at noon".
"a" appears twice in "launch at noon".
"u" appears once in " launch at noon ".
"n" appears 3 times in "launch at noon".
"c" appears once in "launch at noon".
"h" appears once in "launch at noon".
" " appears twice in "launch at noon".
"t" appears once in "launch at noon".
"o" appears twice in "launch at noon".

A: public void test() {
    // The string to test.
    String s = "launch at noon";
    // Count them.
    Map<Character, Integer> characterCounts = countCharacters(s);
    // Print the results.
    for (Map.Entry<Character, Integer> e : characterCounts.entrySet()) {
        int count = e.getValue();
        // Work out the name for the number.
        String number = count < specials.length
                // The special short ones.
                ? specials[count]
                // Is it a general one?
                : count < numbersAsWords.length
                // Yes
                ? numbersAsWords[count] + " times"
                // Way too many.
                : "too many times";
        // Print it.
        System.out.println("\"" + e.getKey() + "\" appears " + number + " in \"" + s + "\".");
    }
}

private Map<Character, Integer> countCharacters(String s) {
    // Map from character in string to count of occurrences.
    Map<Character, Integer> counts = new HashMap<>();
    // Walk the string.
    for (int i = 0; i < s.length(); i++) {
        // Get character at that point.
        char ch = s.charAt(i);
        // What's in the map for that character.
        Integer count = counts.get(ch);
        if (count == null) {
            // Not seen this character before - start at zero.
            count = 0;
        }
        // Increment seen count.
        count += 1;
        // Put it back in the map.
        counts.put(ch, count);
    }
    return counts;
}

// The short ones.
private static final String[] specials = {"not at all", "once", "twice"};

// The rest.
private static final String[] numbersAsWords = {"zero",
        "one",
        "two",
        "three",
        "four",
        "five",
        "six",
        "seven",
        "eight",
        "nine",
        "ten",
        "eleven",
        "twelve",
        "thirteen",
        "fourteen",
        "fifteen",
        "sixteen",
        "seventeen",
        "eighteen",
        "nineteen",
        "twenty",
        "twenty-one",
        "twenty-two",
        "twenty-three",
        "twenty-four",
        "twenty-five",
        "twenty-six",
        "twenty-seven",
        "twenty-eight",
        "twenty-nine",
        "thirty",
        "thirty-one",
        "thirty-two",
        "thirty-three",
        "thirty-four",
        "thirty-five",
        "thirty-six",
        "thirty-seven",
        "thirty-eight",
        "thirty-nine",
        "forty",
        "forty-one",
        "forty-two",
        "forty-three",
        "forty-four",
        "forty-five",
        "forty-six",
        "forty-seven",
        "forty-eight",
        "forty-nine",
        "fifty",
        "fifty-one",
        "fifty-two",
        "fifty-three",
        "fifty-four",
        "fifty-five",
        "fifty-six",
        "fifty-seven",
        "fifty-eight",
        "fifty-nine",
        "sixty",
        "sixty-one",
        "sixty-two",
        "sixty-three",
        "sixty-four",
        "sixty-five",
        "sixty-six",
        "sixty-seven",
        "sixty-eight",
        "sixty-nine",
        "seventy",
        "seventy-one",
        "seventy-two",
        "seventy-three",
        "seventy-four",
        "seventy-five",
        "seventy-six",
        "seventy-seven",
        "seventy-eight",
        "seventy-nine",
        "eighty",
        "eighty-one",
        "eighty-two",
        "eighty-three",
        "eighty-four",
        "eighty-five",
        "eighty-six",
        "eighty-seven",
        "eighty-eight",
        "eighty-nine",
        "ninety",
        "ninety-one",
        "ninety-two",
        "ninety-three",
        "ninety-four",
        "ninety-five",
        "ninety-six",
        "ninety-seven",
        "ninety-eight",
        "ninety-nine",
        "one hundred",
};


text: Q: Does the .NET Roslyn compiler produce better optimised IDL I understand that the Rosyln .NET compiler exposes a new API for interacting with the compiler, but does it also produce better optimised IDL that will ultimately be more performant than the previous compiler?


text:
Q: Optimize HTML page with a TON of links I maintain an HTML page that contains a list of links to photo galleries. Over the past few years it has gone from a small page to a list that contains HUNDREDS of links. My fear is that it has affected the SEO of the page as a whole; being interpeted by spiders as a link farm. Of course, I have no real way of knowing fo sure but I have started to suspect.
Is there an efficient simple way to deal with a large number of links in a manner that is still easy for the user to browse? While having hundreds of links one of top of the other may not be the best looking method, its easy to search since they are all in chronological order. I am looking to figure out a way that I can keep the page simple without creating more of a maintenance nightmare for myself.
One idea I had was use XML to store the links and use some kind of dropdown so that when a spider hit the page it would not see a mountain of links, just a reference to XML

A: Use a "pager" script to show, say 10 at a time.  They are available in every web framework or you could quickly hack up your own.

A: ... how about this. Put links in separate file(s) (or somehow store them outside of the page, db, flat file, etc.) and load them via ajax call as needed. Say, something like 'Category A' button, when clicked loads links into a div. That should keep it out view for spiders.
Then there's this: http://www.robotstxt.org/meta.html and this: http://en.wikipedia.org/wiki/Nofollow


text:
Q: Assigning a shortcut to Visual Assist's quick actions In plain Visual Studio there is the Alt+Enter shortcut, which brings up a popup with  quick fixes and improvement suggestions.
I am using the Visual Assist plugin for c++ development, which lets me right-click on a item and open 'Quick Actions and Refactorings (VA)' menu.
I would like to combine these two options into one: Having the advanced features in the easy accessible Alt+Enter shortcut without reaching to the mouse and right-click. Anyone knows how to assign a custom shortcut to 'Quick Actions and Refactoring'? Or any suggestions how to get rid of the tedious right-click?

A: Assigning shortcuts always works like this in Visual Studio:
Tools -> Options -> Environment -> Keyboard

*

*Find the right identifier for the desired action, which is
VAssistX.RefactorContextMenu in your case.

*Assign the desired shortcut Alt+Enter for the scope Text Editor and there you go.
Note, that this replaces Visual Studio's original Alt+Enter functionality, not blending them together.


text:
Q: Behavior of core dump. is defined or undefined behavior? In the below code, i made a mistake by giving the buffer size small.
char request[10];

While reading from file i used the fscanf and my line in file was "THIS_IS_THE_TEST_CODE". Here the line length is more than size of buffer.
But below are some scenarios where my code executed successfully without core dump even though the buffer size was small.
Scenario 1:
I have commented the line
class_test *c = class_test :: getinstance();

At that time code executed successfully without dump.
Scneario 2:
After finding the bug, i increased the buffer size, it worked for all cases.
But the pstack core shown at feof
 fefabfe0 feof     (1, ffbff9c4, ffbff9cc, 212e4, ff390100, 0)
 00010940 _start   (0, 0, 0, 0, 0, 0) + 5c

Why such behavoiur of the code?
Environment: UNIX SOLARIS
 class class_test
     {
        public:

           static class_test* getinstance()
           {
              static class_test single_obj;
              return &single_obj;
           }

     };

     #include<iostream>

         int main()
         {
            using namespace std;
            class_test *c = class_test :: getinstance();

            FILE  *fptr;
            char request[10];

            if((fptr  = fopen("inputstat.txt","r")) == NULL)
            {
               printf("Couldn't Open..");
            }
            else
            {

           while(!feof(fptr))
           {
              memset(request,'\0',sizeof(request));
              fscanf(fptr,"%s",request);

           }
        }
        return 0;
     }


text:
Q: setuid upstart not working I have created a .conf file in which I include
    setuid mario
    setgid mario

in order to run as mario user.
The program I run in the exec command is forever which runs an instance of node which inside spawns cvlc. cvlc does not permit to be executed as root.
With this configuration "sudo start myapp" does not start.
I'm using upstart 1.5.
Thanks in advance.


text:
Q: How to reuse vue method for different form inputs I am making a gaming character creator menu, which has a lot of form inputs that essentialy work the same way, incrementing an attribute up or down by one on button click.
I am fairly new to using Vue and would like to be able to pass the character attribute eg. 'torso' aswell from the form element to my increase() and decrease() methods without to repeat code.  Currently I can change by hardcoding in the this.form.heads++ or this.form.heads-- but would like to do something like this.form.val++ with val being which ever form element was clicked.
index.html
<form>

                Head Type

                Type {{form.heads}}

                Torso Type

                Type {{form.torso}}

</form>

app.js (cut down a little to focus on the issue)
const APP = new Vue({
  el: '#app',
  data: {
    step:1,
    display: false,
    form: {
      albedo:'mp_head_mr1_sc08_c0_000_ab',
      heads:1,
      torse:1,
    },
  },
  methods: {
    OpenUI() {
      this.display = true
    },
    CloseUI() {
      this.display = false
      $.post('https://parks_creator/CloseUI')
    },
    decrease(){
      this.form.heads--;
      $.post('https://parks_creator/inputchange', JSON.stringify({
          data: this.form
      }))
    },
    increase(){
      this.form.heads++;
      $.post('https://parks_creator/inputchange', JSON.stringify({
          data: this.form
      }))
    },
    prev() {
      this.step--;
    },
    next() {
      this.step++;
    },
    change(){
      $.post('https://parks_creator/inputchange', JSON.stringify({
          data: this.form
      }))
    },
  },
  computed: {},
  watch: {

  },

})```

A: You can pass a character attribute to your methods as a parameter.
script:
methods: {
  decrease(attribute){
    this.form[attribute]--
  },

  increase(attribute){
    this.form[attribute]++
  }
}

template


text:
Q: how to import a sheet from a specific workbook? I am working on analyzing some data that is basically currency exchange rates and so forth. This data fluctuates daily.
I want to create a workbook where one can select the date. Also, i will have a folder full of data from each date.
Based on the date selected, I would want to import the first two sheets from the file with the name matching the date.
Any help on how to do this in VBA would be very much appreciated.
Thank you very much

A: You can use simple worksheet copy like this
Sub Importsheet()

    Dim anotherWorksheet As Workbook
    Set anotherWorksheet = Workbooks.Open("some medium funny sheet path and name")
    anotherWorksheet.Sheets("Sheet1").Copy before:=ThisWorkbook.Sheets(1)
    anotherWorksheet.Close (False)
End Sub

this is just example, you need to specify your workbooknames, and sheetnames/numbers and also where you wana to place them...


text:
Q: Getting "Permission denied" when running this code I am writing a basic C program and using PuTTY to execute this program.
#include <stdio.h>
#include <stdlib.h>
typedef struct{
        unsigned int *r;
}Image;
int main()
{
    printf("yes\n");
    unsigned int a = 7;
    Image *image;
    image = malloc(sizeof(Image));
    image->r[0] = a;
    printf("r[0] =");
    printf("%d\n",image->r[0]);
    free(image);
    return 0;
}

I executed it but I am getting an error.
$ gcc -c test.c -o test -Wall -std=c11
$ ./test
./test: Permission denied.

I am new to pointers and other stuff. So, I don't know what to do next


text:
Q: Symmetric difference of two Java arrays I have two arrays
 String[] ID1={"19","20","12","13","14"};

 String[] ID2={"10","11","12","13","15"};

How can I get following answer while comparing above two arrays.
I want to exclude common elements while comparing above two arrays.
 String[] Result={"14","15","19","20","10","11"};

A: Seems like you want the union of the two sets (no duplicates, right?) minus the intersection:
Set<Integer> union = new HashSet<Integer>(Arrays.asList(ID1));
union.addAll(Arrays.asList(ID2);

Set<Integer> intersection = new HashSet<Integer>(Arrays.asList(ID1));
intersection.retainAll(Arrays.asList(ID2);

union.removeAll(intersection);

// result is left in "union" (which is badly named now)

(I changed your String to Integer, which seems to fit the data better, but it would work with String the same way)

A: It looks like XOR operation ;)
Please describe your needs a little bit more directly. Pseudocode:
foreach s in ID1 {
  if(ID2.contains(s)) {
    ID2.remove(s)
  } else {
    ID2.add(s)
  }
}

ID2 will contain your result. In assumption that there are not duplicates in both arrays.


text:
Q: Transparent hexagon-masked collage using PHP GD I'm creating a line of hexagon-masked images using GD but I'm unable to work out how to create transparency around each mask. The collage itself works perfectly but it adds a white, not transparent background to the image, despite setting 127 on the alpha argument in the imagecolorallocatealpha function. The code is based on this SO answer.
$count = 0;

// Full size image
$dest = imagecreatetruecolor( 195 * count( $images ), 230 );

// Loop image array
foreach ( $images as $image_array ) {

    // Get image source and create raw format
    $image_src = wp_get_attachment_image_src( $image_array['image'], 'hexagon' );
    $raw = strpos( 'png', $image_src[0] !== false ) ? imagecreatefrompng( $image_src[0] ) : imagecreatefromjpeg( $image_src[0] );

    $w = imagesx( $raw );
    $h = imagesy( $raw );

    /* Shape(ish)
     /\
    |  |
     \/
    */
    $points = array(
        0.5 * $w, 0,
        0, 0.23 * $h,
        0, 0.72 * $h,
        0.5 * $w, $h,
        $w, 0.72  * $h,
        $w, 0.23  * $h
    );

    // Create the mask
    $mask = imagecreatetruecolor( $w, $h );
    imagefilledpolygon( $mask, $points, 6, imagecolorallocate( $mask, 255, 0, 0 ) );

    // New image
    $image = imagecreatetruecolor( $w, $h );
    imagealphablending( $image, false );
    imagesavealpha( $image, true );

    // Transparency
    $transparent = imagecolorallocatealpha( $raw, 255, 255, 255, 127 );
    imagefill( $image, 0, 0, $transparent );

    // Pixel mapping
    for( $x = 0; $x < $w; $x++ ) {
        for ( $y=0; $y < $h; $y++ ) {
            $m = imagecolorsforindex( $mask, imagecolorat( $mask, $x, $y ) );
            if( $m['red'] ) {
                $color = imagecolorsforindex( $raw, imagecolorat( $raw, $x, $y ) );
                imagesetpixel( $image, $x, $y, imagecolorallocatealpha( $image,
                                  $color['red'],
                                  $color['green'],
                                  $color['blue'],
                                  $color['alpha']
                                )
                            );
            }
        }
    }

    // Merge to the original image
    imagecopymerge( $dest, $image, ( 195 * $count ), 0, 0, 0, imagesx( $image ), imagesy( $image ), 100 );
    $count++;
}

$path = get_template_directory() . '/assets/images/tile_image_one.png';
imagepng( $dest, $path, 0, NULL );
imagedestroy( $dest );

A: You need
imagesavealpha( $dest, true );

And if you plan to overlap the transparent bits of hexagon,
imagealphablending( $dest, true );


text:
Q: association issue using model and omniauth identity in ruby I have a video model and i'm trying to associate that to omniauth identity. omniauth is working fine. what i'm trying to achieve is when a person is logged in and submits a video i want that video to be able to associate back to the user that submitted it.
I have setup belongs_to :user and a column called user_uid in the video model. I also setup has_many :videos in the user model.
The problem is that whenever I submit a new video I get uid of 1 (which is the default). So what gives?
Video Model:
class Video < ActiveRecord::Base
    belongs_to :user
    end

User Model:
class User < ActiveRecord::Base

  has_many :videos
  def self.from_omniauth(auth)
    find_by_provider_and_uid(auth["provider"], auth["uid"]) || create_with_omniauth(auth)
  end

  def self.create_with_omniauth(auth)
    create! do |user|
      user.provider = auth["provider"]
      user.uid = auth["uid"]
      user.name = auth["info"]["name"]
    end
  end
end

also here is the current schema:
  create_table "users", :force => true do |t|
    t.string   "provider"
    t.string   "uid"
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "videos", :force => true do |t|
    t.string   "title"
    t.string   "description"
    t.string   "url"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "submitted_by"
    t.string   "identity_id",  :default => "1"
    t.string   "user_uid",     :default => "1"
  end

video submission page code:
<%= form_for(@video) do |f| %>
  <% if @video.errors.any? %>

<%= pluralize(@video.errors.count, "error") %> prohibited this video from being saved:

      <% @video.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label :title %>

    <%= f.text_field :title %>

    <%= f.label :description %>

    <%= f.text_field :description %>

    <%= f.label :url %>

    <%= f.text_field :url %>

    <%= f.submit %>

<% end %>

A: Simple solution - just don't use the OmniAuth uid for anything except logging in.  Once the user logs in, you'll have a User id which Rails can handle much easier.  Rename your videos.user_uid column to user_id and be happy.


text:
Q: I can't understand why I'm getting an Error #1452 on MySQL I'm trying to work on my database, which I've just gone through all the trouble to retrofit with foreign keys that will cascade on update. But now, I'm finding that I can't enter any rows into this table. I keep getting this message:
#1452 - Cannot add or update a child row: a foreign key constraint fails (testing3.ouc_breeds, CONSTRAINT breeds_Species FOREIGN KEY (Species) REFERENCES nfk_species (Name) ON DELETE CASCADE ON UPDATE CASCADE)
Now, I read on this page (mysql foreign key error #1452) that this means that there is "at least one row in the child table that references a non-existent row in the parent table."
The last few times I've gotten this message, I realized that I had either forgotten to populate the parent table with data, because I'd recently copied it, or that some data I was trying to enter in the child table (or rather columns I was trying to leave blank) truly didn't match with any values in the parent table.
But here I'm baffled. The parent table has all it's entries, the child table is being filled with a PHPMyAdmin form that automatically pulls all foreign keys from the parent table, and all the columns are the same. What's going on?
The error specifically references the Species foreign key, so here is the information for the Parent/Child tables.
** Table SQL (Pulled from export files)**
    **Parent Table:**
    CREATE TABLE `NFK_Species` (
      `Id` int(11) NOT NULL,
      `Name` char(255) COLLATE utf8_bin NOT NULL
    ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

    ALTER TABLE `NFK_Species`
      ADD PRIMARY KEY (`Id`),
      ADD UNIQUE KEY `Name` (`Name`);

    **Child Table**

    CREATE TABLE `OUC_Breeds` (
      `Species` char(255) COLLATE utf8_bin NOT NULL,
      `Family` char(255) COLLATE utf8_bin NOT NULL DEFAULT 'N/A',
      `Breed_Name` char(255) COLLATE utf8_bin NOT NULL,
      `Height` float NOT NULL,
      `Weight` int(255) NOT NULL,
      `Size_Chart` varchar(255) COLLATE utf8_bin NOT NULL,
      `Coat_Length` char(255) COLLATE utf8_bin NOT NULL,
      `Coat_Value` char(255) COLLATE utf8_bin NOT NULL,
      `Coat_Type` char(255) COLLATE utf8_bin NOT NULL,
      `Country_Of_Origin` char(255) COLLATE utf8_bin NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

ALTER TABLE `OUC_Breeds`
  ADD UNIQUE KEY `Breed` (`Breed_Name`),
  ADD KEY `Species` (`Species`),
  ADD KEY `B_Coat_Length` (`Coat_Length`),
  ADD KEY `breeds_Coat_V` (`Coat_Value`),
  ADD KEY `breeds_Country` (`Country_Of_Origin`),
  ADD KEY `breeds_Family_idx` (`Family`);

    ALTER TABLE `OUC_Breeds`
      ADD CONSTRAINT `breeds_Coat_L` FOREIGN KEY (`Coat_Length`) REFERENCES `nfk_coat_length` (`Length`) ON DELETE CASCADE ON UPDATE CASCADE,
      ADD CONSTRAINT `breeds_Coat_V` FOREIGN KEY (`Coat_Value`) REFERENCES `nfk_coat_length` (`Value`) ON DELETE CASCADE ON UPDATE CASCADE,
      ADD CONSTRAINT `breeds_Country` FOREIGN KEY (`Country_Of_Origin`) REFERENCES `nfk_countries` (`Country`) ON DELETE CASCADE ON UPDATE CASCADE,
      ADD CONSTRAINT `breeds_Family` FOREIGN KEY (`Family`) REFERENCES `ouc_families` (`Family`) ON DELETE CASCADE ON UPDATE CASCADE,
      ADD CONSTRAINT `breeds_Species` FOREIGN KEY (`Species`) REFERENCES `nfk_species` (`Name`) ON DELETE CASCADE ON UPDATE CASCADE;

**Enter Data SQL**

    INSERT INTO `Testing3`.`OUC_Breeds` (
        `Species`, `Family`, `Breed_Name`, `Height`, `Weight`, `Size_Chart`,
        `Coat_Length`, `Coat_Value`, `Coat_Type`, `Country_Of_Origin`)
    VALUES (
       'Dogs', 'N/A', 'Labrador Retriever', '23', '70',
        'img.png', '3', 'Short', 'Straight', 'England')

IMG of entry field

If there's any other information that would help you help me, please let me know. If I can't get this fixed, I won't be able to move forward with my database or website.
Edit:
I just tried to modify an entry in a different table where I was making adjustments to that row's Species info, and I once again got Error #1452. Could there be something wrong with my actual Species table?
Edit 2:
It was recommended that I provide sample data sets for my tables, so here they are.
            INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES
            (1, 'Dogs'),
            (2, 'Cats'),
            (3, 'Birds'),
            (4, 'Rabbits'),
            (5, 'Guinea Pigs'),
            (6, 'Rats'),
            (7, 'Mice'),
            (8, 'Gerbil'),
            (9, 'Hamster'),
            (10, 'Unicorn'),
            (11, 'All'),
            (12, 'N/A');

          INSERT INTO `OUC_Breeds` (`Species`, `Family`, `Breed_Name`, `Height`, `Weight`, `Size_Chart`, `Coat_Length`, `Coat_Value`, `Coat_Type`, `Country_Of_Origin`)
VALUES('Dogs', 'N/A', 'German Shepherd Dog', 25, 80, '/images/size-charts/gsd.png', '3', 'Short', 'Double', 'Germany');

Also, I noticed that the Species "Key" Name ('Species') does not match the constraint name ('breeds_Species'). Could this be causing problems?
Edit 3
Ok, so I updated my OUC_Breeds.Species Key to match the constraint Key name, and after that the #1452 error stopped talking about the SPECIES column and started talking about the LENGTH column, which I then noticed didn't match either. So then I went through and made sure all the KEY names matched the CONSTRAINT names, but now still getting Error #1452 on my COAT_VALUE column, even though the key/constraints match. I've double checked the column values (both are CHAR(255), the value I'm trying to put in exists on the Coat_Length table, and I know I'm missing something else.
Updated Key/Constraints
-- Indexes for table `OUC_Breeds`
--
ALTER TABLE `OUC_Breeds`
  ADD UNIQUE KEY `Breed` (`Breed_Name`),
  ADD KEY `breeds_Coat_V` (`Coat_Value`),
  ADD KEY `breeds_Country` (`Country_Of_Origin`),
  ADD KEY `breeds_Species` (`Species`) USING BTREE,
  ADD KEY `breeds_Coat_L` (`Coat_Length`) USING BTREE,
  ADD KEY `breeds_Family` (`Family`) USING BTREE;

-- Constraints for table `OUC_Breeds`
--
ALTER TABLE `OUC_Breeds`
  ADD CONSTRAINT `breeds_Coat_L` FOREIGN KEY (`Coat_Length`) REFERENCES `nfk_coat_length` (`Length`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `breeds_Coat_V` FOREIGN KEY (`Coat_Value`) REFERENCES `nfk_coat_length` (`Value`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `breeds_Country` FOREIGN KEY (`Country_Of_Origin`) REFERENCES `nfk_countries` (`Country`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `breeds_Family` FOREIGN KEY (`Family`) REFERENCES `ouc_families` (`Family`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `breeds_Species` FOREIGN KEY (`Species`) REFERENCES `nfk_species` (`Name`) ON DELETE CASCADE ON UPDATE CASCADE;

A: Here are two reasons for why you might be getting the 1452 error:

*

*You are trying to INSERT a new record into OUC_Breeds containing a species which does not exist in the parent table NFK_Species.  I realize you mentioned in your question that you are using only primary key species which already exists.  But why are you using ON DELETE CASCADE ON UPDATE CASCADE in the first place?

*Your OUC_Breeds table contains one or more Species entries which no longer exist in the NFK_Species table.  Remember, even if you added these entries before adding the constraint MySQL will still roll over.  Here is a query you can use to check for this second possibility:
SELECT DISTINCT Species FROM
OUC_Breeds breeds LEFT JOIN NFK_Species species
ON breeds.Species = species.Name
WHERE species.Name IS NULL;
If you get back any Species from this query it means that your OUC_Breeds table is violating the foreign key constraint.

A: After going back and forth between phpMyAdmin and MySQL Workbench, I realized that on MySQL Workbench (for some reason) my foreign keys were linking to tables that "did not exist" (They had been renamed). I don't understand why this was a problem, as when you view the EXPOT SQL from phpMyAdmin (the same ones I listed here), it references the correct tables with the correct names.
So, to sum it up, in order to fix my problem I had to:
1.) Check and make sure the value I want to enter into my foreign key actually exists in my parent key. Make sure the table isn't empty or the value you're trying to enter didn't get deleted somehow.
2.) Check to make sure that the names of all defined KEYS match any corresponding CONSTRICTION foreign keys. In my case, I wasn't able to simply re-name them. I had to remove all the foreign keys and indexes and re-asign them in order for my database to accept them.
3.) Check to make sure that the foreign key is referencing a table that actually exists (make sure the Name is spelled correctly). I was only able to figure this out because I was using two MySQL programs (PHPMyAdmin and MySQL Workbench). Again, in order to fix it I had to remove the foreign key and re-assign it.
So, YAY! My database is currently working. I have gone through the rest of my tables that use foreign keys and attempted to enter (bogus) rows into them to make sure they work, and they do.


text:
Q: using Kinesis Client library with Spark Steaming PySpark I am looking for using KCL on SparkStreaming using pySpark.
Any pointers would be helpful.
I tried few given by spark Kinesis Ingeration link.
But i get the error for JAVA class reference.
Seems Python is using JAVA class.
i tried linking
spark-streaming-kinesis-asl-assembly_2.10-2.0.0-preview.jar
while trying to apply the KCL app on spark.
but still having the error.
Please let me know if anyone has done it already.
if i search online i get more about Twitter and Kafka.
Not able to get much help with regard to Kinesis.
spark verision used: 1.6.3

A: I encountered the same problem. The kinesis-asl jar had several files missing.
To overcome this problem, I had included the following jars in my spark-submit.

*

*amazon-kinesis-client-1.9.0.jar

*aws-java-sdk-1.11.310.jar

*jackson-dataformat-cbor-2.6.7.jar

Note: I am using Spark 2.3.0 so the jar versions listed might not be the same as those you should be using for your spark version.
Hope this helps.


text:
Q: PHP Mail Sending BCC not wordking I am using PHP mail and trying to send BCC, but for some reason since I've added the lines with //ADDED NEW on it , it's just now sending any emails at all.
Here is the full code:
 $to = "me@gmail.com";
 $bcc = $row['recipients']; //ADDED NEW
 $subject = $row['subject'];
 $message = $row['text_body'];

 $headers = "From: " . strip_tags('me@gmail.com') . "\r\n";
 $headers .= "Reply-To: ". strip_tags('me@gmail.com') . "\r\n";
 $headers .= "Bcc: $emailList\r\n"; //ADDED NEW
 $headers .= "MIME-Version: 1.0\r\n";
 $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

 mail($to, $bcc, $subject, $message, $headers); // $bcc ADDED NEW

Why is this not sending?

A: There's no $bcc argument to the mail() function. It should be:
mail($to, $subject, $message, $headers);

The blind recipients will be retrieved from the Bcc header in $headers.

A: Your problem,

*

*Set $bcc but in $headers does not using it

*Putting invalid argument into mail function.

Try this
$to = "me@gmail.com";
$bccList = $row['recipients']; //ADDED NEW
$subject = $row['subject'];
$message = $row['text_body'];

$headers = "From: " . strip_tags('me@gmail.com') . "\r\n";
$headers .= "Reply-To: ". strip_tags('me@gmail.com') . "\r\n";
$headers .= "Bcc: $bccList\r\n"; //ADDED NEW
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

mail($to, $subject, $message, $headers); // $bcc ADDED NEW


text: Q: What spell did Dolohov use on Hermione in Order of the Phoenix? What was the spell with purple flame used by Dolohov on Hermione during the Battle at the Department of Mysteries in Order of the Phoenix? If Dolohov hadn't been silenced, would it have killed her?


text:
Q: Flutter How get token device with fcm on Android Mode My project flutter 3.3 and fcm last version it error on product mode
It not get token device all android device
How config

A: You'll need googleplay services in Android studio installed as well as emulator capable of running google APIs. then from root project directory run flutter pub add firebase_messaging. Also you will need to add this in the manifest file
<meta-data
    android:name="firebase_messaging_auto_init_enabled"
    android:value="false" />
<meta-data
    android:name="firebase_analytics_collection_enabled"
    android:value="false" />

Also this might be useful for dealing with the token: Firebase (FCM) registration token in Flutter


text:
Q: Initialize a pointer to a class with NULL values I am tring to intialize an array of pointers to a NODE struct that I made
struct Node{
    int data;
    Node* next;
};

the private member of my other class is declared as

Node** buckets;

It is currently initialised as
    buckets = new Node*[SIZE]
Is there anyway to initialize the array so that its members point to NULL or some other predefined Node pointer?
EDIT: Im looking for a means to initilize it without trying to generate a for loop to traverse through the full lenght of the array. The size of the array is determined at runtime.
EDIT 2: I tried std::fill_n(buckets, SIZE_OF_BUCKET, NULL); but the compiler gives the error "cannot convert from 'const int' to 'Node *'" I am using visual studio 2008. Is there something wrong that I am doing?

A: First of all, the simplest solution is to do the following:
Node** buckets = new Node*[SIZE]();

As litb previously stated, this will value initialize SIZE pointers to null pointers.
However, if you want to do something like Node **buckets and initialize all of the pointers to a particular value, then I recommend std::fill_n from <algorithm>
Node **buckets = new Node*[SIZE];
std::fill_n(buckets, SIZE, p);

this will set each Node*' to p after allocation.
In addition, if you want the Node to have sane member valuesupon construction, the proper way is to have a constructor. Something like this:
struct Node {
    Node() : data(0), next(NULL){}
    Node(int d, Node *n = NULL) : data(d), next(n) {}

    int data;
    Node* next;
};

That way you can do this:
Node *p = new Node();

and it will be properly initialized with 0 and NULL, or
Node *p = new Node(10, other_node);

Finally, doing this:
Node *buckets = new Node[N]();

will construct N Node objects and default construct them.

A: If you mean by array your array-of-pointers buckets, then yes. Just set buckets = NULL.
Edit: based on your question edit, just use memset.
memset(buckets, 0, NUM_ELEMENTS_IN_BUCKETS*sizeof(Node*));


text:
Q: Status code of endpoint is always 401, even when logged in. Why? I have 2 endpoints: /login and /welcome
The user should only have access to the endpoint /welcome, if they are authenticated.
My problem is that in the browser the status of /welcome is always 401, even if the status of /login was 200 before.
Angular
public login(): Observable<any> {
  const headers = new HttpHeaders({
    Authorization: 'Basic ' + window.btoa('linda:pass')
  })
  return this.http.get(environment.apiBaseUrl + 'login', { headers, responseType: 'text' as 'json' })
}

public welcome(): Observable<any> {
  return this.http.get(environment.apiBaseUrl + 'welcome');
}

Spring Boot
@RestController
public class LoginController {

    @CrossOrigin
    @GetMapping("/welcome")
    public ResponseEntity<String> welcome() {
        return ResponseEntity.ok("Welcome!");
    }

    @CrossOrigin
    @GetMapping("/login")
    public void login() {}
}

@Configuration
@EnableWebSecurity
public class Config {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(10);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(auth -> auth
                        .antMatchers("/login").permitAll()
                        .antMatchers("/welcome").hasRole("ADMIN")
                )
                .httpBasic();
        return http.build();
    }

    @Bean
    public InMemoryUserDetailsManager userDetailsManager() {
        var linda = User.builder()
                .username("linda")
                .password(passwordEncoder().encode("pass"))
                .roles("ADMIN")
                .build();
        return new InMemoryUserDetailsManager(linda);
    }
}

What am I doing wrong?

A: Spring security expression hasRole("ADMIN") will add ROLE_ prefix in the authorization rule (can be configure different) so it expect the role to be ROLE_ADMIN, while the user manager you define is .roles("ADMIN") which will against the authorization rule you define hence you get the 401 Unauthorized response.
If don't want to change your role's name you can use another Spring security expression which is hasAuthority(..)
For more info check out the documentation


text:
Q: what should be the command line for creating executable using pyinstaller? I have a Project in which a main.py file which has below line for passing the command line argument
os.system(r'robot -d %s\\results -v CWD:%s -A %s\\arguments.txt  data\util\data' % (cwd, cwd, cwd))

The command line which I am giving to create the executable is
pyinstaller -F --add-data "arguments.txt;." main.py

the executable is created but giving error -
[ ERROR ] Parsing 'data\util\data' failed: File or directory to execute does not exist.

below is the directory structure.
main project -

arguments.txt
main.py
datacreation/util/data

main.spec is as follow
# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(['main.py'],
             pathex=['(path_to)\\Desktop\\(path_to)\\main_project'],
             binaries=[],
             datas=[('arguments.txt', '.')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          [],
          exclude_binaries=True,
          name='main',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          console=True )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               upx_exclude=[],
               name='main')

Thanks

A: When you add your file arguments.txt in one file mode, the data will extract in a temp path like C:/Users/<user>/AppData/Local/Temp/_MEIXXX, so in your command line, it needs to load from this path which would be equal to sys._MEIPASS.
import os
import sys

def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

arguments_path = resource_path("arguments.txt")
data_path = resource_path("path_to_ur_data")
...

os.system(r'robot -d %s\\results -v CWD:%s -A %s  data\util\data' % (cwd, cwd, arguments_path)) # add all external path here


text:
Q: VBA - CountIf cell range displayed value is equal to desired value I am having an issue running my code through, because the Range.Value is different than the Range.NumberFormat.  For example, my value is a date and time and I would like to test for the day of the week. I was able to get the number format to be Sun-Sat, however, I am unsure how to test for it with CountIf.
Dim rep         as Worksheet
Dim day         As Range
Dim time        As Range
Dim wf          As WorksheetFunction
Set rep = Worksheets("Report")
Set day = rep.Range("H1", rep.Range("H1").End(xlDown))
Set time = rep.Range("I1", rep.Range("I1").End(xlDown))
Set wf = WorksheetFunction

With rep
    .Columns("H").NumberFormat = "dddd"
    .Columns("I").NumberFormat = "AM/PM"

    .Range("K1") = "Monday"
    .Range("K2") = "Tuesday"
    .Range("K3") = "Wednesday"
    .Range("K4") = "Thursday"
    .Range("K5") = "Friday"
    .Range("K6") = "Saturday"
    .Range("K7") = "Sunday"

    .Range("M1") = "AM"
    .Range("M2") = "PM"

        .Range("L1") = wf.CountIf(day, "Monday")
        .Range("L2") = wf.CountIf(day, "Tuesday")
        .Range("L3") = wf.CountIf(day, "Wednesday")
        .Range("L4") = wf.CountIf(day, "Thursday")
        .Range("L5") = wf.CountIf(day, "Friday")
        .Range("L6") = wf.CountIf(day, "Saturday")
        .Range("L7") = wf.CountIf(day, "Sunday")

    .Range("N1") = wf.CountIf(time, "AM")
    .Range("N2") = wf.CountIf(time, "PM")
End With

This is what I have so far, but it only outputs 0 for the solution to the countif.  Thanks in advance.

A: Here's another way to do the counts.
Note I did most of the "work" in VBA arrays as this is much faster than repeatedly accessing the worksheet:
EDIT: To include counting the number of entries in column H with AM or PM times
Option Explicit

Sub foo()
    Dim rep As Worksheet
    Dim rDts As Range
    Dim vDts As Variant
    Dim vCnts As Variant 'for the weekday count
    Dim vAP As Variant   'for the AM PM count
    Dim I As Long, J As Long

Set rep = Worksheets("sheet1")
'read dates into array -- faster processing
With rep
    vDts = .Range(.Cells(1, 8), .Cells(.Rows.Count, 8).End(xlUp))
End With

'Results array
ReDim vCnts(1 To 7, 1 To 2)
    vCnts(1, 1) = "Sunday"
    vCnts(2, 1) = "Monday"
    vCnts(3, 1) = "Tuesday"
    vCnts(4, 1) = "Wednesday"
    vCnts(5, 1) = "Thursday"
    vCnts(6, 1) = "Friday"
    vCnts(7, 1) = "Saturday"

ReDim vAP(1 To 2, 1 To 2)
    vAP(1, 1) = "AM"
    vAP(2, 1) = "PM"
'Do the counts
    For I = 1 To UBound(vDts, 1)
        J = Weekday(vDts(I, 1))
        vCnts(J, 2) = vCnts(J, 2) + 1

        'Check for AM or PM
        If Hour(vDts(I, 1)) < 12 Then
            vAP(1, 2) = vAP(1, 2) + 1
        Else
            vAP(2, 2) = vAP(2, 2) + 1
        End If

    Next I

'output the results
rep.Range("K1:L7").Value = vCnts
rep.Range("M1:N2").Value = vAP

End Sub


text:
Q: Sum of numbers less than $2^n$ with $m$ ones. My friend gave me a formula to calculate the sum of numbers with exactly $m$ ones in their binary representation that are less than $2^n$. It is as follows:
$$ {{n-1} \choose {m-1} }* (2^n-1)$$
Is this formula correct? If it is, could you kindly explain the logic behind it? Most probably, the $2^n-1$ comes from a geometric series, so, probably it has something to do with the distribution of the ones, I guess?...
Please help. Thank you.

A: A hint:
There are ${n\choose m}$ binary numbers having $n$ digits, among them exactly $m$ ones. Exactly ${1\over n}$ of all ones in the big list of these numbers are at the first, ${1\over n}$ at the second, $\ldots$, ${1\over n}$ at the $n^{\rm th}$ digit of the numbers.

A: Imagine to write down, row by row, each number in its binary representation, and put on top a row with the value $(2^0,2^1,\cdots)$ of each digit.
Now fix a digit (column): how many ones will be on it ? all the different ways in which you can distribute the remaining $m-1$ in the remaining $n-1$ digits. Then sum column by column, and you get the formula.


text:
Q: LS_COLORS how persist after sudo su I have a username created on my machine and the username is added to sudoers file to have root access.
My .bashrc file also contains a script which is saying to change the colors for the PS1 and the colors for ls commands
export PS1="\[\e[1;32m\][\u@\h \W]\$\[\e[0m\] "
export LS_COLORS="di=1:fi=0:ln=31:pi=5:so=5:bd=5:cd=5:or=31:mi=0:ex=35:*.rpm=90"

by the end of the script I also have the command sudo su to make me directly root when I'm log in.
The problem is the PS1 persist and the colors change after sudo su but the ls commands are still the default ones. How can I fix this?

A: sudo su -p will preserve the calling user's environment, with a few exceptions.  The exceptions can be found in the su man page, but the relevant part is:
   -m, -p, --preserve-environment
          Preserve the entire environment, i.e. it does not set HOME,
          SHELL, USER nor LOGNAME.  This option is ignored if the option
          --login is specified.

A: Run sudo -l as your regular user to see the options currently in effect.

*

*Does the output include env_reset? If so, only a short list of safe/essential environment variables will be preserved when going through sudo. You can use env_check and/or env_keep keywords in the sudoers file to specify environment variables that will be allowed through sudo.

*Does the output include always_set_home? If so, then the $HOME environment variable will point to the home directory of the target user, i.e. /root in your case. As a result, the resulting shell will run /root/.bashrc rather than your personal one, and likewise all programs will look for their user-specific configuration files under /root/ directory rather than your personal home directory.
If sudo -s uses root's .bashrc rather than your personal one, then always_set_home is most likely in effect (or you have a weird distribution with draconian PAM modules or something). In that case, use visudo to edit your sudoers file, and add one of the following lines (the exclamation mark before the name of option means "not"):

*

*Defaults !always_set_home unsets the option for all users.

*Defaults>root !always_set_home unsets it for all transitions to the root user, whoever the original user is.

*Defaults:johndoe !always_set_home unsets it for transitions where johndoe is the original user only.

Order matters: the last setting wins, so if there are any existing Defaults lines in your sudoers file, you should add your customizations after them.

And if you chain su after sudo, it will apply its own rules, which are usually not configurable. The behavior (and even availability) of su -p or su -m varies between different Linux distributions and versions.
sudo su means switching from your regular user to root, and then again from root to root, maximizing the chances for disruption of carefully-adjusted personal environment settings for little gain. With sudo -s you can achieve the same thing, either directly or with some tweaking of Defaults options in the sudoers file, depending on your preferences and choice of Linux distribution.
sudo su -, on the other hand, is the obsolete way to say "I explicitly want the environment to be just as if the target user (i.e. root) logged in directly; I want no trace of my personal environment to remain in the resulting session." If you have a version of sudo that was released on this millennium, you can use sudo -i instead to achieve that.
In the 2010s, the only reasons to use sudo su or sudo su - are probably muscle memory, following outdated advice, or dealing with truly old systems. You should probably unlearn these two commands.


text:
Q: Cron doesn't run sh script in ubuntu 20 I tried different options to automatically run the backup script, it just doesn't work. Everything is fine in the logs, everything shows that the launch is in progress. What could be the problem? The script works when started manually. Script:
#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/nino_new/nino
now=$(date +"%d-%m-%y_%H:%M:%S")
filename=backups/nino_$now.json
docker exec -ti skill01 python manage.py dumpdata -o $filename -a

crontab:
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/nino_new/nino
* * * * * sh /root/nino_new/nino/backup.sh

A: Try to remove the sh after * * * * * and let only the path to the script.


text:
Q: How to properly set editable checkbox inside a JTable cell in Java Swing application? I have a JTable, where I have couple of JCheckBoxes. I am initializing JCheckBoxes and other cells values from database. My problem is, when I click on the JCheckBox to checked or unchecked, they don't do nothing.
When I clicked twice, the editable JTable cell become active and shows the value of JCheckBox which is 0 OR 1. I can edit the cell with 0 OR 1 and when I save, it saves the record and load the checkbox with edited value.
Following snippet to show how I am loading and creating JCheckBoxes:
class TextBoxNewCellRenderer extends JPanel implements TableCellRenderer {

:::
public Component getTableCellRendererComponent(

case 10: //Active
                switch (column) {
                    case 0:
                        this.add(lblStar);
                        this.add(new JLabel(value.toString(), JLabel.LEFT));
                        break;
                    case 1:
                        checkBox = new JCheckBox();
                        checkBox.setToolTipText("Set 0 OR 1");
                        checkBox.setEnabled(true);
                        if(value.toString().equals("1"))
                            checkBox.setSelected(true);
                        if(value.toString().equals("0"))
                            checkBox.setSelected(false);
                        this.add(checkBox);
                        break;
:::

 return this;
    }
}

In my renderTable method I Override following isCellEditable:
 DefaultTableModel model = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {

                  switch (row){
                      case 10: //Active
                        switch (column) {
                            case 0:
                                return false;
                            case 1:
                                return true;
                            case 2:
                                return false;
                            case 3:
                                return false;
                            default:
                                return false;
                        }
                    default:
                 return false;
                }
            }
        };

Here is the picture of the JTable when I double click on JCheckBoxe:

Is there anyway I can checked or unchecked the JCheckBoxes with one click? I don't wanna update JTable cell with 0 OR 1 in order to checked or unchecked. Please Help.
Cheers.

A:
When I clicked twice, the editable JTable cell become active and shows the value of JCheckBox which is 0 OR 1.

If you want the default renderer/editor to be used then you should be storing Boolean.TRUE or Boolean.FALSE in the TableModel.
Then you also need to override the getColumnClass() method of the TableModel to return Boolean.class.
Read the section from the Swing tutorial on How to Use Tables for more information and working examples.


text:
Q: Background video stuck in a fixed position and not moving with the page While scrolling my background video is stuck on the screen. I have set the position to fixed but I want it to stop acting when the next container starts.
I also want the text of that video container to go sliding up through the video while scrolling and the same with the next container texts
I have tried replacing the position: fixed with background-poistion: fixed with no desirable changes

#title {
  font-family: 'Inknut Antiqua', sans-serif;
  color: rgb(243, 30, 112);
  font-size: 12px;
  top: 0;
  display: flex;
  flex-direction: row;
}

.logo {
  width: 4%;
  top: 6px;
  display: flex;
  flex-direction: row;
}

.top-container {
  padding: 60px 30px 30px 30px;
  margin: -80px -8px -40px -30px;
  background-color: #f1f1f1;
  display: flex;
  justify-content: center;
  position: relative;
  background-image: linear-gradient(-45deg, blue, white, yellow);
}

body {
  box-sizing: border-box;
}

#header {
  position: sticky;
  top: 0;
  ;
}

#header-img {
  width: 3%;
  padding: 0;
  display: flex;
  position: relative;
  top: 2px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 20%;
  background-color: #333;
  width: 100%;
  display: flex;
  justify-content: center;
  overflow: hidden;
}

li {
  list-style: none;
  margin-right: 70px;
  font-size: 25px;
  font-weight: bold;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 3px 10px;
  text-decoration: none;
}

li a:hover {
  background-color: #04AA6D;
  border-radius: 5px;
}

ul {
  list-style-type: none;
  margin: -48px -6px 0px -10px;
  padding: 9px;
  display: flex;
  flex-direction: row;
}

#cover {
  margin: 0.5px -10px 0px -10px;
  position: fixed;
  display: grid;
  width: 100%;
  margin-right: -98px;
  height: 550px;
  object-fit: cover;
  align-self: center;
  z-index: -1;
  opacity: 0.8;
}

.container {
  height: 100%;
  padding: 0.01em 16px;
  padding-top: 0.01em;
  padding-right: 0px;
  padding-bottom: 0.01em;
  padding-left: 0px;
  display: grid;
  position: relative;
  justify-items: center;
}

#sml {
  position: absolute;
  display: grid;
  color: white;
  transform: translate(0px, 150px);
}

#text {
  position: absolute;
  display: grid;
  color: whitesmoke;
  transform: translate(0px, 150px);
  z-index: 1;
  font-size: 50px;
}

.policies {
  margin-top: 0px;
  background-color: whitesmoke;
  display: grid;
  position: relative;
}

#prod {
  margin-top: 30px;
  position: absolute;
  top: 860px;
}

/* .centered{
    position: absolute;
    color: rgb(228, 56, 56);
    top: 30%;
    left: 50%;
    transform: translate(-50%,-50%);
} */
<!DOCTYPE html>

    <title>Giovanni's Guitars</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inknut+Antiqua:wght@300&display=swap" type='text/css'>

Giovanni's Guitars

Features

How It Works

Pricing

    <video autoplay muted loop id="cover">
        <source src="https://cdn.videvo.net/videvo_files/video/free/2021-05/small_watermarked/210512_01_Music_4k_009_preview.webm" type="video/mp4">
    </video>

Since 1961

Guitars and Basses.

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Vitae, minima. Dolore quod quam similique, odio facere necessitatibus quas officia libero non eveniet sit ipsum consectetur sunt distinctio omnis dolor, doloremque quaerat, labore quia fugiat
      porro facilis inventore! Nulla magnam labore assumenda laboriosam incidunt nisi dignissimos maxime repudiandae, maiores ipsa quod eligendi, at nesciunt quos. Commodi vitae blanditiis ratione assumenda. Voluptatem placeat provident illum officia
      fugit sequi vero nisi quam. Ipsum rerum eius ratione ea asperiores possimus praesentium commodi fuga, minima eum laudantium suscipit nostrum eveniet perferendis deserunt laboriosam blanditiis neque, alias, voluptatem eligendi dolorum vitae quae!
      Aut amet aliquid libero pariatur, blanditiis harum atque. Necessitatibus, iure? Odio quae magnam aliquid incidunt officia error perspiciatis illum voluptatum hic? Quas alias nemo accusantium temporibus error? Provident fuga fugiat eius enim totam
      soluta saepe beatae accusantium asperiores sunt nesciunt ipsa, eaque dolorum et perspiciatis dignissimos sequi? Adipisci dolorem doloremque facere pariatur inventore fuga cupiditate vel quidem enim a quia, ab odio, eveniet dignissimos dolores aliquid
      tenetur autem, quis nam quibusdam. Vel, quam excepturi. Fugit maxime voluptatum nam maiores delectus, quo illo consequatur aliquid dolorem excepturi quia sit laudantium quam deserunt numquam adipisci voluptatem eveniet voluptates, sed veniam rem
      reprehenderit corporis? Blanditiis quod, aut consequuntur commodi nisi, cupiditate dolor nihil aperiam deserunt quaerat molestiae quis nesciunt, laborum unde incidunt culpa! Possimus commodi impedit ullam eius aut veritatis expedita voluptatum nam
      deserunt ipsa, eum consequatur iusto doloribus enim voluptas labore ut nobis obcaecati illo perspiciatis quam similique provident. Culpa, quos sint eveniet eaque sequi doloremque mollitia nesciunt alias maiores debitis natus soluta. Explicabo dolorum
      ipsum dolores quaerat doloribus ad commodi nulla cupiditate doloremque. Quas iusto velit pariatur voluptatibus labore? Assumenda, cumque! Dicta molestias, harum officiis aperiam velit temporibus optio obcaecati nemo sint quam debitis nostrum. Esse,
      dolor. Excepturi provident ea ab, quas fugiat, dolores magni sapiente ipsum, accusantium commodi ex itaque enim! Beatae odio ipsa quisquam enim eius expedita obcaecati doloribus libero illum minima dolor asperiores accusantium, saepe suscipit facilis
      consequatur laboriosam, optio nemo cupiditate commodi necessitatibus aperiam. Enim perferendis ullam cum beatae soluta quas aspernatur labore itaque veniam delectus dolor debitis, voluptatibus veritatis deserunt nihil blanditiis velit ex obcaecati
      necessitatibus officiis minima omnis odit. Explicabo est consequuntur, ea nemo asperiores placeat nisi cum fugiat reiciendis repudiandae unde ipsum, distinctio nesciunt eos eligendi. Quo provident atque aperiam nemo numquam quaerat aliquid! Quibusdam
      culpa obcaecati quaerat excepturi veniam! Ut aliquam dolorum vitae praesentium reprehenderit? Unde hic consequatur officia, amet doloremque expedita! Voluptas accusamus animi ipsum quisquam atque et, ducimus est sequi quos quibusdam, nulla omnis,
      magnam debitis molestiae sit eius soluta impedit iusto esse voluptatem minus fugiat dolor provident? Adipisci ipsam eos, id ad accusamus voluptates accusantium maiores quas quos nobis, optio culpa assumenda similique voluptatum rem dolorum veniam
      doloremque ducimus quasi sit. Quos blanditiis natus in nisi sint illo unde inventore repudiandae, beatae eius ut vero ex at veritatis dolor itaque obcaecati adipisci. Itaque beatae omnis tempora et eos debitis, amet incidunt consequuntur aut aliquid,
      porro distinctio expedita repellat tempore. Similique iste dolores excepturi esse laborum ad, asperiores voluptate. Cum harum aliquid alias qui perferendis magnam maiores eligendi expedita et sapiente quibusdam animi unde minus, mollitia nihil repellat
      delectus cupiditate, architecto eveniet! Modi iusto vero molestiae laudantium, corporis optio a vel perspiciatis quisquam alias maiores ratione, ea ipsam id quam dolorem quis consequuntur. Excepturi at explicabo doloremque asperiores cupiditate?
      Cum sunt dolorem similique eveniet eligendi, obcaecati nesciunt vel perspiciatis delectus magnam, illum doloribus aut amet ipsam veritatis laboriosam quidem alias illo saepe rerum! Et dicta quo tempore eos dolore? Iste hic recusandae, blanditiis
      cumque veniam quas architecto. Repudiandae aliquam necessitatibus magni rerum quisquam eum atque dolorum placeat dignissimos. A qui cumque voluptates sint optio voluptatibus vitae harum tenetur reiciendis id eos quidem tempore laborum in error obcaecati
      odit ex et ratione, eaque assumenda aut eius! Impedit, quis. Nulla inventore neque omnis qui eveniet molestias eius sint vel voluptas! Tempora, animi? Sequi veniam iure quibusdam repellat, dolorum, id earum accusamus reiciendis at possimus adipisci
      a similique?

A: do you want something like this? If you want this, simply delete the html in the video section and use the code snippet.

var video = document.querySelector('#ds');
window.onscroll = () => {
  if (document.querySelector('.hd-a').getBoundingClientRect().bottom < 0) {
    video.pause();
  } else {
    if (!video.play()) {
      video.play();
    }
  }
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.hd-a {
  position: relative;
  width: 100%;
  height: 100vh;
  background-color: red;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.hd-a #ds {
  min-width: 100vw;
  position: absolute;
}

.hd-a .desc {
  position: absolute;
  z-index: 99;
  color: #fff;
  text-align: center;
  padding-left: 50px;
  padding-right: 50px;
}

.desc p {
  margin-top: 50px;
}

Lorquasi, velit, quam sit ipsa officia illo veritatis expedita

Loremque adipisci sequi animi dicta!

  <video autoplay muted loop id="ds">
                <source src="https://cdn.videvo.net/videvo_files/video/free/2021-05/small_watermarked/210512_01_Music_4k_009_preview.webm" type="video/mp4">
            </video>

Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem amet officia mollitia repudiandae autem, voluptates cupiditate consequuntur aspernatur repellat atque eum error dolorum quos numquam natus! Officia laborum facere earum iste molestias dignissimos
  laboriosam, aliquam vel incidunt fuga. Dolorem doloribus veritatis magni expedita voluptas sit earum laudantium blanditiis reprehenderit quis! Impedit excepturi consequuntur porro tempore atque sequi eaque unde ut neque rerum odio nisi repellendus veniam
  voluptates veritatis doloribus cumque consequatur sunt beatae aperiam quasi, non sapiente! Praesentium, eaque aut! Amet illo nostrum non qui blanditiis repellat fugiat, voluptatum reiciendis, asperiores totam harum aliquid facere consectetur, corporis
  laboriosam porro impedit delectus quas natus! Sequi deserunt aliquid veritatis ea doloribus quasi neque molestias atque, itaque dicta corrupti, necessitatibus a quaerat, quia explicabo quisquam iste est aut deleniti id. Sed blanditiis nemo eos debitis
  perferendis suscipit hic nesciunt, illo ducimus praesentium laborum quaerat eum. Voluptate, cum obcaecati? Voluptatem perferendis in animi sit repellat! At dolor eveniet dolores iure est sunt dolorem magnam illum ea, numquam sapiente atque eius voluptates
  veniam, nihil expedita laborum quis ipsam labore officiis animi. Exercitationem, qui possimus nesciunt maxime id voluptates maiores, error unde modi debitis similique nihil temporibus! Quae eius iure minus ut eaque architecto quaerat similique incidunt
  modi illum, expedita natus tenetur. Similique possimus quam vero quia sit doloremque tempore. Beatae ipsa similique voluptatibus maiores perspiciatis excepturi voluptates? Doloribus impedit dolor debitis quibusdam qui quidem! Incidunt itaque, vitae
  laboriosam, optio impedit aliquid at cumque fugiat consequuntur praesentium vel excepturi nihil omnis animi voluptatum officiis voluptatem vero aspernatur aliquam? Omnis itaque ratione ducimus inventore debitis, pariatur, similique iste cumque nobis
  exercitationem rem consequatur possimus veniam soluta, praesentium ut repellat illum. Nemo odio, quaerat numquam, expedita obcaecati saepe culpa esse amet provident ratione unde officiis. Quod aperiam molestiae ex quaerat animi iusto autem tempora,
  neque consectetur nostrum assumenda mollitia natus tempore, dolorum soluta asperiores vel ipsam facilis non aliquam! Doloribus, adipisci at praesentium accusantium laborum aut dicta cum atque dolore qui quis magnam fuga delectus cumque error enim esse
  eum? Nulla doloribus quis voluptas repellat molestias cupiditate est quibusdam. Expedita tempore corporis non iure animi, amet esse quaerat error impedit aliquam ipsum, et odio, accusamus earum ratione ut. Omnis ipsam iure error ullam ducimus sunt consequatur
  neque itaque culpa aliquid hic quo, ratione nulla a amet earum quae iste minus fuga reiciendis nam dolore debitis molestiae. Qui, sapiente. Et illo vel voluptas nioluptas hic eum modi, sint temporibus officia assumenda est corrupti sed quisquam minus
  ab inventore eveniet eos sequi consequatur. Labore, delectus doloribus iure id odit nemo accusantium fugit exercitationem odio nobis consequatur error placeat assumenda pariatur adipisci libero nesciunt voluptas laborum ratione minima. Eius, facere,
  recusandae pore voluptatem quaerat fugit cumque quam ex eaque, dolores, repellendus earum officia sapiente magnam aliquam optio! Alias quia autem debitis consequuntur temporibus ipsam quam placeat eum iste atque ea quod nobis labore non impedit voluptas
  dolor recusandae eaque nam omnis fugit, at, delectus quae? Porro error aut rem at earum, officiis placeat magnam magni eius. Quasi eveniet ex quaerat dolorem impedit corporis aspernatur, non consequuntur.


text:
Q: Invoke Inner class method having parameters using reflection I am trying to test my code though knowing using reflection is not a good way of testing. I have a outer class as public having private inner class with a public method as below,
public class Outer {

    private class Inner {
        private int var = 1;

        public Inner(int a) {
            System.out.println("___");
        }

        public void test(int a) {
            System.out.println("Hey");
        }
    }
}

My main java class looks like below
main() {
    Outer b = new Outer();
    System.out.println(b);
    Class<?> innerClass = Class.forName("car.Outer$Inner");

    Constructor<?> constructor = innerClass.getDeclaredConstructor(Outer.class, 1);

    constructor.setAccessible(true);
    Object c = constructor.newInstance(b,b);

    Method method = c.getClass().getDeclaredMethod("test");
    method.setAccessible(true);
    method.invoke(c, 1);
}

This is throwing

Exception in thread "main" java.lang.NoSuchMethodException: car.Outer$Inner.test()
      at java.lang.Class.getDeclaredMethod(Class.java:2130)
      at car.A.main(A.java:36)

How to invoke inner class method taking parameter using reflection?

A: You need to supply the argument class(es) in the call to getDeclaredMethod(). When you call getDeclaredMethod(), the first argument is the name of the method you want looked up and any remaining arguments are the classes of the argument(s) to the method you want. This is how getDeclaredMethod() distinguishes between overloaded method names to get one particular method. Since you have supplied no additional arguments, getDeclaredMethod() is looking for a method named test that takes no arguments. You're getting an exception because you have no such method in class Outer$Inner. The only test method you do have takes an int parameter`, so the following should do what you want:
Method method = c.getClass().getDeclaredMethod("test", int.class);

Here, int.class is the Class object corresponding to the primitive argument type int.


text:
Q: MVC's Kendo UI loses masking on post and on UI. I'm trying to mask a phone number in the following piece of code:
@Html.Kendo().MaskedTextBoxFor(model => model.Student.HomePhoneNumber).Mask("(999) 000-0000").HtmlAttributes(new { @class = "form-control" }).UnmaskOnPost(true)

So the UnmaskOnPost(true) unmasks the value of the phone number (turns (xxx)-xxx-xxxx to xxxxxxxxxx). This is the intended behavior
However, if there's any validation error in my MVC page, the text box containing the phone number displays the unmasked value of xxxxxxxxxx instead of (xxx)-xxx-xxxx.
Any help is greatly appreciated.

A: Add ApplyFormatInEditMode = trueto your data annotaion:
[DisplayFormat(DataFormatString = "{0:(ddd)-ddd-dddd}", ApplyFormatInEditMode = true)]

change (ddd)-ddd-ddddto proper one if isn't correct.


text:
Q: Can the Lagrange Interpolating polynomial be used in a machine learning algorithm? My understanding of the Lagrange interpolating polynomial is that given $\space n \space$ points, we can fit a polynomial of degree $\space n+1 \space$ as a means of approximating the values between the points.
This polynomial is defined as:
$$L_n(x) = {(x-x_1)(x-x_2)...(x-x_n) \over (x_0-x_1)(x_0-x_2)...(x_0-x_n)}y_0 +...+ {(x-x_1)(x-x_2)...(x-x_{n-1}) \over (x_n-x_1)(x_n-x_2)...(x_n-x_{n-1})}y_n$$
Could this be more reliable in a machine learning algorithm that deals with one numerical input and one numerical output, where the training data is a set of points $\space (x,y)  \space$, with $\space x=input \space$ and $\space y=output \space$ . Rather than using neural networks?

A: The problem with interpolation polynomials is that "they are trying too hard to fit the data points" and end up missing the structure of the dataset. This problem is called overfitting and you should be aware of it. It happens when you use a larger than necerssary degree polynomial for regression.


text:
Q: Problem with image caching I have an iPhone app with a UITableView. I'm download images from internet and put them in the TableViewcell. First I cache the images and then I load them into the TableView. On the first sight, it looks like the images cached well and are loaded fine in the tableview. But when I scroll the TableView, the app crashes and I get an error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSPathStore2 isFileURL]: unrecognized selector sent to instance 0x6e4d800'

I used this tutorial/example to cache the images: http://www.makebetterthings.com/blogs/iphone/image-caching-in-iphone-sdk/
Does anyone know what's going wrong and what I have to do to solve this problem?
Thanks,
Jelle

A: You're calling a method on an NSString that doesn't exist (the method is isFileURL). The method exists on NSURL so I guess the solution is something like this :
// Turn the string into a url
NSString *myPath = @"/cache/image1.png";
NSURL *myURL = [NSURL fileURLWithPath:myPath];

// This line would previously have crashed
BOOL isFile = [myURL isFileURL];

The other possibility is that you think you are using an NSURL but you forgot to retain it :)


text:
Q: Passing an array to another method in an applet So I am writing a program that randomly picks 10 cards in a deck and displays them. However, I can't figure out how to pass the array with I use to store the random cards to the method in which I print out the cards. This is my code:
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Image;
import java.applet.Applet;
import java.lang.Math;
import java.util.Random;

public class unit12Assignment extends Applet
{
    Image card1 ... card52;

public void init()
{
    card1 = getImage( getDocumentBase(), "c1.gif" );
        ...
    card52 = getImage( getDocumentBase(), "sk.gif" );
}

public void getCards(String[] cardSelection)
{
    String cardNumber;
    double cardRandom;
    int cardRandomNumber;
    Random ran = new Random();
            cardSelection = new String[10]

    for (int number = 0; number <=  9; )
    {
        cardRandom = ran.nextInt(52) + 1;
        cardRandomNumber = (int) Math.round( cardRandom );

        if ( cardRandomNumber > 0 && cardRandomNumber <= 52 )
        {
            cardNumber =  "card" + cardRandomNumber;
            number++;
        }
    }
}

    // i wanna pass it to this method
public void paint(Graphics g)
{
    setBackground( Color.green );
    g.drawImage( cardSelection[0], 10, 10, this);
    g.drawImage( cardSelection[1], 90, 10, this);
    g.drawImage( cardSelection[2], 170, 10, this);
    g.drawImage( cardSelection[3], 250, 10, this);
}

}
Its seems like a simple problem but I completely forgot how to do it. Any help is appreciated. Thanks!

A: You need to make the paint method accept a String[].  Then you can pass in your array when you call paint.
For example:
public void main(String[] args) {
  String[] myArray = makeArray();
  printArray(myArray);
}

public String[] makeArray() {
  return new String[] {"element0", "element1", "element2"};
}

public void printArray(String[] array) {
  for (String element : array) {
    System.out.println(element);
  }
}

A: Declare String[] cardSelection; as an instance variable (next to the class declaration).
Then, in the getCards() method instantiate the array:
cardSelection = new String[10];


text:
Q: Returning a structure results in gibberish I'm using structures in C and when I try to return a structure from a function it always results in gibberish when I try to print the contents of that structure in main.
Here is my code :
#include <stdio.h>
struct etudiant
{
    int a;
    int b;
    int c;
};
typedef struct etudiant ETD;

ETD ajouter_etd()
{
    ETD e;
    scanf("%i%i%i", e.a, e.b, e.c);
    return e;
}

void main()
{
    ETD e;
    e = ajouter_etd();
    printf("%i%i%i", e.a, e.b, e.c);
}

A: You must pass the addresses of your variables to scanf as it needs to know where in memory to place the results of its conversions. This is done with the address-of operator (&).
#include <stdio.h>

typedef struct etudiant {
    int a;
    int b;
    int c;
} ETD;

ETD ajouter_etd(void)
{
    ETD e;
    scanf("%i%i%i", &e.a, &e.b, &e.c);
    return e;
}

int main(void)
{
    ETD e;
    e = ajouter_etd();
    printf("%i%i%i\n", e.a, e.b, e.c);
}


text:
Q: How to change css property with function in react I want to change visiblty properties with a function.  I want when user click on the button change visible properties on textarea. How can ı make ?
enter image description here

A: Make a state variable to keep track of the textarea visible state, then in the textarea tag, add style for using that state variable.
Then onlick event, toggle the state variable either to false or true.

A: const [show, setShow] = useState(false)

const changeVisibility = () => {
  setShow(!show)
}

return (
<>

        {show && (

                <textarea rows="2"></textarea>

        )}

    <button onClick={changeVisibility}>show</button>
</>
);

A: Here's a simple example.

*

*Use useState to manage the visibility of the text area.

*Attach a handler to the button that calls a function that updates the state.

*Use a class called hidden. Initially the textarea won't have it but you can conditionally add it if the updated state tells you to.

const { useEffect, useState } = React;

function Example() {

  const [ visible, setVisible ] = useState(true);

  function handleClick() {
    setVisible(!visible);
  }

  return (

      <button onClick={handleClick}>Toggle visibilty</button>
      <textarea className={!visible && 'hidden'}></textarea>

  );
};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
.hidden { visibility: hidden; }


text:
Q: Appending textbox to a div in dojo I created a div and a textbox using the following code
     var left_div = dojo.create('div', {
        id: 'left_div'
    }, child.borderContainer.domNode, 'first');

    child.borderContainer.clientName = new dijit.form.ValidationTextBox({
        name:           'clientName',
        placeHolder:    'client name'
    });

Now, I have to append the clientName to the left div.

A: If clientName  is a widget you can use
widget.placeAt(parentNode)

A: This should do the trick:
child.borderContainer.clientName = new dijit.form.ValidationTextBox({
        name:           'clientName',
        placeHolder:    'client name'
}, left_div);

The second parameter for a widget constructor is usually the dom node to place the widget at.  From the API:

Usage:
  var foo = new dijit.form.ValidationTextBox(/* Object? / params, / DomNode|String */ srcNodeRef);