text:
Q: Google Play services resources were not found. 'AdsMob' I am getting this error when I try to load and InterstitialAd from google AdMob. I know that I have written the code correctly. As I followed the short tutorial on https://developers.google.com/mobile-ads-sdk/docs/admob/advanced#play
All the happens is I get and error in the Logcat. What might I be doing wrong.
Here is the code:
public class Pref extends PreferenceActivity implements
        SharedPreferences.OnSharedPreferenceChangeListener {

    /** The view to show the ad. */
      private AdView adView;

      /* Your ad unit id. Replace with your actual ad unit id. */
      private static final String AD_UNIT_ID = "MY_ID";
      private static final String inAD_UNIT_ID = "MY_ID";
      private InterstitialAd interstitial;

    @SuppressWarnings("deprecation")
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.ad_layout);

        //addPreferencesFromResource(R.xml.preferences);
        //getPreferenceManager()
                //.setSharedPreferencesName("com.gordondev.south_korea");
        //addPreferencesFromResource(2130903040);
        //getPreferenceManager().getSharedPreferences()
            //  .registerOnSharedPreferenceChangeListener(this);

        // Create the interstitial.
        interstitial = new InterstitialAd(this);
        interstitial.setAdUnitId(inAD_UNIT_ID);

        // Create ad request.
        AdRequest adRequest = new AdRequest.Builder().build();

        // Begin loading your interstitial.
        interstitial.loadAd(adRequest);

        // Create an ad.
        adView = new AdView(this);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId(AD_UNIT_ID);

        // Add the AdView to the view hierarchy. The view will have no size
        // until the ad is loaded.
        LinearLayout layout = (LinearLayout) findViewById(R.id.adview);
        layout.addView(adView);

        //((LinearLayout)view).addView(adView);

        // Create an ad request. Check logcat output for the hashed device ID to
        // get test ads on a physical device.
        AdRequest adRequest1 = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
            .build();

        // Start loading the ad in the background.
        adView.loadAd(adRequest1);

    }

    // Invoke displayInterstitial() when you are ready to display an interstitial.
      public void displayInterstitial() {
        if (interstitial.isLoaded()) {
          interstitial.show();
        }
      }

Here is the Logcat error:
03-13 16:49:41.565: I/Ads(29755): Use AdRequest.Builder.addTestDevice("099098AA8954CC0C01AD412143D81BDD") to get test ads on this device.
03-13 16:49:41.565: I/Ads(29755): Starting ad request.
03-13 16:49:41.575: E/GooglePlayServicesUtil(29755): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
03-13 16:49:41.575: I/Ads(29755): Use AdRequest.Builder.addTestDevice("099098AA8954CC0C01AD412143D81BDD") to get test ads on this device.
03-13 16:49:41.575: I/Ads(29755): Starting ad request.
03-13 16:49:41.585: E/GooglePlayServicesUtil(29755): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
03-13 16:49:41.625: E/GooglePlayServicesUtil(29755): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
03-13 16:49:41.635: E/GooglePlayServicesUtil(29755): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
03-13 16:49:41.645: E/GooglePlayServicesUtil(29755): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
03-13 16:49:41.645: E/GooglePlayServicesUtil(29755): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
03-13 16:49:42.365: I/Ads(29755): Ad finished loading.
03-13 16:49:43.085: I/Ads(29755): Scheduling ad refresh 60000 milliseconds from now.
03-13 16:49:43.085: I/Ads(29755): Ad finished loading.

A: I have the same error running my apps on my device. It seems that the problem have to do with your device.Try using your app to another device
If the ads will appear, your code seems to be fine.
Also you can change this line to this:
AdRequest adRequest = new AdRequest.Builder().build();

Make sure that you have the correct google play libraries in your project

If you have done these : https://developers.google.com/mobile-ads-sdk/docs/
Your app  ads should work perfectly

A: 03-13 16:49:41.585: E/GooglePlayServicesUtil(29755): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.

is a benign error. If the ads are showing don't worry about it.
Your code looks fine.


text:
Q: Open custom Wordpress admin menu item in external URL I have this code snippet which creates custom Wprdpress admin menu items and they show up nicely. Since these are links to the external URL I would like to open them in the external tab. Can't figure out how to to that though. Any suggestion would be appreciated.
add_action('admin_menu', 'admin_menu_add_external_links_as_submenu');

function admin_menu_add_external_links_as_submenu() {
    global $submenu;

    $menu_slug = "externallink"; // used as "key" in menus
    $menu_pos = 1; // whatever position you want your menu to appear

    // create the top level menu
    add_menu_page( 'external_link', 'Tutorials', 'read', $menu_slug, '', '', $menu_pos);

    // add the external links to the slug you used when adding the top level menu
    $submenu[$menu_slug][] = array('Yahoo', 'manage_options', 'https://www.yahoo.com/');
    $submenu[$menu_slug][] = array('Google', 'manage_options', 'https://www.google.com/');
}

A: To make it work as you expect you have to create the extra jQuery function admin_menu_add_external_links_as_submenu_jquery which will open your submenu items in a new tab. This function is checking for the div's ID which is now set for each of your submenu items newtab and newtab2 and the final result is target: _blank (new window) output. Code goes into your active theme or child theme functions.php file. Tested and works.
add_action('admin_menu', 'admin_menu_add_external_links_as_submenu');
add_action( 'admin_head', 'admin_menu_add_external_links_as_submenu_jquery' );

function admin_menu_add_external_links_as_submenu() {
    global $submenu;

    $menu_slug = "externallink"; // used as "key" in menus
    $menu_pos = 1; // whatever position you want your menu to appear

    // create the top level menu
    add_menu_page( 'external_link', 'Tutorials', 'read', $menu_slug, '', '', $menu_pos);

    // add the external links to the slug you used when adding the top level menu
    $submenu[$menu_slug][] = array('
Yahoo
', 'manage_options', 'https://www.yahoo.com/');
    $submenu[$menu_slug][] = array('
Google
', 'manage_options', 'https://www.google.com/');
}

function admin_menu_add_external_links_as_submenu_jquery()
{
    ?>

    <?php
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it ok to use the universal selector in bootstrap 3.1? I am working a lot with position absolute and i don't want to set position relative on the parent of each DOM element every single time. To skip that i use
body *{
    position:relative;
}

but i don't know if this is a good idea or if it will break something in bootstrap.
can anyone help me on this? or tell me if there is a better way to do this?

A: Yes, you can use the universal selector, but I suggest you not to use it(*). Instead use selector in more appropriate way like:
.relative {
  position: relative;
}

And, give the parent element class="relative".
This way, you can position only the required elements, and it may increase web-page performance.


text:
Q: Which C# type should one prefer for defining lists in DTOs? I was wondering if there is a recommended approach to defining a property of a plain object that is used for data transfer, for example via a REST-API which is a list of other objects. Which C# type should one prefer for defining those?

*

*List<T> maybe? It's short, everybody knows it, and we don't have to cast or transform it into a list to do sorting, modifying etc.

*ICollection<T> maybe? It's an interface that has a clear meaning and supports other types of enumerations, which avoids transforming those into a list on the sender side.

*IEnumerable<T> maybe? It's even stricter than ICollection.

*Arrays, T[] maybe? Even shorter, but you need to transform those from lists and vice versa. Not so nice for working with out-of-the-box (well, REST-response).

A: Generally speaking DTOs (Data Transfer Objects) need to be serialized in order to be transferred, for example to JSON.
Types like IList and IEnumerable can easily be serialized but are not so easy to deserialize because the serializer has to pick a concrete type.
In my experience the best balance between convenience, functionality and efficiency is List<T> but your specific use case may justify a different choice.
Note that because DTOs typically reference concrete types, they can not be tested and therefore should not contain any methods.


text:
Q: Why is the determiner after the verb in "We were both tired" and "We have both seen the movie"? There are two sentences to determiner below:

*

*We were both tired.

*We have both seen the movie.

What I know is that the determiner is used in front of noun or pronoun, but the sentences of examples show that the determiner is located after verb.
I would like to know reason why the determiner is after verb.

A:
We were both tired.

There is no determiner.  "Tired" is an adjective.
But the word "both" can be a determiner:

Both cats were black, which I took as an omen.

We have both seen the movie.

Find the determiner.  It is the definite article: the.


text:
Q: What are the possible Clifford functions of a curve? Let $C$ be some smooth proper curve of genus $g$ over an algebraically closed field $k$. In order to understand special divisors on C one may consider the following function c(r), which I will call Clifford's function. It assigns to a number $0 \leq r \leq g-1$ the (minimal degree of a divisor such that r(D) = dim|D| = r) - 2r. Clifford's theorem states that $c(r) \geq 0$. Looking at a $D \in g^1_d$ we notice that $r(nD) \geq n$ and hence $c(r) \leq rc(1)$. From this I arrive at the guess that $c$ is always concave. In fact I guess that there exists some generic Clifford function $C_{max}$ and that we can characterize all Clifford functions as concave functions $0 \leq c \leq C_{max}$.
In my searches I have only been able to find results on special values of the Clifford function (for instance $c(1)$ corresponds to the gonality of a curve), but none on this function as an object. Is it possible to characterize all functions occurring as the Clifford function of some curve $C$?

A: This is a partial answer concerning the existence of such a $C_{max}$ and its concavity. The Brill-Noether theorem states that on a generic curve a $g^r_d$ exists iff $g-(r+1)(g-d+r) \geq 0$. This is equivalent to $d \geq g+r-\frac{g}{r+1}$. It follows that the generic Clifford function is $c(r) = g-r-\lfloor\frac{g}{r+1}\rfloor$ which again by Brill-Noether theory is the maximal such function.
It remains to show that this function is concave which is equivalent to showing that $f(r) = \lfloor\frac{g}{r+1}\rfloor$ is concave within the range. In fact it is enough to show that $f(r-1) + f(r+1) \geq 2 f(r)$ for integers $1 \leq r \leq g-2$. Setting $h(r) = \frac{g}{r+1}$, it is enough to show $h(r-1) + h(r+1) -2 \geq 2h(r)$ for such $r$. This is an easy calculation.
To continue it is probably helpful to understand the basics of the intersection of Brill-Noether loci in the moduli space of curves.


text:
Q: Add corresponding elements in two arrays of different length I have two arrays:
a = [50, 17, 54, 26]
b = [19, 7, 8, 18, 36, 8, 18, 36, 18, 14]

I want to add to the elements of b the corresponding elements of a. When the elements of a runs out, I want to cycle through a to supply the elements. The result should be:
c = [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]

How could I go about this?

A: b.zip(a * (b.size / a.size + 1)).map { |o| o.reduce(:+) }
#⇒ [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]

Or, much better and more concise from @SimpleLime:
b.zip(a.cycle).map(&:sum)

A: a = [50, 17, 54, 26]
b = [19, 7, 8, 18, 36, 8, 18, 36, 18, 14]

enum = a.cycle
b.map { |e| e + enum.next }
#=> [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]

A: Another one, using map, with_index and modulo:
b.map.with_index { |e, i| e + a[i % a.size] }
#=> [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]

A: EDIT: Only works in rails
def add_arrays(array_a, array_b)
  results = []
  array_b.in_groups_of(4).each do |group|
    group.each_with_index do |record, j|
      results << (record + array_a[j])
    end
  end
  results
end

Not tested it but that should do the trick


text:
Q: What are sublinear algorithms? I have been asked the following question by one of my fellow mates.
Which of the following expressions is not sublinear?
O(log log n)
O(n)
O(logn)
O(root(n))

I have gone through https://en.wikipedia.org/wiki/Time_complexity#Sub-linear_time but couldn't but I am not sure that I have understood it completely. Could someone point me in the right direction.

A: A function, f(x), is said to grow faster than another function, g(x), if the limit of their ratios as x approaches infinity goes to some positive number (or infinity), as seen in the definition below.

In the case of sublinear, we want to prove that a function grows slower than c*n, where c is some positive number.
Thus, for each function, f(n), in your list, we want the ratio of f(n) to (c*n). If the limit is 0, this means the function, f(n), is sublinear. Otherwise it grows at the same (approximate) speed of n or faster.
lim n->inf (log log n)/(c*n) = 0 (via l'Hopital's)

(sublinear)
lim n->inf (n)/(c*n) = 1/c != 0

(linear)
lim n->inf (log n)/(c*n) = 0 (via l'Hopital's)

(sublinear)
lim n->inf (sqrt(n))/(c*n) = 0

(sublinear)

A: I think I understood why you're confused: the wikipedia page you link uses Little-Oh notation:

Sub-linear time
An algorithm is said to run in sub-linear time (often spelled sublinear time) if T(n) = o(n)

Beware that T(n) = o(n) is a stronger requirement than saying T(n) = O(n).
In particular for a function in O(n) you can't always have the inequality
f(x) < k g(x) for all x > a

satisfied for every k you choose. y=x and k=1 will prove you wrong and little-oh notation requires every k to satisfy that expression.
Any O(n) function is not also in o(n). Thus your non-sublinear expression is O(n).
I recommend reading this answer to continue your studies


text:
Q: Converting a String to a Date -> FormatException Im desperately trying to convert the following String to a Date.
I did research on how to do this, but was not able to do it successfully.
So basically, I have two Datepicker-Controls on my form.
When the form is being saved, I always want to have the Date from Control #1, but keep the Time from Control #2.
I am trying as following:
Dim strDatum As String = dtpDatum.Value.ToString() '= 03.01.13 00:00:00
Dim strStart As String = dtpVon.Value.ToString()   '= 23.01.13 10:39:01
Dim sStartDatum = Strings.Left(strDatum, 8) & " " & Strings.Mid(strStart, 10, 9) '= 03.01.13 10:39:01

'here I'm trying to convert my new String to a Date and assign it to my a parameter
.Parameters("@dStartZeit").Value = DateTime.ParseExact(sStartDatum, "DD.MM.YY HH:mm:ss", New Globalization.CultureInfo("en-US"))

I get an "FormatException" when executing my query.
What am I doing wrong here?
Thanks!

A: Custom format strings are case-sensitive. Try:
DateTime.ParseExact(sStartDatum, "dd.MM.yy HH:mm:ss", New Globalization.CultureInfo("en-US")`

A: formating strings requires case-sensitivity.
parameter.Parameters("@dStartZeit").Value = DateTime.ParseExact(sStartDatum, "dd.MM.yy HH:mm:ss", New Globalization.CultureInfo("en-US"))


text:
Q: a list of 20 numbers,each number generate 1-100,how to make no repitition? I have looked at a lot of others,i still don't get how to input the non-repeat code into my code below.Newbie here,require someone to explain.
import java.util.Random;

class random{
public static void main(String[] args) {
    Random dice = new Random();
    int number;
    for (int counter = 1; counter <= 20; counter++) {
        number = 1 + dice.nextInt(100);
        System.out.println(number + " ");
    }
}

A: First add the random number to a set, this will stop duplicate entries. Then loop through and print out the set. There are a couple different ways you could do this but here is a way with the least amount of change to your code:
Set<Integer> numbers = new HashSet<Integer>();
Random dice = new Random();
int number;
for (int counter = 1; counter <= 20;) {
    number = 1 + dice.nextInt(100);
    if(numbers.add(number)) { //Only increment the counter if the number wasn't already in the set
        counter++;
    }
}
for(Integer num : numbers) {
    System.out.println(num + " ");
}

A: A little bit simpler approach than suggested by MrMadsen is to control the set size:
Set<Integer> numbers = new LinkedHashSet<>();
Random dice = new Random();
while(numbers.size() < 20)
    numbers.add(dice.nextInt(100)+1);
for(Integer num : numbers) {
    System.out.println(num + " ");
}

Just for completeness here's Java-8 solution:
new Random().ints(1, 101).distinct().limit(20).forEach(System.out::println);

A: instead of just printing the random number have a set(which allows only unique elements) to capture the number and have a if condition to check the length of the set (set.size() == 20) come out of the loop until then you run the for loop to find the random numbers. I think this will solve your problem

A: Keep track of what is generated previously. Try this
public static void main(String...args) {
        Random dice = new Random();
        Set<Integer> previouslyGenerated = new  HashSet<Integer>();
        int number = 0,counter = 0;
        while (counter <20){
            number = 1+dice.nextInt(100);
            if (!previouslyGenerated.contains(number)){
                previouslyGenerated.add(number);
                System.out.println(number + " ");
                counter++;
            }

        }

}


text:
Q: How should I write these rewrite rules in my .htaccess file I have this in my .htaccess file:
RewriteEngine on

RewriteCond %{HTTP_HOST} ^admin\.domain1\.com$ [OR]
RewriteCond %{HTTP_HOST} ^admin\.domain2\.com$ [OR]
RewriteCond %{HTTP_HOST} ^admin\.domain3\.com$
RewriteRule (.*) /path/to/directory/$1 [L]

RewriteCond %{HTTP_HOST} ^admin\.domain4\.com$
RewriteRule (.*) /different/path/$1 [L]

The first block works, but the second block gives me the following error:
Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at [no address given] to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

Apache/2.4.29 (Ubuntu) Server at admin.domain4.com.ar Port 80

What am I doing wrong??

A:
The first block works, but the second block gives me an Internal Server error:

Both rules/blocks have the same "issue". The first rule will only "work" if you have another .htaccess file in the /path/to/directory/ that also uses mod_rewrite (perhaps to route the URL?) in order to prevent an internal rewrite loop (the probable cause of your Internal Server Error).
The easiest way to resolve this, if you are on Apache 2.4, is it simply use the END flag, instead of L. For example:
RewriteRule (.*) /different/path/$1 [END]

The L flag only stops the current round of processing, it does not stop all processing by the rewrite engine. On the second pass through the rewrite engine, the pattern (.*) also matches the rewritten request /different/path/<url> which gets further rewritten to /different/path/different/path/<url> etc. resulting in an endless loop, unless there is something to stop it.


text:
Q: How to convert an object to a string in Spark? Im trying to follow the spark example - https://www.javaworld.com/article/2972863/big-data/open-source-java-projects-apache-spark.html
but get compilation error on this line -->input.flatMap( s -> Arrays.asList( s.split( " " ) ) );
Type mismatch cannot convert from JavaRDD<object> to JavaRDD<String>

Code:-
public class WordCountTask
{

    public static void wordCountJava8( String filename )
    {
        // Define a configuration to use to interact with Spark
        SparkConf conf = new SparkConf().setMaster("local").setAppName("Work Count App");

        // Create a Java version of the Spark Context from the configuration
        JavaSparkContext sc = new JavaSparkContext(conf);

        // Load the input data, which is a text file read from the command line
        JavaRDD<String> input = sc.textFile( filename );

        // Java 8 with lambdas: split the input string into words
        JavaRDD<String> words = input.flatMap( s -> Arrays.asList( s.split( " " ) ) );

        // Java 8 with lambdas: transform the collection of words into pairs (word and 1) and then count them
        JavaPairRDD<String, Integer> counts = words.mapToPair( t -> new Tuple2( t, 1 ) ).reduceByKey( (x, y) -> (int)x + (int)y );

        // Save the word count back out to a text file, causing evaluation.
        counts.saveAsTextFile( "output" );
    }

    public static void main( String[] args )
    {
        if( args.length == 0 )
        {
            System.out.println( "Usage: WordCount <file>" );
            System.exit( 0 );
        }

        wordCountJava8( args[ 0 ] );
    }
}

A: You need to use Iterable
 JavaRDD<String> words = input.flatMap(
          new FlatMapFunction<String, String>() { public Iterable<String> call(String x) {
              return Arrays.asList(x.split(" "));
            }});

Or
JavaRDD<String> words = input.flatMap(s -> Arrays.asList(s.split(" ")).iterator());

A: flatMap function should return Collection's Iterator object.
FlatMapFunction<T, R>:
        Iterable<R> call(T t)

Replace-
JavaRDD<String> words = input.flatMap( s -> Arrays.asList( s.split( " " ) ) );

With:
JavaRDD<String> words = input.flatMap(s -> Arrays.asList(s.split(" ")).iterator());


text:
Q: Generating XML from nested numbered lists in Python I have a nested, numbered list structure like this:

1.1 - "james"
  1.1.1 - "alice"
  1.2.1 - "bob"

What is the best/fastest way to turn it into an XML structure like this:
> <1>
>    <1><james/>
>       <1><alice/></1>
>       <2><bob/></2>
>    </1>
> </1>

This is super easy if the depth of the numbered lists is only 3, but in this case it is unknown, maybe up to 6.
I'm pretty sure I need to create a recursive self-referential function but need a way of putting each element in its place within the XML structure, which I'm stuck on at the moment.

A: Here's a small recursive function that will convert lists to XML strings.  Adding padding support, or limiting depth is trivial to add, but I'll leave that for you.
def xml(it, depth=1):
 s = ''
 for k, v in enumerate(it):
  s += '<%d>' % (k+1)
  if isinstance(v, list):
   s += xml(v, depth+1)
  else:
    s += str(v)
  s += "</%d>\n" % (k+1)
 return s

Here's an example usage and output.
>>> data = ['Names', ['Boy names'], ['Girl Names', ['J-Names', ['Jill', 'Jen']]]]
>>> print xml(data)
'<1>Names</1>
<2><1>Boy names</1>
</2>
<3><1>Girl Names</1>
<2><1>J-Names</1>
<2><1>Jill</1>
<2>Jen</2>
</2>
</2>
</3>'


text:
Q: Vertical Alignment Doesn't Work when Form is Added inside Div I am (desperately) trying to vertically align (middle) a form in the middle of a div. I just couldn't get it to work all, so I just went back to basics, and vertically centered a div in the middle of another:

text

This works perfectly well. I would assume that the form would behave the same but when I add it I get some really strange results:

text

    <form style='display: inline-block; vertical-align: middle;'>
        Add Something:
        <input type='text' value='nothing in there'/>
    </form>

As you can see the text is centered with respect to the blue box but not the form. Worse, not adding vertical-align: middle to the form is actually changing the position of the text (green box)

text

    <form style='display: inline-block;'>
        Add Something:
        <input type='text' value='nothing in there'/>
    </form>

I am lost. Please help!

A: I actually ended up embedding the form within the green box, declaring the form a table-cell and vertically centring it. It seems to work:

        <form style='display: table-cell; vertical-align:middle;'>
            Add Something:
            <input type='text' value='nothing in there'/>
        </form>


text:
Q: Checkboxes in child component, how to uncheck every other one when one is checked fairly new to react, so sorry in advanced. I have a need where I need to uncheck any checked checkboxes if one of them are checked. This component is a grandchild component of my app.js
App.js:
class App extends Component {

    constructor (props) {
      super (props);
      this.state = {
        data:[
          {
            id:'player1',
            toggleId: 'audio0',
            checked:false,
            isAlt:false
          },
          {
            id:'player2',
            toggleId: 'audio1',
            checked:false,
            isAlt: true
          },
          {
            id:'player3',
            toggleId: 'audio2',
            checked:false,
            isAlt:false
          },
          {
            id:'player4',
            toggleId: 'audio3',
            checked:false,
            isAlt: true
          }
        ]
      }
  }

render(){
  return (

      <Notice/>
      {this.state.data.map((dynamicComponent, i) =>
        <AudioPlayer key = {i} componentData = {dynamicComponent}/>)
      }
      {/* {audioMap.map(i => {
              return <AudioPlayer toggleId={this.state.toggleId[i]} checked={this.state.checked[i]}/>
            })} */}

  );
}
}

export default App;

In the audio player component, I have a state for active and setActive and am rendering a toggle switch child component:
AudioPlayer.js:
const [checked, setChecked] = useState(props.componentData.checked);
{/*toggle switch */}

          <ToggleSwitch id={props.componentData.toggleId} checked={checked} onChange={checked => setChecked(checked)} />

ToggleSwitch.js (taken from https://www.sitepoint.com/react-toggle-switch-reusable-component/):
const ToggleSwitch = ({ id, name, checked, onChange, optionLabels, small, disabled }) => {
  function handleKeyPress(e){
    if (e.keyCode !== 32) return;

    e.preventDefault();
    onChange(!checked)
    console.log('clicked');
  }

  return (

      <input
        type="checkbox"
        name={name}
        className="toggle-switch-checkbox"
        id={id}
        checked={checked}
        onChange={e => onChange(e.target.checked)}
        disabled={disabled}
        />
        {id ? (
           { handleKeyPress(e) }}>

        ) : null}

    );
}

// Set optionLabels for rendering.
ToggleSwitch.defaultProps = {
  optionLabels: ["On", "Off"],
};

ToggleSwitch.propTypes = {
  id: PropTypes.string.isRequired,
  checked: PropTypes.bool.isRequired,
  onChange: PropTypes.func.isRequired,
  name: PropTypes.string,
  optionLabels: PropTypes.array,
  small: PropTypes.bool,
  disabled: PropTypes.bool
};

export default ToggleSwitch;

As you can see, I'm rendering four of the same child component, and each of them have a nested toggleSwitch/checkbox. The app.js is setting the checked to false onLoad. I need to make it such that I need to uncheck any active checkbox if one gets checked.If one is checked, then uncheck any active ones. From what I understand, I need to pass data from the child to the parent, but I'm not sure how to do that. Can I even affect the state in the parent? From what I understand, I shouldn't be using props to set the state data. Any help would be appreciated. Thank you


text:
Q: Libraries imported in one .py doesnt work for imported functions of anothers .py Hope you can help me on this, here is the problem:
I'm working in "x.py" in which I have imported a lot of functions from another file named "functions.py".
Also, I have some specific functions in other files (s1.py,s2.py lets say...), which I also called in my x.py.
The problem comes when I try to use a function or library from functions.py in order to help me with those specifics files where I have other functions (s1.py, s2.py). They just simply dont recognize the libraries which I already imported... ???
Work around I've been using: declare the libraries needed directly in s1.py and s2.py, but I don't like it to much, it seems like I'm duplicating that code.
Is there any way to get my s1.py and s2.py to recognize the imported libraries in x.py???

A: Importing a module does not import all its imports by default. You do need to import functions in s1 and s2 even if you are already doing import x.
Or alternatively, you could do from x import functions inside s1 and s2. But personally I'm not sure if I would ever do that - it obfuscates things a bit, and one might say that code duplication is not a thing in the case of imports. Maybe it would make sense on a conceptual level: we import functions via x because the functions are specific to x. But in such case I would make x a package and put functions in that package (in which case the import statement would incidentally look the same). But if functions is not specific to x, i.e. it is expected to be useful for various modules unrelated to x, then don't import it via x.
If you're concerned about the performance impact of multiple imports, this explains that there is none.


text:
Q: Can I cast an unknown object to an interface so I can access its properties in C#? I'm trying to not repeat code, so I have a method that does a quick transform on the property of an interface.
I have 3 concrete classes that make use of this interface, and I want them all to be able to use this method.
The problem comes when I get one of these objects out of Session. I don't see any way to cast it properly.
public ActionResult GetItems()
{
     details = (IHeader<IDetail>)Session["SelectedHeader"].Details // Throws invalid cast
     return Json(details);
}

// My interface and class examples:
interface IHeader<T> where T: IDetail
{
     IList<T> Details { get; set; }
}

class ConcreteHeader : IHeader<ConcreteDetail>
{
     public IList<ConcreteDetail> Items { get; set; }
}

class ConcreteDetail : IDetail
{
    ...
}

I can't use generics because this is an action method in ASP.NET MVC 3 (unless there is a trick to that). Is this possible, or do I have to write a method for each class?
EDIT: Not sure if this is clear from original question:
What goes into session is any one of the concrete objects:
Session["SelectedHeader"] = new ConcreteHeader() { Details = new List<ConcreteDetail>() };

A: You need to wrap your cast with parentheses:
details = ((IHeader<IDetail>)Session["SelectedHeader"]).Details;

A: If you're using .NET 4.0, simply cast using the dynamic keyword to ensure proper automagical type resolution:
// note intellisense won't work when you use dynamic keyword...
var details = ((dynamic)Session["SelectedHeader"]).Details;

A: Seems like you just ran into the wonderful world of co- and contravariance. I wrote a blog post about it which tries to explain it as simple as I could.
Bottom line: you can't cast IHeader<ConcreteDetail> to IHeader<IDetail> prior to .NET 4.0.
Starting from .NET 4.0 you can use the in and out keywords in order to allow this. You could possibly define your interface as interface IHeader<out T>.
In case you don't use .NET 4.0 yet, you can work around the issue by creating a new lambda:
details = () => Session["SelectedHeader"].Details;


text:
Q: Replace a span tag with an anchor tag using a Python regex I have an HTML string, and I want to replace  tags with  tags.
From this:

        @Joseph Walters

    hi

to this:

    @Joseph Walters
    hi

I want 3 groups using RegEx: data-oe-model, data-oe-id, and name @Joseph Walters.
Note: data-oe-model and data-oe-id need to combine into href.
Is this possible with a Python RegEx?
I have tried this.

A: You can use the following to match:
(.*?)\

And replace with the following:
\4

See DEMO

A: You can get the values for data-oe-model & data-oe-id first. And then use re.sub
a="""@Joseph Walters hi"""
data_oe_model = re.findall(r'data-oe-model="(.*?)"', a)[0]
data_oe_id = re.findall(r'data-oe-id="(.*?)"', a)[0]
b = re.sub('span data-oe-model="(.*?)" data-oe-id="(.*?)"', 'a href='+data_oe_model+'/'+data_oe_id, a)

print  b

Output: @Joseph Walters hi

Note: Do some validations while getting the values by list indexing.


text:
Q: Error in downloading IcedTea web Start I executed the command:
sudo apt-get install icedtea-netx

...and this error was displayed:
Error in downloading IcedTea web Start..

A screenshot of the terminal session:

Please Help!

A: I suspect that only one line is present in /etc/environment file.
Open the file /etc/environment in an editor
sudo nano /etc/environment

And check the double quote at the end of the line. Compare the content with the line below, note the double quote at end of the line.
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"


text:
Q: Documentation on writing buildout recipes I am trying to find tutorials on how to write buildout recipes. I haven't found any, except the one on buildout site. But it is very rudimentary. Is there a good tutorial for writing buildout recipes?

A: http://pypi.python.org/pypi/ZopeSkel/ has a template for a buildout recipe.  That at least gets you started regarding having a skeleton for adding your own code.
http://pypi.python.org/pypi/zc.buildout#id1 has some information on which methods you need to implement.
Best way to learn it is by looking at an existing recipe to see how it gets done. I'd suggest my own recipe :-) :
https://svn.plone.org/svn/collective/buildout/collective.recipe.backup/trunk/

A: A quick google search came back with the following:
http://docs.plone.org/old-reference-manuals/buildout/creating.html
And the answers in the following Stack Overflow question look pretty helpful as well:
Better resources to learn buildout

A: Here's a short tutorial with basic information http://grok.zope.org/documentation/tutorial/introduction-to-zc.buildout/writing-your-own-recipes


text:
Q: How to disable Camera and Screen Share for all applications (globally) in mac Using MDM? We know that using MDM we can handle Privacy Preferences Policy Control in mac.

I am able to disable Screen Sharing and Camera feature for the
Particular Application.

Is there any way by which we can disable this globally for all applications?
Payload Example
Device Management Profile
PrivacyPreferencesPolicyControl.Services

A: The only MDM I currently have access to is Jamf Pro.
In Jamf Pro create a new configuration profile and in the left hand list select "Restrictions". Now in the main window select "Functionality" and the second and third items control the camera and screen recording.


text:
Q: TCP connections are stacked until 65k when using HttpWebRequest fetching function - internet connectivity is lost I don't understand what may cause this error
I am using the below function with about 1000 concurrent connections
Each connection uses a different webproxy
After a while like 15 minutes working, the established TCP connection count starts to stack and internet connectivity becomes lost
When i do not use any webproxy, i do not encounter any error
I am using below function to retrieve active TCP connections count
var properties = IPGlobalProperties.GetIPGlobalProperties();

I don't see any leak in my function
So i need your help to solve this annoying problem
c# .net 4.6.2
Here the statuses of active TCP Connections when this problem occurs

public static cs_HttpFetchResults func_fetch_Page(
    string srUrl, int irTimeOut = 60,
    string srRequestUserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0",
    string srProxy = null, int irCustomEncoding = 0, bool blAutoDecode = true, bool blKeepAlive = true)
{
    cs_HttpFetchResults mycs_HttpFetchResults = new cs_HttpFetchResults();
    mycs_HttpFetchResults.srFetchingFinalURL = srUrl;

    HttpWebRequest request = null;
    WebResponse response = null;

    try
    {
        request = (HttpWebRequest)WebRequest.Create(srUrl);
        request.CookieContainer = new System.Net.CookieContainer();

        if (srProxy != null)
        {
            string srProxyHost = srProxy.Split(':')[0];
            int irProxyPort = Int32.Parse(srProxy.Split(':')[1]);
            WebProxy my_awesomeproxy = new WebProxy(srProxyHost, irProxyPort);
            my_awesomeproxy.Credentials = new NetworkCredential();
            request.Proxy = my_awesomeproxy;
        }
        else
        {
            request.Proxy = null;
        }

        request.ContinueTimeout = irTimeOut * 1000;
        request.ReadWriteTimeout = irTimeOut * 1000;
        request.Timeout = irTimeOut * 1000;
        request.UserAgent = srRequestUserAgent;
        request.KeepAlive = blKeepAlive;
        request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

        WebHeaderCollection myWebHeaderCollection = request.Headers;
        myWebHeaderCollection.Add("Accept-Language", "en-gb,en;q=0.5");
        myWebHeaderCollection.Add("Accept-Encoding", "gzip, deflate");

        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

        using (response = request.GetResponse())
        {
            using (Stream strumien = response.GetResponseStream())
            {
                Encoding myEncoding = Encoding.UTF8;
                string srContentType = "";

                if (response.ContentType != null)
                {
                    srContentType = response.ContentType;
                    if (srContentType.Contains(";"))
                    {
                        srContentType = srContentType.Split(';')[1];
                    }
                    srContentType = srContentType.Replace("charset=", "");
                    srContentType = func_Process_Html_Input(srContentType);
                }

                try
                {
                    myEncoding = Encoding.GetEncoding(srContentType);
                }
                catch
                {
                    myEncoding = irCustomEncoding == 0 ? Encoding.UTF8 : Encoding.GetEncoding(irCustomEncoding);
                }

                using (StreamReader sr = new StreamReader(strumien, myEncoding))
                {
                    mycs_HttpFetchResults.srFetchBody = sr.ReadToEnd();
                    if (blAutoDecode == true)
                    {
                        mycs_HttpFetchResults.srFetchBody = HttpUtility.HtmlDecode(mycs_HttpFetchResults.srFetchBody);
                    }
                    mycs_HttpFetchResults.srFetchingFinalURL = Return_Absolute_Url(response.ResponseUri.AbsoluteUri.ToString(), response.ResponseUri.AbsoluteUri.ToString());
                    mycs_HttpFetchResults.blResultSuccess = true;
                }
            }
        }

        if (request != null)
            request.Abort();
        request = null;
    }
    catch (Exception E)
    {
        if (E.Message.ToString().Contains("(404)"))
            mycs_HttpFetchResults.bl404 = true;

        csLogger.logCrawlingErrors("crawling failed url: " + srUrl, E);

    }
    finally
    {
        if (request != null)
            request.Abort();
        request = null;

        if (response != null)
            response.Close();
        response = null;
    }

    return mycs_HttpFetchResults;
}


text:
Q: which one can be effective reference table or pointer table I have a tree in the form of several objects that make doubly linked lists. For direct access, in real time, these objects I thought about creating a reference table as size_tableau = nbr_object.
would you ideas about the declaration of the table?
if you have other suggestions I am taking.

{0,1,2,3,4,5,6,7,8,9,10}
{0,3,6,7,10} {1,2,4,5,8,9}
{3,10} {6,7,10} {1,5,8,9} {2,4}
{3,10} {6} {7,10} {1,8} {5,9} {2,4}

A: In c++ you can declare an array like so:
int numbers[11] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

The size is specified in the square brackets.
If you had a function that gave you the size, then you would need a dynamically sized array. std::vector is commonly used for this purpose.
void createTable(int table[11])
{
  std::vector<int> numbers (table, table + 11 * sizeof(int));
}


text:
Q: How to display previously uploaded files using ng2-file-upload I'm using ng2-file-upload, the files get uploaded properly but I want to display previously uploaded files as well, I have called an API and stored all the previously uploaded files in an array in the component but how to display that on HTML page.

Select files

            Multiple
            <input type="file" ng2FileSelect [uploader]="uploader" multiple  />

                    Name
                    Size
                    Progress
                    Status
                    Actions

                    {{ item?.file?.name }}
                    {{ item?.file?.size/1024/1024 | number:'.2' }} MB

                <button type="button" class="btn btn-success btn-s"
                        (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
                     Upload all
                </button>
                <button type="button" class="btn btn-warning btn-s"
                        (click)="uploader.cancelAll()" [disabled]="!uploader.isUploading">
                     Cancel all
                </button>
                <button type="button" class="btn btn-danger btn-s"
                        (click)="uploader.clearQueue()" [disabled]="!uploader.queue.length">
                     Remove all
                </button>

I have fetched the uploaded files in 'Queue' array, How i can i display that here
uploadfiles() {
        this.common.getData(url).subscribe(
            data => {
                this.queue.push({
                    name: file.Name,
                    id: file.Id,
                    size: file.Size
                })}

A: If you want to display both uploading files and already uploaded files in a single table, there are several ways to do.
You can display first the files in progess, then the files already uploaded:

Be careful to have the same number of  so that the table have the same number of column (the progress column can be empty for the second part for example. Depends on how you want to display your data)
Or you can concat the two array in one, and display it with one *ngFor.
For that, you will have to check the data structure to be consistent between the uploading files and the previous files you get via api.
Instead of picking only the name, size and id, you should add it this way:
this.queue.push({
  file: file
})}

Considering the "file" object is the same type as the files from uploader.queue.
There's nothing magic about it, everything depends on how you want to display the objects.


text:
Q: How to force gradle to add dependencies to the module path instead of the class path in eclipse? I have a gradle javafx library which build.gradle lokks like this :
plugins {
    id 'java-library'
    id 'java-library-distribution'
    id 'org.openjfx.javafxplugin' version '0.0.8'
}

repositories {
    mavenCentral()
    jcenter()
}

jar {
    archiveName = 'streampi-fx'
}

distributions {
    main {
        distributionBaseName = 'streampi-fx'
        contents {
            from 'src/main'
        }

    }
}

javafx {
    version = "14"
    modules = [ "javafx.controls", "javafx.fxml" ]
}

with a module-info requiring javafx :
module fr.streampi.fx {
    exports fr.streampi.fx.view.icons;
    exports fr.streampi.fx.model;
    exports fr.streampi.fx.model.io;
    exports fr.streampi.fx.model.utils;
    exports fr.streampi.fx.view;

    requires javafx.base;
    requires javafx.controls;
    requires transitive javafx.graphics;
}

I'm running my project in eclipse but every time I refresh the project, all dependencies are put to the class path instead of the module path. I then have to put them back manually in the module path every time my projects refreshes. How to make gradle set the dependencies in the module path ?

A: I am using this one in my root build.gradle (with Gradle 6.7)
subprojects {
    apply plugin: "java"
    java {
        modularity.inferModulePath = true
    }
    repositories {
        jcenter()
    }
}


text:
Q: Эффект набора текста при переключении слайдера В слайдере необходимо реализовать эффект "набора текста" при переключении слайдов. Для самого слайдера использую Slick Slider. Вот рабочий пример http://test2.hotweb.com.ua/webbit/ находится в вверху страницы.
HTML код:

                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 477.175 477.175"><path d="M145.188 238.575l215.5-215.5c5.3-5.3 5.3-13.8 0-19.1s-13.8-5.3-19.1 0l-225.1 225.1c-5.3 5.3-5.3 13.8 0 19.1l225.1 225c2.6 2.6 6.1 4 9.5 4s6.9-1.3 9.5-4c5.3-5.3 5.3-13.8 0-19.1l-215.4-215.5z"/></svg>

                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 477.175 477.175"><path d="M360.73 229.075l-225.1-225.1c-5.3-5.3-13.8-5.3-19.1 0s-5.3 13.8 0 19.1l215.5 215.5-215.5 215.5c-5.3 5.3-5.3 13.8 0 19.1 2.6 2.6 6.1 4 9.5 4 3.4 0 6.9-1.3 9.5-4l225.1-225.1c5.3-5.2 5.3-13.8.1-19z"/></svg>

JS код:
printTextSlider();

function printTextSlider() {
    var $btn = $('.nav-btn-slider'),
            $ul       = $('.slider-item-list'),
            $activeLi = $ul.find('.slick-active'),
            $text     = $activeLi.find('.slider-text');

    $text.addClass('is-active');
    printText($text);

    $btn.on('click', function() {

        var $activeLi = $ul.find('.slick-active'),
                $siblings = $activeLi.siblings().find('.slider-text'),
                $text     = $activeLi.find('.slider-text'),
                id        = $text.attr('id');

        setTimeout(function() {
            $siblings.removeClass('is-active');
        }, 1000);

        $text.addClass('is-active');
        printText($('#'+id));

    });
}

function printText(el) {
    var a = el.data('text');
    a = a.split('');

    console.log(a);

    el.text('');

    var c = a.length;

    j = 0;

    setInterval(function() {
        if(j < c) {
            el.text(el.text() + a[j]);
            j++;
        }
        else {
            el.removeClass('after-line');
        }
    }, 100);
}

Стили(Sass) применяемые для текста:
.slider-text-wrap {
  max-width: 700px;
  width: 100%;
  margin: 0 auto;
  padding-top: 230px;
}

.slider-text {
  font-size: 36px;
  word-wrap: break-word;
  opacity: 0;

  &.is-active {
    opacity: 1;
  }
}

.after-line {
  &:after {
    content: '_';
  }
}

Проблема: при переключении слайдов, текст выводиться некорректно.


text:
Q: Dependencies Between Workflows on Github Actions I have a monorepo with two workflows:
.github/workflows/test.yml
name: test

on: [push, pull_request]

jobs:
  test-packages:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v1
      - name: test packages
        run: |
          yarn install
          yarn test
...

.github/workflows/deploy.yml
name: deploy

on:
  push:
    tags:
      - "*"

jobs:
  deploy-packages:
    runs-on: ubuntu-latest
    needs: test-packages
    steps:
      - uses: actions/checkout@v1
      - name: deploy packages
        run: |
          yarn deploy
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
...

This doesn't work, I can't reference a job in another workflow:
### ERRORED 19:13:07Z

- Your workflow file was invalid: The pipeline is not valid. The pipeline must contain at least one job with no dependencies.

Is there a way to create a dependency between workflows?
What I want is to run test.yml then deploy.yml on tags, and test.yml only on push and pull requests. I don't want to duplicate jobs between workflows.

A: It seems that the Wait n Check action is currently the optimal workaround for this missing feature, as it declares in its README:

 It allows to work around a GitHub Actions limitation of non-interdependent workflows (we can only depend on jobs inside a single workflow).

UPDATE: see also my other answer for a partial solution using workflow_run.

A: This is possible with a combination of workflow_call and needs. Adding workflow_call to the on values of a job allows it to be called by other jobs. You can then call that job from the other workflow, and use needs to force future steps to depend on the success of that job. You can read about making workflows callable here: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#onworkflow_call and requiring a step to succeed before triggering future steps here: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idneeds
So for your case, the following should work:
# cat .github/workflows/tests.yml
name: tests
on: [workflow_call]  # allow this workflow to be called from other workflows
jobs:
  ...

# cat .github/workflows/deploy.yml
name: deploy
on:
  push:
    tags:  # trigger the deploy job on tag creation
    - *
jobs:
  tests:
    uses: ./.github/workflows/tests.yml  # use the callable tests job to run tests
  deploy:
    name: deploy
    needs: [tests]  # require tests to pass before deploy runs
    ...

A: You can (also) do it by combining workflow_run and if.

Using the below config, the deploy workflow will start only when all of these conditions are true:

*

*after the test workflow is completed,

*if the test workflow was successful,

*Tere was a tag pushed to the default branch,

Assuming that the default branch is main:
name: deploy

on:
  # the 1st condition
  workflow_run:
    workflows: ["tests"]
    branches: [main]
    types:
      - completed

jobs:
  deploy-packages:
    # the 2nd condition
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    (...)

....BUT unfortunately the 3rd condition cannot be checked this way as the deploy workflow is triggered in a context of the HEAD of the default branch, without the knowledge about the tag that may be pointing there.
So doing something like:
    if: ${{ github.event.workflow_run.conclusion == 'success' }} && startsWith(github.ref, 'refs/tags/') }}

...will NOT work.

I will update this answer when I find out the workaround for this issue.

A: Now it's possible to have dependencies between workflows on Github Actions using workflow_run.
Using this config, the Release workflow will work when the Run Tests workflow is completed.
name: Release
on:
  workflow_run:
    workflows: ["Run Tests"]
    branches: [main]
    types:
      - completed


text:
Q: Time synchronization in Active directory I've got issues with time synchronization in a domain. I have DCs that spans time zones, however the PDC is located in a time zone where daylight savings is active, this caused all the additional DCs and clients located in places where daylight savings is not active to roll back one hour....how can this issue be solved.
Regards.

A:
I have DCs that spans time zones, however the PDC is located in a time zone where daylight
  savings is active, this caused all the additional DCs and clients
  located in places where daylight savings is not active to roll back
  one hour...

Can I uggest you have an admin (with knowledge) have a look at your machines? Something is SERIOUSLY WRONG with your timezone setup.
WIndows does not care about timezones - it has an internal clock that then gets translated into a visible "local time" when needed (and this translation is where the timezone comes in), but all timestamps are - if the machines are properly configured - totally ignorant to timezones.
Also, there is only one domain controller (the PDC Emulator) that is responsible for the time. I.e. he distributes it. Not that this is PDC Emulator - there is no PDC ever since I think Active Directory was created.
The only way i can see that happening what you describe is that the setup was done by someone totally ignorant of timezones and the machines actually are not in the correct timezones but a default one. If every machien would be - locally - set to their correct timezone, that would be a total non-issue as the machiens would ajust their presentation of the timestamps when summer/winter time changes (or not) and they would know when this happens.
Basically you run all servers in a specific timezone and then think they should magically ignore the timezone settings they have and show the correct time. The clients and additional DC's should have their timezone information updated so that they know their real timezone, not a fake one.
I again advice you have your AD checked by someone at least on junior admin level because if you bothered up that part then it is likely you have a ton of other issues - this is really "setting up a windows network 101" level.

A: Ensure that all clients and servers are in their respective time zones, all time zone patches are installed and that Windows is set to automatically adjust for daylight savings time.  Also ensure that you have a reliable time source.  See my post here for more info about that.

A: I suggest you create sites for each different time zone.


text:
Q: Trying to print out my ArrayList using one of my methods in my class what am i doing wrong? Here is my program. All i'm trying to do is print the ArrayList at the end and it won't, what am i doing wrong I'm trying to use mls.ToString() but thats not working. Please tell me what i did wrong. PS this is homework and thanks for the help.
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    ArrayList<Book> mls = new ArrayList<Book>();
    String userAuthor;
    String userTitle;
    int userYearPub;
    int userPageCount;

    String answer;
    int numberAnswer;
    int choice;

    do {
        Scanner in = new Scanner(System.in);

        System.out.println("Please enter the author of the book.");
        userAuthor = in.next();
        System.out.println();

        System.out.println("Please enter the title of the book.");
        userTitle = in.next();
        System.out.println();

        System.out.println("Please enter the year the book was published.");
        userYearPub = in.nextInt();
        System.out.println();

        System.out.println("Please enter the number of pages of the book.");
        userPageCount = in.nextInt();
        System.out.println();

        Book usersBook = new Book(userAuthor, userTitle, userYearPub, userPageCount);

        System.out.println(usersBook.ToString());
        System.out.println();

        do {
            System.out.println("If you want to change anything press one of the following options: ");
            System.out.println('1' + " Author.");
            System.out.println('2' + " Title.");
            System.out.println('3' + " Year it was published.");
            System.out.println('4' + " Number of pages");
            System.out.println('5' + " Quit");
            System.out.println();
            choice = in.nextInt();

            if (choice == 1) {
                System.out.println("Please enter the new author:");
                answer = in.next();
                usersBook.setAuthor(answer);
            }

            if (choice == 2) {
                System.out.println("Please enter the new title:");
                answer = in.next();
                usersBook.setTitle(answer);
            }

            if (choice == 3) {
                System.out.println("Please enter the new year:");
                numberAnswer = in.nextInt();
                usersBook.setYearPub(numberAnswer);
            }

            if (choice == 4) {
                System.out.println("Please enter the new pages count:");
                numberAnswer = in.nextInt();
                usersBook.setPages(numberAnswer);
            }

            if (choice == 5) {
                break;
            }

            System.out.println();
            System.out.println("Is this correct?");
            System.out.println('1' + " yes");
            System.out.println('2' + " no");
            choice = in.nextInt();

            if (choice == 1) break;

        }while (choice == 2);

        mls.add(usersBook);

        System.out.println(usersBook.ToString());

        System.out.println();
        System.out.println("Do you want to input another book?");
        System.out.println("If so press 1, if not press 2.");
        choice = in.nextInt();

        System.out.println(mls.ToString());

    } while (choice == 1);

}

}
Here is the Book class.
public class Book {
private String author;
private String title;
private int yearPub;
private int pages;

public Book(String Author, String Title, int YearPub, int Pages)
{
    this.author = Author;
    this.title = Title;
    this.yearPub = YearPub;
    this.pages = Pages;
}
public String ToString()
{
    return  "The Author of this book is " + author +
            "\nThe title of this book is " + title +
            "\nThe year published is " + yearPub +
            "\nThe number of pages is " + pages;
}

public void setAuthor(String newSring)
{
    author = newSring;
}
public void setTitle(String newString)
{
    title = newString;
}
public void setYearPub(int newValue)
{
    yearPub = newValue;
}
public void setPages(int newValue)
{
    pages = newValue;
}

}

A: mls is not a Book. It is an ArrayList<Book>. You need to fetch the books from the list before calling ToString(). Something like the following:
for(int i = 0; i < mls.size(); i++) {
    System.out.println(mls.get(i).ToString());
}

A: You are triying to access the method ToString of a List of books "mls", which hasn't such method, your variable is not a book is a list of books.
You have to replace "mls.ToString()" for "usersBook.ToString()" in order to access your method.
PS: You should rename your method with lowercase toString, in Java all objects implicitly inherit that method, you can/shall override it.

A: Problem is line with:
System.out.println(mls.ToString());

ArrayList don't have ToString() method. ArrayList have toString() method.
Solution is:
System.out.println(mls.toString());

or
System.out.println(mls);

You musn't use toString() method, it will be automatically called.
And second problem is that your toString() method in Book class should look like:
@Override
public String toString() {
    return "The Author of this book is " + author +
            "\nThe title of this book is " + title +
            "\nThe year published is " + yearPub +
            "\nThe number of pages is " + pages;
}


text:
Q: How to explicitly represent a basis for the subspace perpendicular to $v ∈ ℝ^3$ I'm looking for an analytic way to explicitly represent two vectors which form a basis
for the space in $\mathbb{R}^{3}$ perpendicular to some vector $v$.
For example, my first thought was to do this:
\begin{align}
u &= v\times u', &
w &= v\times u.
\end{align}
The idea is that $u$ will be perpendicular to $v$ (and $u'$, but that choice is arbitrary and doesn't matter) and that $w$ will be perpendicular to $v$ and $u$.
The fact that both $u$ and $w$ are perpendicular to $v$ puts them in the correct subspace.
The fact that $u$ and $w$ are perpendicular to each other means they form an orthogonal basis.
The problem, of course, is that this fails when $v$ is parallel to $u'$. I'm looking for a fully general way to express $u$ and $w$.
There are many algorithms for doing this, but those are not useful to me at the moment. I'm looking for an explicit representation of the form
\begin{align}
u &= f(v), &
w &= g(v,u).
\end{align}
Any ideas?

A: What you're really after is a method of producing a vector $u = f(v)$ orthogonal to $v$ which always works and which doesn't involve any sort of 'choice'.
With that, getting the last vector is as easy as $w = f(v) × u$.
You could take
$$
f(v) = \begin{cases}
v × (1,0,0) & \text{if $v ≠ (1,0,0)$} \\
(0,1,0) & \text{otherwise}
\end{cases}
$$
but you're probably wanting to exclude this kind of solution on the basis of the choice of $(1,0,0)$ as special.
But suppose we have a magic formula $f : ℝ^3 → ℝ^3$ which produces an orthogonal vector $f(v) \perp v$ as advertised.
There are infinitely many possible answers, arranged with rotational symmetry in the plane $v^\perp$.
The formula must have a way of picking out one of those vectors as distinct from the rest, so the formula itself cannot be symmetric — it must involve some choice of vector.
So you can't get away with not making a choice.
But if we take $v × u'$ for an initial guess $u'$, the formula will fail for $u' \parallel v$.
As a way of "disguising" the choice, you could generate two vectors, one of which may be zero, and then choosing the one that isn't. For example,
$$
f(v) ∈ \{v × (1,0,0), v × (0,1,0)\}
.$$
Both of these are $\perp v$, and they can't both vanish for the same $v ≠ 0$.

Arguably, the better way to handle the geometry of vectors and planes is to use a language with less redundancy:
Instead of representing $v^\perp$ with an orthogonal basis, you can represent it as a bivector.
For example, if $v = v_x ̂ + v_y ̂ + v_z ̂$, then the normal plane is described by the bivector
$$
v_x ̂ ∧ ̂ + v_y ̂ ∧ ̂ + v_z ̂ ∧ ̂
.$$
If this kind of 'multilinear algebra' interests you, I recommend reading about multivectors and geometric algebra.

A: If we approach the problem, finding "a basis for the space in $\mathbb R^3$ perpendicular to some vector" $\vec v$, using an orthogonal transformation, then numerical stability will be better than Gram-Schmidt or the cross-product (which only exists in $\mathbb R^3$).
An orthogonal transformation preserves the angles between and lengths of vectors.  This helps with numerical stability, because inevitable rounding errors will not grow geometrically under an orthogonal transformation.
Especially convenient for your purpose is a Householder reflection $Q$ which is both orthogonal ($Q^T = Q^{-1}$) and symmetric ($Q^T = Q$). Hence such $Q$ is its own inverse.  The approach works for Euclidean space $\mathbb R^n$ quite generally.
Notice that if column vector $\vec v$ is nonzero, then the vectors perpendicular to it are the same as those perpendicular to the unit length vector $\vec v/||\vec v||$.  So we consider without loss of generality only the case $||\vec v|| = 1$.
If $\vec v$ were a standard basis vector, e.g. $\mathbf e_1 = (1\;0\;\ldots\;0)$, then we would know immediately a basis for those vectors perpendicular to $\vec v$ is formed by all the other standard basis vectors, $\mathbf e_2, \mathbf e_3, \ldots, \mathbf e_n$. So let's assume $\vec v \neq\mathbf e_1$.
The idea is to construct a Householder reflection $Q$ such that $Q\vec v = \mathbf e_1$.  It follows that $Q\mathbf e_1 = \vec v$, and that a basis for the subspace of $\mathbb R^n$ perpendicular to $\vec v$ will be given by $Q\mathbf e_2,Q\mathbf e_3,\ldots,Q\mathbf e_n$.  In other words $\vec v$ is the first column of $Q$, and the remaining columns of $Q$ form a basis for the orthogonal complement.
The formula for $Q$ is $I - 2\vec x\,\vec x^T$ where:
$$ \vec x = \frac{\mathbf e_1 - \vec v}{||\mathbf e_1 - \vec v||} $$
It is routine to show that Householder reflection $Q$ is orthogonal and symmetric (exercise left for the Reader?), so the essential point we need to detail is that the first column of $Q$ is $\vec v$.
Writing column vector $\vec v$ by its components:
$$ \vec v = (v_1 \; v_2 \; \ldots \; v_n)^T $$
permits the following substitution and simplification:
$$ \begin{align*} Q\mathbf e_1 &= (I - 2\vec x\,\vec x^T)\mathbf e_1 \\
&= \left( I - \frac{2(\mathbf e_1 - \vec v)(\mathbf e_1 - \vec v)^T}{||\mathbf e_1 - \vec v||^2} \right) \mathbf e_1 \\
&= \mathbf e_1 - \frac{2(\mathbf e_1 - \vec v)(1 - v_1)}{||\mathbf e_1 - \vec v||^2} \\
&= \mathbf e_1 - \frac{2(1 - v_1)}{(1-v_1)^2 + \sum_{i=2}^n v_i^2} (\mathbf e_1 - \vec v) \\
&= \mathbf e_1 - \frac{2(1 - v_1)}{1-2v_1 + \sum_{i=1}^n v_i^2} (\mathbf e_1 - \vec v) \\
&= \mathbf e_1 - \frac{2 - 2v_1}{2 - 2v_1} (\mathbf e_1 - \vec v) \\
&= \mathbf e_1 - (\mathbf e_1 - \vec v) \\
&= \vec v \end{align*} $$
The diligent Reader will spot where the assumption $\vec v \neq \mathbf e_1$ allows us to avoid (multiplying and) dividing by zero.  In fact the computation should be numerically accurate unless $\vec v$ is so close to $\mathbf e_1$ as to cause a subtractive cancellation problem with $(\mathbf e_1 - \vec v)$.  If this were to happen, it can be fixed by replacing $\vec v$ with $-\vec v$. The same vectors perpendicular to $\vec v$ are perpendicular to $-\vec v$, and $(\mathbf e_1 + \vec v)$ would then avoid subtractive cancellation.


text:
Q: Make all HTML components disappear, only show the background image I want to implement a fancy feature in my website. I have a nice background image in my website, and HTML components on top of it. I want to put a link somewhere in the background image such that, when a user clicks that link, all the HTML elements disappear, and the user can view the full image. This feature can be toggled. Can anyone suggest me how I may achieve this with jQuery?

A: You can hide everything pretty easily:
$('body > *').hide();

Although that'll also hide your toggle link. You probably want to put all of the hidable elements in a container (like a div) and toggle the visibility on that.

A: You could do something like this:
$('.show_bg').click(function() {
    $('body > *').toggle();
    $(this).show();
    return false;
});

jsFiddle Example.

A: Make a CSS class that hides all child elements:
.hideall * { display: none; }

Now you can add the class to the body to hide everything, and remove the class to show everything again:
$(function(){
  $('#hidelink').click(function(e){
    e.preventDefault();
    $('body').addClass('hideall');
  });
  $('body')click(function(){
    $('body').removeClass('hideall');
  });
});

The advantage with this method is that it won't potentially mess up the layout by setting a diplay style on elements, and when showing the contents it won't make things visible that should remain hidden.

A: You would need to wrap all the elements you want to toggle within a wrapper div except for the button you're using to toggle this functionality.
<body>
    <div id='wrapper'>sdfsdf
        <!-- All your content -->
    </div>
    <button name='toggle_bg'>Toggle background image</button>
</body>
<script>
$("button[name='toggle_bg']").click(function(){
    $("div#wrapper").toggle();
});
</script>


text:
Q: Swig: How to typemap c++ string const & to python string? I have a constructor with these prototypes:
YCPTerm(const string& s);
YCPTerm(const string& s, const YCPList& l);
YCPTerm(bytecodeistream & str);

I'm using swig to generate python bindings. In python, I try to call the constructor, and get this:
>>> import ycp
>>> ycp.YCPTerm("Empty")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ycp.py", line 575, in __init__
    this = _ycp.new_YCPTerm(*args)
NotImplementedError: Wrong number or type of arguments for overloaded function 'new_YCPTerm'.
  Possible C/C++ prototypes are:
    YCPTerm::YCPTerm(string const &)
    YCPTerm::YCPTerm(string const &,YCPList const &)
    YCPTerm::YCPTerm(bytecodeistream &)

I found this answer which seems to be a similar issue, but a typemap typecheck didn't work for me.
This is what I tried:
%typemap(typecheck,precedence=141) const std::string& str {
  $1 = Z_TYPE_PP($input) == IS_STRING;
}

How do I solve this? Do I need an in and out typemap to convert the value? I've been reading about typemap's here, and am not sure how to typemap a const string&.

A: The std_string.i library includes the typedefs that do conversions back and forth between std::string and Python strings. See the documentation on the std::string library in SWIG for more details.

A: I found the answer here.
Adding these lines to my .i file fixed the error:
%include std_string.i
%inline %{
using namespace std;
%}

I don't understand the why though. Maybe someone else can answer that.


text:
Q: Dojo drag and drop gets angry after adding new row I have a table with draggable rows in Dojo. When I dynamically add new row in table through javascript it creates problem while dragging newly created row. On console it shows
Failed to load source. Yet it drags other rows that was already in table.
While creating new row I also give my row this class class="dojoDndItem". My <tbody> is <tbody dojoType="dojo.dnd.Source">
Do I need to do something special while creating new row?

A: Could you try using the insertNodes method on your dnd source dijit?  I think just adding the nodes with javascript will not trigger the DND source's code that registers it as a draggable element and set up the event listeners.

A: There was a problem that dojo was not updating it draggable nodes. Also by viewing source was not displaying newly created rows. Dojo dnd source has a property called autoSync. See dojo.dnd.Source api. Its by default set to false but enabling it true does the work. It automatically syncs the nodes and all newly generated nodes was able to drag and drop.
So after this  becomes <tbody dojoType="dojo.dnd.Source" autoSync="true">


text:
Q: What is the AWS Attribute outputs and ImportValue in cloudformation i'm starting my AWS journey and today got a chance to Create cloudformation stack for creating a filesystem on the AWS, i was able to spun the filesystem, however I have few
doubts about some values and functions/attributes as those were given by someone in the team and he on long vacations so, asking here for help.
Below is cloudfoemation Stack which works Just fine.
Cloudformaton Stack:
---
Description: "Create FSxN filesystem"
Resources:
  MytestCluster:
    Type: "AWS::FSx::FileSystem"
    Properties:
      FileSystemType: "ONTAP"
      StorageCapacity: "1024"
      SubnetIds: ['subnet-0f349h6eee098b0pg']
      OntapConfiguration:
        DeploymentType: "SINGLE_AZ_1"
        PreferredSubnetId: "subnet-0f349h6eee098b0pg"
        ThroughputCapacity: "128"
        FsxAdminPassword: '{{resolve:secretsmanager:fsx_admin_password}}'
      SecurityGroupIds:
        - !ImportValue 'KPCL-FSxforONTAPsgID'
      Tags:
        - Key: "Backup"
          Value: "None"
  MytestSVM:
    Type: "AWS::FSx::StorageVirtualMachine"
    Metadata:
      cfn-lint:
        config:
          ignore_checks:
            - E3001
    Properties:
      FileSystemId: !Ref MytestCluster
      Name: svmdemo
      RootVolumeSecurityStyle: "UNIX"
      SvmAdminPassword: '{{resolve:secretsmanager:svm_admin_password}}'
      Tags:
        - Key: "Backup"
          Value: "None"
  fsxndemovolume:
    Type: "AWS::FSx::Volume"
    Metadata:
      cfn-lint:
        config:
          ignore_checks:
            - E3001
    Properties:
      Name: myTestVol001
      OntapConfiguration:
        JunctionPath: /myVolume001
        SizeInMegabytes: 1536000
        StorageEfficiencyEnabled: true
        StorageVirtualMachineId: !Ref MytestSVM
      VolumeType: "ONTAP"
      Tags:
        - Key: "Backup"
          Value: "None"
Outputs:
  FileSystemId:
    Value: !Ref "MytestCluster"
  SvmId:
    Value: !Ref "MytestSVM"
...

I would like Understand:
I have few doubts to myself to clear which i tried to understand from document but couldn't comprehend well, hence though taking expert suggestion..
First one: below  under SecurityGroupIds what does  - !ImportValue mean here.
  SecurityGroupIds:
    - !ImportValue 'KPCL-FSxforONTAPsgID'

Second one: What is outputs means here.
Outputs:
  FileSystemId:
    Value: !Ref "MytestCluster"
  SvmId:
    Value: !Ref "MytestSVM"

Last one: what is ignore_checks: and its value - E3001 here.
      ignore_checks:
        - E3001

Please help me to understand.

A: Outputs in stack creates exports in cloudformation which can be listed in AWS Console, !Import directive is used to reference to export from another stack.
cfn-lint section in metadata is used to silent errors in CloudFormation Linter tool and has no impact to the resource itself.

A:
First one: below under SecurityGroupIds what does  - !ImportValue mean here.

The following:
      SecurityGroupIds:
        - !ImportValue 'KPCL-FSxforONTAPsgID'

means that in the current stack your are going to import security group ID which was exported by some other stack.
This export/import functionality allows you to decouple and reuse your infrastructure. Instead of having everything in one stack, you can make one stack with network resources (its a common setup), such as security groups, subnets, VPCs, and other stacks that actual use those resources.

Second one: What is outputs means here.

Outputs allow you to return values from your stacks. You can think of them as a type of return values from functions in common programming languages.
Output values have lots of use-cases. Examples are: they can be exported, and imported in other stacks. They can also be queried programmatically, in case your stacks are part of some CI/CD pipelines or other application. They can be used as input parameters to other stacks, again as port of some CI/CD pipeline. This is alternative to export/import functionality.

Last one: what is ignore_checks: and its value - E3001 here.

This is some extra code not related to CloudFormation itself. It is actually a hint to Visual Studio Code
cfn-lint-visual-studio-code editor to ignore some auto checks it does.


text:
Q: .bat file can't escape character i have a problem in my script:
@echo on
setlocal EnableDelayedExpansion
pushd C:\Users\Oskars.Abuhovs\Desktop\testJstoReplace
for /f "delims=" %%a in ('dir /b /a-d-h-s') do (
  set newFile=C:\Users\Oskars.Abuhovs\Desktop\tempjs\%%a
  if exist !newfile! del /f /q !newfile!
  for /f "delims=" %%L in (%%a) do (
    set newLine=%%L
    echo !^newLine:dojo/i18n=ggggggggg^^!dddd! >> !newFile!
  )
)
popd
pause

The problem is in a row:
echo !^newLine:dojo/i18n=ggggggggg^^!dddd! >> !newFile!

Where character ! is not escaped, i read that in setlocal EnableDelayedExpansion ! character should be escaped using ^^, but it is not happening. How can i escape this character?
Edited:
I want to replace part of the string in files. This particular string dojo/i18n should be replaced with another string, that contains !. For example dojo/i18n!mycomputer.
Whole script together reads files from folder, then search every file line by line searching for this string: dojo/i18n, when it is found, string should replace that with early mentioned text dojo/i18n!mycomputer, that contains !. I tried to do it with escaping ! character with two ^^ as it is supposed to work when setlocal EnableDelayedExpansion, but this combination: ^^! does not work in this line, but when i tried simple echo ^^! it worked.
So i am asking how to escape ! character in that line?
Thanks in advance!

A: This might work for you:
@echo off
setlocal EnableDelayedExpansion
pushd "C:\Users\Oskars.Abuhovs\Desktop\testJstoReplace"
for /f "delims=" %%a in ('dir /b /a-d-h-s') do (
  set "newFile=C:\Users\Oskars.Abuhovs\Desktop\tempjs\%%~a"
  if exist "!newfile!" del /f /q "!newfile!"
  for /f "delims=" %%L in ("%%~a") do call:doline "%%~L" "!newfile!"
)
popd
PAUSE
goto:eof

:doline
SETLOCAL DISABLEDELAYEDEXPANSION
set "newLine=%~1"
echo %newLine:dojo/i18n=ggggggggg!dddd% >> "%~2"
ENDLOCAL
goto:eof

A: You can rewrite your code to avoid the need for delayed expansion:
@echo on
pushd C:\Users\Oskars.Abuhovs\Desktop\testJstoReplace
set newFile=C:\Users\Oskars.Abuhovs\Desktop\tempjs
for /f "delims=" %%a in ('dir /b /a-d-h-s') do (
  if exist "%newfile%\%%a" del /f /q "%newfile%\%%a"
  for /f "delims=" %%L in ('type "%%a" ') do (
    >>"%newfile%\%%a" echo %%L:dojo/i18n=ggggggggg!dddd
  )
)
popd
pause

A: @echo off
setlocal ENABLEDELAYEDEXPANSION
SET dddd=replacement^^!data
for /f "delims=" %%a in ('dir /b /a-d-h-s *.doj') do (
  set newFile=u:\temp\%%a
  if exist !newfile! del /f /q !newfile!
  (
  for /f "delims=" %%L in (%%a) do (
    set newLine=%%L
    FOR /f "tokens=1*delims==" %%Q IN ('set dddd') DO (
     SETLOCAL disabledelayedexpansion
     CALL echo %%newLine:dojo/i18n=ggggggggg%%R%%
     endlocal
    )
  )
  )>>!newfile!
)

This worked for me. Filenames and masks changed to protect the innocent, naturally.

A: Thanks for your answers, but in the end i decided to switch to .vbs for solving my problem.
Used this code, if someone latter need it:
Const ForReading = 1
Const ForWriting = 2

strFilePath = Wscript.Arguments(0)
strOldText = Wscript.Arguments(1)
strNewText = Wscript.Arguments(2)

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strFilePath)
Wscript.Echo objFolder.Path
Set colFiles = objFolder.Files
For Each testFile in colFiles
    FileToReplace = strFilePath + testFile.Name
    Wscript.Echo FileToReplace
    Set objFile = objFSO.OpenTextFile(FileToReplace, ForReading)
    strText = objFile.ReadAll
    objFile.Close

If InStr(strText, strOldText) Then
    strText = Replace(strText, strOldText, strNewText)
    Set objFile = objFSO.OpenTextFile(FileToReplace, ForWriting)
    objFile.Write strText  'WriteLine adds extra CR/LF
    objFile.Close
End If
    strText = ""
Next


text:
Q: GRUB2 doesn't load on BIOS/GPT setup What's my platform
Debian testing with Linux kernel 5.10.40 on Dell Latitude E5550.
What I'm doing
Up to now, my setup was old fashioned MBR partitions with "legacy" BIOS mode. Unfortunately, my new laptop doesn't support BIOS mode anymore, so I have to migrate to UEFI setup.
Since GPT is said to be supported with BIOS mode on Linux, I conceived the following migration path:
BIOS/MBR -> BIOS/GPT -> UEFI/GPT
To that end, I created the BIOS Boot Partition, as instructed by GRUB manual above, and converted my partitions to GPT with sgdisk -g /dev/sda. My current partition layout is:
# parted /dev/sda print
Model: ATA TS128GSSD370S (scsi)
Disk /dev/sda: 128GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags:

Number  Start   End    Size    File system  Name         Flags
 1      32,3kB  253MB  253MB   ext4
 2      253MB   263MB  10,5MB               boot-system  bios_grub
 3      263MB   128GB  128GB

Partition #3 is my main partition with LUKS-encrypted filesystem root and partition #1 is unencrypted /boot directory.
After convertion to GPT, I reinstalled GRUB with grub-install --target=i386-pc /dev/sda.
What doesn't work
When trying to boot from this drive, screen goes black and after ~2 seconds it displays a message: Selected boot device failed. Press any key to reboot the system. Googling it seems to indicate that it can point to multiple kind of issues with both Linux and Windows, so it's probably a BIOS/UEFI message and GRUB doesn't even gets loaded at this point, though it can be wrong assumption.
Currently, I use Super GRUB2 disk, which finds GRUB configuration on partition #1 and uses it to boot into my system. So it works just as before with MBR partitions, except the GRUB2 code from MBR doesn't seem to execute
What I've tried
The only thing that came to my mind was trying to set a boot flag on partition #1. It used to be there before the GPT conversion, though I'm not sure if it was needed. However, doing that and reinstalling GRUB again didn't change the outcome.

A: In theory, yes, BIOS/GPT should be supported because the BIOS does not actually read the partition table at all, only the bootloader (the piece of GRUB that's written to the MBR) needs to understand GPT partitions.
However, some firmwares do still look at partition tables even in BIOS-boot mode and are known to not bother even trying to boot from GPT-partitioned disks, even if the disk has a completely valid MBR boot code installed. Dell is sometimes among those, from what I've heard.
I would suggest skipping this migration step entirely. It won't really make the future migration to UEFI/GPT any easier – you will still have to throw away your current GRUB configuration and re-do those two "boot" partitions as an EFI System Partition anyway, so just do it all in one step.


text:
Q: Which of these three options would be fastest to populate my DB table? I have a (huge: 6.4 million rows) database table with three columns as follows:
URL     Title      Description

Right now only the URL column is populated, with various urls from around the web. I have to add a title and meta description to the url in each row. There are three ways I see I can do this:
Option 1: Use php and CURL to go to each url and grab the title and meta:description. (Even with using options 2 or 3 I'll have to do this for at least part of the urls).
Option 2: I have a DMOZ xml file which has several million elements which look like this:
    <ExternalPage about="http://animation.about.com/">
       <d:Title>About.com: Animation Guide</d:Title>
       <d:Description>Keep up with developments in online animation for all skill levels.     Download tools, and seek inspiration from online work.</d:Description>
       <topic>Top/Arts/Animation</topic>
    </ExternalPage>
    <ExternalPage about="http://www.toonhound.com/">
       <d:Title>Toonhound</d:Title>
       <d:Description>British cartoon, animation and comic strip creations - links, reviews  and news from the UK.</d:Description>
       <topic>Top/Arts/Animation</topic>
    </ExternalPage>

etc.
I can use xmlreader to compare the url in every ExternalPage-about to see if it matches one of the 6.4 million urls in my table, and if it does, add the title and description.
Option 3: I can write all the above dmoz data into a separate database table (again using xmlreader), which will also take time, and then somehow use JOINs and SELECTs on the two tables to get the information I need.
Would option 2 or 3 be quicker for those urls than just using option 1 for all the urls? If yes, which of the two options would be faster?

A: It is just a script, you will run it only once.. It doesn't matter if it is not very fast.
By the way 6 million rows are not too huge, it will take minutes on any decent computer.
CURL solution is not an option at all! do you know how long will it take to fetch 6 million URLS?!!
Insert the XML into database, and do queries as you like.
EDIT: To capture millions of URLs (it might take weeks to finish!):

*

*Get a cheap vps server (faster connection than your home computer).

*Export urls to text file.

*use wget to download each URL (don't forget to use multiple wget processes).

A: Assuming "Faster" means less time to update your URL table, then option 3 seems to be the best option.
You can populate another table with records from XML and then using JOIN to update your main table.


text:
Q: My property conflict with transact sql property because of the name Select * from InfinitusApp.CollaboratorUserLevels c
inner join InfinitusApp.ApplicationUsers a
on c.identity = a.Id

Where i rum this, return:

Because in my model CollaboratorUserLevels i have a property with Identity name,
return "Incorrect syntax near the keyword 'Identity'" even using alias

A: Assuming you have not turned off quoted identifier you can use "
Select * from InfinitusApp.CollaboratorUserLevels c
inner join InfinitusApp.ApplicationUsers a
on c."identity" = a.Id


text:
Q: Can Openshift templates create objects over multiple projects If I create project 'A' and want to deploy a template from inside it that creates objects in project 'A' and also in another project 'B' how would I achieve this. I tried simply specifying the namespace of project 'B' in the template but got the error

the namespace of the provided object does not match the namespace sent on the request

A: According to documentation:

If an object definition's metadata includes a fixed namespace field value, the field will be stripped out of the definition during template instantiation. If the namespace field contains a parameter reference, normal parameter substitution will be performed and the object will be created in whatever namespace the parameter substitution resolved the value to, assuming the user has permission to create objects in that namespace.

So just specify required namespaces as template's parameters. Usable example:
apiVersion: template.openshift.io/v1
kind: Template
metadata:
  name: xxx
parameters:
- name: ns1
  value: test1
- name: ns2
  value: test2
objects:
- apiVersion: v1
  data:
    key1: value1
  kind: ConfigMap
  metadata:
    namespace: ${ns1}
    name: cm1
- apiVersion: v1
  data:
    key2: value2
  kind: ConfigMap
  metadata:
    namespace: ${ns2}
    name: cm2


text:
Q: Having trouble in installing Ubuntu 14.04.2 LTS alongside Win 7 (64-bit) I am new to Ubuntu.  I am trying to install Ubuntu 14.04.2 LTS through UnetBootin.  As I go through the steps, I see that i am never asked the option to install Ubuntu alongside my existing OS (Windows 7). Do I need to partition the hard drive before installing Ubuntu alongside Windows 7?  It's pretty confusing.  I eagerly look forward to some help in this regard.

A: Installing Ubuntu without partitioning was able in Ubuntu 12.04 thanks to Wubi software
Development is disconntinued and Ubuntu 14.04.2 isn't supported.
Don't be affraid, Ubuntu installers are safe, follow them and let the installer to partition your disk.
Luck!


text:
Q: Proxy to work with OpenLayers and Geoserver Locally with IIS express I need to set a proxy to work with OpenLayers and Geoserver, which are both using a different port on my pc. I'm the site with openlayers is hosted IIS express and I'm not using Apache (so the proxy.cgi solution is not for me). I need it to perform a wmsgetfeatureinfo and, at this point, I really don't know what to put in OpenLayers.ProxyHost =. Can you help?

A: Found the solution: simply, if you are using the WebMatrix like me, you can install the PHP from the settings of the program directly into the iis. This way, I'm able to use the proxy made in php and it works perfectly!


text:
Q: How to solve such complicated integral involving Bessel function. I am stucked in solving this integral that involves exponential, Bessel function and Power.
$\int_{-\infty}^{\infty}(x-z)^{2m_1-1}\cdot z^{m_2+m_3-1}\cdot e^{\frac{m_1}{\Omega_1}(-2xz+z^2)}\cdot K_{m_2-m_3}\left(2\sqrt\frac{m_2m_3}{\Omega_2\Omega_3}z\right)dz$
Any help in this regard will be highly appreciated.


text:
Q: IntellIJ IDEA Ultimate 2019.3 Showing Fully Qualifed Name for Annotation IntelliJ IDEA Ultimate 2019.3 on macOS Catalina (10.15.2) is showing the fully qualified for annotations that I import...
For example, after creating a Spring Boot Project with the Web dependency from Spring Initializr and then importing the unzipped file into IntelliJ IDEA as a Maven project, I tried to add the @RestController annotation to my class:
@RestController
public class RestController {
}

IntelliJ IDEA automatically completes it with the fully qualified name (which is not what I prefer):
@org.springframework.web.bind.annotation.RestController
public class RestController {

}

Went to Preferences -> Editor -> Code Style -> Java and the Use fully qualifed class names is unchecked.
How can I get rid of this annoying code completion?
Just want it to look like this (it was working but something happened and I even tried File -> Invalidate Caches.../Restart
It used to be that if I put @RestController, it would import the class and look like this:
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RestController {

}

This is what I am seeking to revert back to...
Any assistance is much appreciated.

A: Figured it out - I was trying to be very generic so I named my class RestController... That's why IntelliJ IDEA had decided to include the fully qualified package name for the annotation because it was doing me a favor by not letting the compiler know that the class name and the annotation are different pieces of code.
Indeed, IntelliJ IDEA is truly intelligent!


text:
Q: NHibernate ICriteria and Expected Types Is there any way to get at the types of objects I would expect NHibernate to place in an ICriteria object as the result of running a query? In this code sample, I can get at the types of my objects if they aren't null, but what if they are? Also, depending on the data returned, one "row" (object[]) may have null fields in places where other rows don't - forcing me to enumerate through all rows (worst case) to determine what each column (index of object[])  should be.
Where can I find the expected type for the object (the expected type for each of the objects in the array I've created - obviously it wouldn't be on my array, but I would expect it to be somewhere in the ICriteria hierarchy)?
DetachedCriteria dc = DetachedCriteria.For<MyObject>().Add(...).SetProjection(...);

IList<object[]> list = dc.GetExecutableCriteria(session).List().OfType<object[]>().ToList();

foreach(object [] o in list)
{
   foreach(object p in o)
   {
      if(p != null)
         Type t = p.GetType();
      else
         throw new ApplicationException("Query returned null for column");
   }
}

I ask this because having to actually examine the results returned by NHibernate seems like the wrong way to go about this. Reflection doesn't appear to be any help either, because I can't find an instance to my object's types anywhere but on the actual result "row" / "column" when examining the ICriteria object (a CriteriaImpl object) returned.
I ask because I'm trying to dynamically create a DataTable from an NHibernate result, and I want to have the columns strongly typed.

A: The types returned are the types you queried for. If your users are adding custom columns and querying freely, you won't know what you're querying for, so you can't get a strongly-typed result without inspecting the actual objects.
AFAIK this is a limitation in NHibernate.


text:
Q: Switch between Neo4j databases dynamically I have 8 databases in Neo4j and depending on user interaction I need to load them dynamically. I know that I can modify neo4j.conf file for that and restart the database, but how to do that dynamically, say, from node.js?

A: Have the 8 dbs running alongside and connect to the wanted one on the "right-for-that-user" port when creating the connection to neo in node.
I think any other "stop-start other" solution would cause interruption of service and lost data.
I'm curious of the why you have that need, unless you are hosting neo for several companies.
If you want to hide data from different users of the same app. Well, create roles, lock everything and provide custom endpoints.


text:
Q: How can I invert AND reinvert (flash) another process's X11 window? I need to implement a visual bell for Konsole, because it doesn't honour the accessibility settings on my Ubuntu/KDE set-up.
I've cobbled together a utility to invert the currently focused X11 window, and have it triggered by Konsole, but I can't work out how to get it to re-invert the window without simply calling the invert program twice from a shell script (which works, but is ugly).
#include <X11/Xlib.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    Display *dpy;
    Window focused=0;
    Window rr;
    int revert_to=0;
    GC gc;
    XGCValues gcv;
    int xr, yr;
    unsigned int wr, hr, bwr, dr;

    struct timespec tp1;
    struct timespec tp2;

    dpy = XOpenDisplay(":0.0");
    XGetInputFocus(dpy, &focused, &revert_to);
    XGetGeometry(dpy, focused, &rr, &xr, &yr, &wr, &hr, &bwr, &dr);

    gc = XCreateGC(dpy, focused, 0, NULL);
    XSetSubwindowMode(dpy, gc, IncludeInferiors);

    gcv.function = GXcopyInverted;
    XChangeGC(dpy, gc, GCFunction, &gcv);
    XFlushGC(dpy, gc);
    XCopyArea(dpy, focused, focused, gc, xr, yr, wr, hr, 0, 0);

    clock_gettime(CLOCK_REALTIME, &tp1);

    for(;;) {
      XEvent e;
      while (XPending(dpy)) XNextEvent(dpy, &e);

      usleep(5000);

      clock_gettime(CLOCK_REALTIME, &tp2);
      if (((tp2.tv_nsec - tp1.tv_nsec)/1000000 + 1000 * (tp2.tv_sec - tp1.tv_sec)) > 15)
        break;
    }

    exit(0);
}

I tried to add a second copy operation - inverting or non-inverting - as follows:
int invert=0;
long slept=0;

for(;;) {
  XEvent e;
  while (XPending(dpy)) XNextEvent(dpy, &e);

  if (invert == 0 || slept > 29) {
    switch (invert++) {
      case 1:
        gcv.function = GXcopyInverted;
        break;
      case 2:
        gcv.function = GXcopyInverted;
        // gcv.function = GXcopy;
        break;
      case 3:
        exit(0);
    }
    XChangeGC(dpy, gc, GCFunction, &gcv);
    XFlushGC(dpy, gc);
    XCopyArea(dpy, focused, focused, gc, xr, yr, wr, hr, 0, 0);

    clock_gettime(CLOCK_REALTIME, &tp1);
    slept=0;
  }

  usleep(5000);

  clock_gettime(CLOCK_REALTIME, &tp2);
  slept = ((tp2.tv_nsec - tp1.tv_nsec)/1000000 + 1000 * (tp2.tv_sec - tp1.tv_sec));
}

Sometimes it works, sometimes it just blanks the window, sometimes it doesn't do anything. The console refreshes the blanked or inverted data readily enough, but it's confusing.
I presume I have to return control to X11 somehow between inversion operations, to synchronise, but I don't really know what I'm doing. :)
The code I stole the basis of this from created a bitmap (to display in another window), so I suppose I could copy the original into a bitmap and then copy it back, but I'm enticed by the first listing above not needing that.
Help?