text:
Q: xUnit Runner for Visual Studio 2012 and native .dlls Context
I am an application with C# and C++/CLI dlls. The C++/CLI dlls reference pure C++ .dlls, e.g. the boost libraries.
Tests are compiled into Tests.dll, which is placed with all the other binaries in $(SolutionDir)\bin\Debug.
Problem
Trying to run the xunit tests using Visual Studio 2012 fails, with the following error:
xUnit.net: Exception discovering tests from C:\Dev\xu-tests\bin\Debug\Tests.dll:
> System.IO.FileNotFoundException: Could not load file or assembly 'ManagedCpp.DLL'
> or one of its dependencies. The specified module could not be found.
> File name: 'ManagedCpp.DLL'

I can reproduce the problem in two ways outside of visual studio:

*

*When trying to run the console runner from outside this directory
..(longpath)..\xunit.console.clr4.exe Debug\Tests.dll

*When trying to run the GUI runner from its installed directory.
I can get it to work however when I use the console to get to the bin\Debug directory, then start the console or GUI runner from there.
This makes me believe that the problem is that VS2012 tries to run the unit tests not using the bin\Debug directory as working directory.
Question
How can I set the working directory in which xunit is run to $(OutDir) (or any specific directory)?


text:
Q: How can I create my web pages Read Only for peoples? I have a website http://www.bccfalna.com/ and the contents on this site are in HINDI Language. I want to make all these pages read only for peoples so that they can not copy the content.
Since I have written some books in HINDI Language on Computer Technology and I know that there are very few Information in HINDI language on the Internet about the Computer and I.T. Technology so I want to sell my EBooks in PDF format.
To show the usefulness of the contents of my books, I have placed all the contents in TEXT format in my website, so that people can see, read and can make decision to buy the book if the book is useful for them.
Since I have placed my whole books in Content form on my site so that various search engines also can give more and more traffic to my site but I am afraid that since I have placed all my content on my site in text form, any one can copy and will not be interested to buy them as PDF Format EBOOK.
I want that people can Read the content of my site but can not be able to copy the contents in any word processor.
Is it possible?
I don't want to make image like content, because Google, Yahoo like modern search engines don't gives too much importance to image sites.
I don't want to use Flash like sites too. The reason is same. Modern Search Engines don't gives too much attention to these kinds of sites.
I want my contents in TEXT format but I want to make them READ ONLY. Is it possible? If Yes: I would like to know HOW? and if No, I would like to get the alternative type solution.
Is there someone Genius to solve this problem? Thanks.

A: Generally speaking, any web content that is readable by a search engine will also be readable and copyable by people visiting your page.
I suppose you could examine the user_agent in the HTTP request to determine whether it originated from a popular search engine or not; if it did, return the plain-text of your content; if it did not, return a raster image of your content (text in an image can't be selected for copying and pasting, but it could be OCR'd or otherwise printed by the user). Some websites will use a script to disable right-clicking to save an image (but such scripts can easily be circumvented). Some sites will place a transparent image over the image containing the content (but this, too, can be circumvented). Note that the user_agent can be falsified if the web surfer knows you're treating search engines specially.
I suggest the best approach, though, is to keep things simple. Only publish the first chapter of your book and a table of contents online, or else only publish the first page of each chapter, or something similar. Search engines do not need the complete text of your book, only representative samples. Nobody will go to the trouble of copy/pasting your text if they can only get to a portion of the complete book.

A: You can't make it indexable to search engines and incapable of being copy & pasted... Google has to be able to copy words from your text to use in it's index. Maybe you could put snippets of the parts you want indexed in text format and put the majority in image/flash. It's not uncommon to see chapter previews on websites selling books.

A: Try Google Books:
I don't know if it works with the HINDI Language (It works. Some examples: http://www.scribd.com/doc/15257971/Google-Hindi-Books)
This solution allows Google to index and everyone to read the whole content. Anyhow copying remains awkward.
http://books.google.com/googlebooks/tour/

A: "Read-only" means they cant modify your webpages, "readable but not copyable" is impossible by definition, and makes about as much sense as "I want to give someone some water, but I dont want it to be wet".  So, to answer your question, no this is not possible at all.  (I regularly have to deal with people who think that this (and others) law of physics/mathematics doesn't apply to them, so sorry if I sound a bit rude.)
On a practical level, if you only give them some of the information, then they will only be able to copy that part of the information.  (If they buy the book, they will be able to copy the rest from there.)

A: As others here have said, what you are asking is not possible.
If you host content for people to view in a browser, and for Google to index, there is absolutely no way to stop anyone from copying it.  It is possible to make copying the content difficult (or at least inconvenient), but there's no way to stop someone from copying it if that's what they really want to do.
The only alternative, as others have already said, is to only post the first chapter of the book, and allow your readers to make a judgement based on that chapter.  If they like the chapter they'll buy the whole book.  This is a pretty common practice.
I understand that posting only part of the content is not what you want, but if you want to make it impossible to copy the whole book then this is your only real option.
The other alternative is to not worry about it.  Cory Doctorow (and others I'm sure) publishes all his books under a Creative Commons license.  They are free to download from his website but he still manages to make money from selling actual books.  If people like your work enough, they'll pay to have it in a nice format.

A: There is, a way to instruct the browser to disable copying text.  This does not, however, prevent copying, just makes is difficult.  Not all browsers recognize this, especially older browsers.  However, there are ways around this, the user can download the entire page and search for the text embedded in the HTML.
Another way, is to make it a graphic, rather than ASCII text.  That way would mean that if anyone really wanted to copy your content, they would have to go through the process of using OCR (optical character recognition), then proof read plus correct the result.
Another way is to make it into a Flash animation, that can also be bypassed by doing a screen capture, then doing an OCR.  In short, there is no way to prevent copying of material displayed in a browser ... but you can make it difficult and, hopefully, people won't bother.
FYI, typically people want their website to be read-only, to make it difficult or impossible for hackers to change their website content (i.e. replace content with vandalized content) ... not to prevent people from accessing the content legitiamately uploaded to the website.
Hope this helps.

A: Scan the text and post as an image, people can still read but not copy the text directly. They can copy the image but that will not matter as it would be the same as just reading from the screen they would have to retype it all if they wanted to steal the work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bi-directional One-to-One mapping with @EmbeddedId and Foreign key I'm having some trouble with a bi-directional one-to-one mapping, using @EmbeddedId and Foreign key.
Every time a perform a em.find(Bkftd03,Bkftd03PK.class) y obtain the same error:
Error performing load command : org.hibernate.TypeMismatchException:
Provided id of the wrong type for class com.ibc.gsr.entity.Bkftd03. Expected: class com.ibc.gsr.entity.Bkftd03PK, got class com.ibc.gsr.entity.Bkftd27PK

The main table structure looks something like this:
Entity
@Table(name="BKFTD03")
@NamedQuery(name="Bkftd03.findAll", query="SELECT b FROM Bkftd03 b")
public class Bkftd03 implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private Bkftd03PK id;

    @OneToOne
    @JoinColumns({
        @JoinColumn(name="PRO_NUM_PROPUESTA", referencedColumnName="PRW_NUM_PROPUESTA", nullable=false)
    })
    private Bkftd27 bkftd27;

And the inverse mapping table:
@Entity
@Table(name="BKFTD27")
@NamedQuery(name="Bkftd27.findAll", query="SELECT b FROM Bkftd27 b")
public class Bkftd27 implements Serializable {

    @EmbeddedId
    private Bkftd27PK id;

    @OneToOne(mappedBy="bkftd27")
    private Bkftd03 bkftd03;

And the PK for both entities:
@Embeddable
public class Bkftd03PK implements Serializable {
    //default serial version id, required for serializable classes.
    private static final long serialVersionUID = 1L;

    @Column(name="PRO_NUM_PROPUESTA", nullable=false, precision=12, columnDefinition="NUMBER(12,0)")
    private long proNumPropuesta;

 .....

@Embeddable
public class Bkftd27PK implements Serializable {
    //default serial version id, required for serializable classes.
    private static final long serialVersionUID = 1L;

    @Column(name="PRW_NUM_PROPUESTA",nullable=false, precision=12, columnDefinition="NUMBER(12,0)")
    private long prwNumPropuesta;

 .......

What I'm doing wrong?


text:
Q: auth pages not getting css in laravel I am beginner to laravel. I have created project. And I have run following commands to it.
composer require laravel/ui --dev
npm install
npm run dev
php artisan ui vue
php artisan ui vue --auth

after this command I get Login and Register menus on my welcome page.
Now my laravel welcome page loads properly. But when I click on login it shows plain html.
I serached and checked app.blade.php for links of css and js. It looks fine.
layouts/app.blade.php having following links
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<script src="{{ asset('js/app.js') }}" defer></script>

Where should be the problem? Why Login and Register not getting css, when welcome page gets css? Please guide.

A: I tried following commands in laravel 8 and it works well
composer require laravel/ui
php artisan ui bootstrap
php artisan ui bootstrap --auth
npm install
npm run dev
npm run production

A: Step 1:

*

*Download nodejs

*Install nodejs in your pc

Step 2:

*

*then open your project root and command

*composer require laravel/ui

*php artisan ui vue --auth

*npm install

*npm run dev
After npm command it will generate node_module folder inside your project remove that folder.
npm command only for .css and .js file.
for help see this video: https://www.youtube.com/watch?v=hOYW3jqh19I&t=9s

A: Some times cache can be the issue in such case, you can run
php artisan cache:clear and optionally php artisan view:clear.

A: You can download these two files from here :

*

*CSS File

*JS File
Then create css and js folders into public folder just put :
CSS file : app.css into project_folder/public/css/
JS file : app.js  into project_folder/public/js/
Its work for me. I think it will also work for you. Thanks.

A: You need to run the below commands for laravel 7.x.
Solution
First go to your project root folder  C:\Whatever\Your_project_name>
      composer require laravel/ui

Try any of the below command according to your front-end framework.
      php artisan ui vue --auth
      php artisan ui bootstrap --auth
      php artisan ui react --auth

At the end don't forget to run
      npm install

If your User Interface is not working properly try below command.
      npm run production

If the above commands don't work for you.

Reason: The error is because there is no css code in the public/css/app.css when you have executed all the commands but still there would be no code in that folder.
Take the file or code from here https://github.com/sabaoonbedar/Css-File-For-Laravel-Developers/tree/master  and place it in your project public/css/app.css OR create similar folders if don't exists.

A: The very simple solution for this problem is use the following cdn
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

instead of
<link href="{{ asset('css/app.css') }}" rel="stylesheet">

the links I have provided are the bootstrap cdn and check that . It will work
and use
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>

instead of
<link href="{{ asset('js/app.js') }}" rel="stylesheet">

A: For me it was simply the npm run dev command.
In my ubuntu 19.10, it has to run with sudo

A: I tried following commands in laravel 8 and it works well, you can also give it a try.
composer require laravel/ui
php artisan ui bootstrap --auth
npm install
npm run dev
npm run production

A: You must compile packages use npm run watch command. after that you can run npm run dev

A: You need to clear the cache on your browser. To confirm that go into incognito mode and try your URL again. If it works then that's the problem.

A: run

*

*npm install

*npm run dev

*npm run watch for continues compiling

A: It seems to me that your node.js version was outdated. Just update the Node.js and start from the beginning by installing the laravel ui and so on.
composer require laravel/ui
php artisan ui vue
php artisan ui vue --auth
npm install
npm run dev

Hope it will fix the problem.

A: Run the below commands in your Laravel project.
composer require laravel/ui
php artisan ui bootstrap --auth
npm install
npm run dev

A: I face the same problem while implementing the composer require laravel/ui in laravel version 7 but I fixed it by following the below steps.
First :

*

*Download nodejs

*Install nodejs in your pc

Second : run this command
composer require laravel/ui

Once the laravel/ui package has been installed, you may install the frontend scaffolding using the ui Artisan command:
// Generate basic scaffolding...
php artisan ui bootstrap
php artisan ui vue
php artisan ui react

// Generate login / registration scaffolding...
php artisan ui bootstrap --auth
php artisan ui vue --auth
php artisan ui react --auth

To generate node_module folder inside your project run the below command
npm install

Once the dependencies have been installed using npm install, you can compile your SASS files to plain CSS using Laravel Mix. The npm run dev command will process the instructions in your webpack.mix.js file. Typically, your compiled CSS will be placed in the public/css directory:
npm run dev

some time you may need to run this command npm audit fix or npm audit fix --force to fix some packages if they required to be.
Maybe some time by running this command npm run dev or npm run watch it will show you an error like below.

@ dev C:\xampp\htdocs\Auth
 npm run development
@ development C:\xampp\htdocs\Auth
mix
        Additional dependencies must be installed. This will only take a moment.

        Finished. Please run Mix again.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ development: `mix`

jus run the npm run watch again it will start Mix █████████████████████████ emitting (95%) after the success the build will be succeeded too.

A: This command working in my machine command.
npm run dev

A:    composer require laravel/ui

   php artisan ui vue
   npm install
   npm run dev

   php artisan ui vue --auth
   npm install
   npm run dev

You will have to call npm install and npm run dev for both scaffolding

A: I was facing the same issue CSS & js works with CDN links but not with default CSS. so there was files no CSS code in the public/css/app.css and js files so I copy and paste the code and files in the public directory from my another laravel directory and now that works fine.

A: after install every thing try this
npm update vue-loader

A: In my case, I just downloaded the latest version of nodejs and install it. After, just type npm run dev. And refresh your browser and good to go!! Cheers!!

A: you can use the styles and the script like this :
Style :
 <link href="/css/app.css" rel="stylesheet">

JS :
 <script src="/js/app.js"></script>

A: Run the command:
npm uninstall popper.js && npm i @popperjs/core

to remove the deprecated package and install their new Popper v2.

A: Public your CSS. I mean keep your CSS file in the public directory of your project.
Your css file should be here at: yourprojectname\public\css\app.css


text:
Q: Removing old semaphores systemV Essentially I would like for when my program on starts up to perform something along the lines of
set IPCS_S = ipcs -s | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f2 -d" "

for id in $IPCS_S; do
  ipcrm -s $id;
done

I want this to ensure that I am not going to open up a left over semaphores(semaphores that were left open after an abnormal termination).
Is there a way to do this with native C++ code? Or is my best bet to call the external shell script?

A: Try this:
Save this file as "removeipc.sh" and then "chmod 777 removeipc.sh",
#!/bin/bash

ME=`whoami`

IPCS_S=`ipcs -s | egrep "0x[0-9a-f]+ [0-9]+" | grep $ME | cut -f2 -d" "`
IPCS_M=`ipcs -m | egrep "0x[0-9a-f]+ [0-9]+" | grep $ME | cut -f2 -d" "`
IPCS_Q=`ipcs -q | egrep "0x[0-9a-f]+ [0-9]+" | grep $ME | cut -f2 -d" "`

for id in $IPCS_M; do   echo $id   ipcrm -m $id; done

for id in $IPCS_S; do   echo $id   ipcrm -s $id; done

for id in $IPCS_Q; do   echo $id   ipcrm -q $id; done


text:
Q: Python: boxplot dataframe with multi-index I am trying to create a boxplot, where on the x-axis I will refer to the two columns of the dataframe, while on y-axis I will show values of the 3rd column.
Let me refer to an example dataframe:
  Lvl1  Lvl2  value
0    A     1      1
1    A     2      2
2    A     1      3
3    B     2      4
4    B     1      5
5    B     2      6

Now, I want to have boxplots for the groups corresponding to Lvl1 and Lvl2. For example for group represented by (Lvl1 = A, Lvl2 = 1) boxplot would be calculated of values of {1,3}.
I know I can create a new column like Lvl0 which would be something like Lvl1 + Lvl2, but is there a way to create a boxplot without such operation?
On the following code:
import pandas as pd
import matplotlib.pyplot as plt

dataset = pd.DataFrame(
    {'Lvl1': ['A', 'A', 'A', 'B', 'B', 'B'], 'Lvl2': [1, 2, 1, 2, 1, 2], 'value': [1, 2, 3, 4, 5, 6]})
grouped = dataset.groupby(['Lvl1', 'Lvl2'])
grouped.boxplot()
plt.show()

I get an error:
KeyError: "None of [Index(['A', 1], dtype='object')] are in the [index]"
Thank you in advance!

A: Try to use seaborn for an easier solution. I think it was answered here: Grouping boxplots in seaborn when input is a DataFrame
With your data:
import seaborn as sns
import pandas as pd

data = pd.DataFrame({'lvl1': ['A', 'A', 'A', 'B', 'B', 'B'],
                     'lvl2': [1, 2, 1, 2, 1, 2],
                     'value': [1, 2, 3, 4, 5, 6]})

df_long = pd.melt(data, "lvl1", var_name="lvl2", value_name="result")

sns.boxplot(x="lvl1", hue="lvl2", y="result", data=df_long)

We get:

If you need more levels, try to combine plots with sns.FacetGrid (https://seaborn.pydata.org/generated/seaborn.FacetGrid.html).
Here I propose using sns.catplot:
data = pd.DataFrame({'lvl1': ['A', 'A', 'A', 'B', 'B', 'B', 'A', 'B'],
                 'group': ['1', '2', '1', '2', '1', '2', '2', '1'],
                 'has_something': [True, False, False, True, True, False, True, False],
                 'before': [3, 4, 5, 5, 3, 4, 2, 6],
                 'after': [1, 2, 3, 4, 5, 6, 2, 3],
                 'baseline': [1, 0, 0, 1, 1, 0, 0, 1]})

df = pd.melt(data, ["lvl1", 'group', 'has_something'], value_name="result")

sns.catplot(data=df, x='lvl1', y='result',
col='group', kind='box', hue='variable', col_wrap=2, margin_titles=True)

And result here:

In order to include 'has_something' variable to the plot, you can use FacetGrid or separate data by 'has_something' and make two plots with different filtered data.

A: You can do it through seaborn. Following code works for me on your data:
import pandas as pd
import seaborn as sns

dataset = pd.DataFrame(
    {
        'Lvl1': ['A', 'A', 'A', 'B', 'B', 'B'], 'Lvl2': [1, 2, 1, 2, 1, 2],
        'value': [1, 2, 3, 4, 5, 6]
    }
)
ax = sns.boxplot(x='Lvl1', y='value', hue="Lvl2", data=dataset)

Expired output:


text:
Q: Adding a table of data to a dictionary excel vba I'm brand new to using dictionaries and could do with a bit of help. I've got a table of data in range A1:C4
A   B   C
1   4   7
2   5   8
3   6   9
Is there any way of adding this tables directly into a dictionary?
Thanks in advance

A: Dim d As Scripting.Dictionary
Dim r As Excel.Range
Dim c As Excel.Range

Set d = New Scripting.Dictionary
Set r = Range("a1:c4")

For Each c In r.Cells
    d.Add CStr(c.Address), c.Value
Next c

A: I think what you're probably looking for is a Multidimensional Array
A standard Array will hold a series of values in a list, and the value of any point in this list can be referenced, for example:
myArray = Array("One", "Two", "Three")

'The first value in an array is at position 0 unless otherwise specified
MsgBox myArray(0) 'Will open a message box with the value "One"
MsgBox myArray(1) 'Will open a message box with the value "Two"
MsgBox myArray(2) 'Will open a message box with the value "Three"

Whereas a standard array is one dimensional, using a Multidimensional Array allows you to add more than one dimension to this list. Put simply a two dimensional array will let you create a table of data.
dim myArray(1 to 3, 1 to 3) as Variant will create a two dimensional array, by also specifying '1 to 3' will allocate a set size and range of items that can be referenced in the array. Take for example this table:
A    B    C
D    E    F
G    H    I
To put this into a multidimensional array would be the following
Dim myArray(1 To 3, 1 To 3) As Variant

myArray(1, 1) = "A"
myArray(1, 2) = "B"
myArray(1, 3) = "C"
myArray(2, 1) = "D"
myArray(2, 2) = "E"
myArray(2, 3) = "F"
myArray(3, 1) = "G"
myArray(3, 2) = "H"
myArray(3, 3) = "I"

MsgBox myArray(2, 2) 'Will open a message box with the value "E"

Given you are looking to produce this from Range("A1:C4") you could use a loop to go through each cell create this:
Dim myArray(1 To 4, 1 To 3) As Variant

For Each c In Range("A1:C4")
    myArray(c.Row, c.Column) = c.Value
Next c


text:
Q: How to get parent domain out of url no sub-domain I was trying out this from a very long time, Need a JavaScript function to extract Parent domain from URL.
Input
https://app.domainname.io
http://domainname.net
https://domainname.com
https://app.domain.com
https://www.google.co.in
http://dev2-aa.domain-name.com
https://app.domain.co.in
Output
domainname.io
domainname.net
domainname.com
domain.com
google.co.in
domain-name.com
domain.co.in
Thank you

A: This solution might not be perfect but works for your sample data:
function extractDomain(url) {
  return url.match(/https?:\/\/(?:\S+\.)*(\S{3,}(?:\.\S{1,3}){1,2})/)[1]
}

Explanation:
https?:\/\/: Looks for http or https
(?:\S+\.)*: Matches but not captures any number of subdomains
(\S{3,}(?:\.\S{1,3}){1,2}): Captures the domain and the TLD. In detail:
S{3,}: Looks for something longer which should be the domain part (eg. google). This is not perfect, because a 2 letters long domain name would not match.
(?:\.\S{1,3}){1,2}: Matches the TLD part: a single TLD (eg. .com) or two short parts (eg. .co.in).

A: We could try this,
function getHostName(url) {
    var match = url.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/i);
    if (match != null && match.length > 2 && typeof match[2] === 'string' && match[2].length > 0) {
    return match[2];
    }
    else {
        return null;
    }
}

function getDomain(url) {
    var hostName = getHostName(url);
    var domain = hostName;

    if (hostName != null) {
        var parts = hostName.split('.').reverse();

        if (parts != null && parts.length > 1) {
            domain = parts[1] + '.' + parts[0];

            if (hostName.toLowerCase().indexOf('.co.uk') != -1 && parts.length > 2) {
              domain = parts[2] + '.' + domain;
            }
        }
    }

    return domain;
}


text: Q: remove text quotations using sql I am getting data from odbc connection using SQL , the problem I have is that all the text format data still have " " , is there anything in SQL I can add to remove these please. example "John" would like it to be just John


text:
Q: Using current url in a javascript function I have this js function
function twitterShare(){
    window.open( 'http://twitter.com/intent/tweet?text='+$(".section-title h1").text() +'
    '+window.location, "twitterWindow",
    "height=380,width=660,resizable=0,toolbar=0,menubar=0,status=0,location=0,scrollbars=0")
    return false;
}

When the twitter window opens it grabs the .section-title h1 class, but I need it to say something like this,
"Check this out here: http://currentwebsiteurl.com"
I need a text string then grab the url of the page.
Any help would be greatly appreciated.

A: You can use window.location.href. It holds the value of the current page you are on.

A: window.location.href contains the current URL of the page.
So your function should look like this:
function twitterShare(){
    window.open('http://twitter.com/intent/tweet?text=Check this out here: ' + window.location.href,
                "twitterWindow", "height=380,width=660,resizable=0,toolbar=0,menubar=0,status=0,location=0,scrollbars=0")
    return false;
}


text:
Q: calling Javascript from java using ScriptEngine i am trying to open the new tab from java itsself using scriptEngine.
private static void openWindow(URL url) {
    String javascript = "window.open(url, '_blank').focus()";
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    engine.put("url", url);
    try{
        engine.eval(javascript);
        }
    }
    catch(ScriptException exception){
        log4j.error("Couldn't open URL in Browser: " + exception.getMessage(), exception);

    }
}

i am getting following exception :
javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "window" is not defined. (#1) in  at line number 1
I understand windows cannot be referenced but what is the alternative here ?
Any pointers would be of great help.

A: This piece of Java has no reference to a browser, hence the error saying that window is not defined.
In case you really want to interact with a browser from Java you might consider looking into Selenium Webdriver. This is often used for testing purposes but might fit your need also.
For opening a page see this Selenium example.


text:
Q: fetch the value from any one of dropdown list from two dropdown list I have two dropdown lists to select value from. What I want is that when the user selects a value from the any one of the list, he cannot select a  value from the another list.

A: You need to listen to the selected item change event from both lists and when one of them is triggered then disable the other list. This assumes both lists are in the same context (class or form).
The problem with this is that if the person made a mistake he is now not capable of changing his selection in the previous list. You may need either a reset or a "none" item in each list that when selected will enable the other list again.
Hope this helps

A: On selection of any dropdown onchange call a function and pass the
disableDrop(id of other dropdown);

disableDrop(id) {

$("#" + id option[value]").prop('disabled',true);

}


text:
Q: SQL Help(Date Functions) I need help on SQL Queries.
TABLE:
Create Table Employees
        ( employee_id   number(3) Primary Key,
          first_name    varchar2(10),
          last_name varchar2(10),
          dept_code varchar2(3),
          hire_date date,
          credit_limit  number(4,2),
          phone_ext varchar2(4),
          manager_id    number(3)
        );

Entries:
insert into Employees values (201, 'Susan', 'Brown', 'Exe', To_Date('01-Jun-1998','DD-Mon-YYYY'), 30, '3484', null);
insert into Employees values (202, 'Jim', 'Kern', 'Sal', To_Date('16-Aug-1999','DD-Mon-YYYY'), 25, '8722', 201);
insert into Employees values (203, 'Martha', 'Woods', 'Shp', To_Date('02-Feb-2004','DD-Mon-YYYY'), 25, '7591', 201);
insert into Employees values (204, 'Ellen', 'Owens', 'Sal', To_Date('01-Jul-2003','DD-Mon-YYYY'), 15, '6830', 202);

I need a query to List all the employees, their hire dates and the number of days each person will have worked for the company as of January 1, 2007.

A: You can use YEAR() on a date field:
SELECT * FROM Employees WHERE YEAR(hire_date)='2003'

if it doesn't work, you can use EXTRACT():
SELECT * FROM Employees WHERE EXTRACT(YEAR FROM hire_date)='2003'

and, as Alan Hadsell rightly commented:
SELECT COUNT(*) FROM Employees WHERE EXTRACT(YEAR FROM hire_date)='2003'


text:
Q: Relaying multicast traffic between docker network and host network I've been trying to multicast traffic between the docker network and the host network. Here's an example of my current setup, with docker containers in blue inside the purple docker network and host network PC's in orange inside the yellow host network:

As you can see, I'm trying to capture and relay multicast traffic inside the 'Relay' docker container. I've given it the --net host option to make the host network interface (ens160) available to it. This allows me to capture traffic on both the docker interface (docker0) and the host interface, after which I resend the traffic over the opposite interface (traffic captured on docker interface gets resent using the host interface and vice versa).
This seems to work when I resend traffic from the docker network to the host network. But traffic from the host network does not want to get sent to the docker network. The green arrows represent successful multicast traffic flows, as in, I confirmed that multicast traffic is sent and received along the arrow. The red arrows show that multicast traffic is not being received on the arrow-ends. All the traffic is sent/received on the same port.
Here's some of the Python code of the relay program:
import socket, netifaces as ni
from scapy.all import sniff, Raw, IP, UDP

def pkt_found(other_sock, multicast_address, port, iface_ip):
    def save_pkt(pkt):
        if pkt[IP].src != iface_ip:
            pkt[IP].src = iface_ip
            pkt[IP].dst = multicast_address
            pkt[UDP].sport = port
            pkt[UDP].dport = port
            del pkt[IP].chksum
            pkt.show2()
            other_sock.sendto(bytes(pkt[Raw]), (multicast_address, port))
    return save_pkt

def listen_for_traffic(iface_name, other_sock, multicast_address, port, iface_ip):
    sniff(iface=iface_name, filter="dst port "+str(port), prn=pkt_found(other_sock, multicast_address, port, iface_ip))

def createMulticastSocket(iface_ip, multicast_address, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
    socket.inet_aton(multicast_address)+socket.inet_aton(iface_ip))
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 64)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
    sock.bind((multicast_address, port))
    return sock

multicast_address = "225.0.0.0"
port = 1234

docker_iface_name = "docker0"
host_iface_name = "ens160"

docker_iface_ip = ni.ifaddresses(docker_iface_name)[ni.AF_INET][0]['addr']
host_iface_ip = ni.ifaddresses(host_iface_name)[ni.AF_INET][0]['addr']

docker_sock = createMulticastSocket(docker_iface_ip, multicast_address, port)
host_sock = createMulticastSocket(host_iface_ip, multicast_address, port)

docker_thread = threading.Thread(target=listen_for_traffic, args=(docker_iface_name, host_sock, multicast_address, port, docker_iface_ip,))
host_thread = threading.Thread(target=listen_for_traffic, args=(host_iface_name, docker_sock, multicast_address, port, host_iface_ip,))

docker_thread.start()
host_thread.start()

Does anyone know what I might be doing wrong?

A: Apparently I should have bound the sockets to the interface IPs instead. Changing  sock.bind((multicast_address, port)) to sock.bind((iface_ip, port)) did the trick.


text:
Q: Timestamp with auto increment in Cassandra Want to write System.currentMiliseconds in the cassandta table for each column by cassandra. For example
writeToCassandra(name, email)

in cassandra table:
--------------------------------
name | email| currentMiliseconds

Can cassandra prepare currentMiliseconds column automatically like auto increment ?
BR!

A: You can try with: dateof(now())
e.g.
INSERT INTO YOUR_TABLE (NAME, EMAIL, DATE)
                VALUES ('NAME',  'EMAIL', dateof(now()));

A: Cassandra has some sort of columnar database taste inside. So if you read docs how the columns are stored inside SSTable, you'll notice that each column has a personal write timestamp appended (used for conflict resolution, like last-write-wins strategy). You can query for that timestamp using writetime() function:
cqlsh:so> create table ticks ( id text primary key, value int);
cqlsh:so> insert into ticks (id, value) values ('foo', 1);
cqlsh:so> insert into ticks (id, value) values ('bar', 2);
cqlsh:so> insert into ticks (id, value) values ('baz', 3);
cqlsh:so> select id, value from ticks;

 id  | value
-----+-------
 bar |     2
 foo |     1
 baz |     3

(3 rows)
cqlsh:so> select id, writetime(value) from ticks;

 id  | writetime(value)
-----+------------------
 bar | 1448282940862913
 foo | 1448282937031542
 baz | 1448282945591607

(3 rows)

As you requested, I've not explicitly inserted write timestamp to DB, but able to query it. Note you cannot use writetime() function for PK.


text:
Q: ElasticSearch Tagline: How to Change How in the world to you change the ridiculous and useless tagline in ElasticSearch?
'tagline' is not found in /etc/elasticsearch/elasticsearch.yml, and when I add it, it has no effect.
Is it hard-wired into the code? What is the point of the dang thing if it can't be changed?
The intertubes seem totally silent on this.... just a thousand results repeating the same ridiculous and useless tagline.

A: The same way you cannot change the tagline of any company (intellectual property anyone?), that tagline cannot be changed as well and is hardcoded into RestMainAction.java.
It should be merely considered as Elasticsearch's way of saying "Hello world".


text:
Q: PHP Append to Multidimensional Arrays I'm trying to append to an array that I have stored in a database. It is saved as a serialized array. I need to pull it out of the DB unserialize it, add to it and then serialize and store it again. I'm not having any issues with anything except the part where I update the array.
The array is as follows:
Array
   (
      [pages]=>Array
            (
                [0]=>12
                [1]=>43
                [2]=>34
            )
      [images]=>Array
            (
                [0]=>54
                [1]=>89
                [2]=>78
            )
   )
//I tried this

$newid = 33;
$array['pages'][] = $newid;

I need to add values to the second dimension of the array. Any ideas?

A: That works exactly the same as for the first subarray:
$newid = 555;
$array['images'][] = $newid;

A: Assuming the array you're working with is stored in a variable named $array, which is not clear from your example, your assignment should work as expected, and set [pages][3]=>33
Then images sub-array can be accessed the same way, substituting 'images' for 'pages'

A: May be you feel more comfortable with array_push():
array_push($array['pages'], $newid);


text:
Q: $\sqrt{3}$ represented as continued fraction Am I incorrect in the assumption that I deal with $\sqrt{3}$ in the same way I would approach $\sqrt{2}$, by adding and subtracting $1$ such that:
$\sqrt{3}=1+\sqrt{3}-1=1+\cfrac{2}{1+\sqrt{3}}$
The table representation is $[1; 1,2]$.
This is what I have so far:
$\sqrt{3}=1+\cfrac{2}{2+\cfrac{2}{1+\sqrt{3}}}$
Which seems to lead me to $[1;2,2,...]$ any help would be appreciated, thanks

A: The numerators should be all $1$. The procedure is to write $x>0$ as
$$
x=x_0+y_0
$$
with $0\le y_0<1$. If $y_0=0$, we're done. Otherwise we set
$$
\frac{1}{y_0}=x_1+y_1
$$
in the same fashion and go on with the same rule.
In your case, $y_0=\sqrt{3}-1$, so
$$
\frac{1}{y_0}=\frac{1}{\sqrt{3}-1}=\frac{\sqrt{3}+1}{2}=
1+\frac{\sqrt{3}-1}{2}
$$
Therefore $x_1=1$ and $y_1=\frac{\sqrt{3}-1}{2}$. Then
$$
\frac{1}{y_1}=\frac{2}{\sqrt{3}-1}=\sqrt{3}+1=2+(\sqrt{3}-1)
$$
Hence $x_2=2$ and $y_2=\sqrt{3}-1$.
OK, now we'll go on forever with the same numbers. Hence $x_n=1$ for odd $n$ and $x_n=2$ for even $n>0$:
$$
\sqrt{3}=[1;1,2,1,2,\dots]=1+
\cfrac{1}{
  1+\cfrac{1}{
    2+\cfrac{1}{
      1+\cfrac{1}{
        2+\ddots
      }
    }
  }
}
$$
See http://planetmath.org/tableofcontinuedfractionsofsqrtnfor1n102

A: You seem to have worked out something that looks correct. Now prove it. Put
$$x=\frac2{2+\frac2{2...}}\implies1+x=1+\frac2{2+x}\implies2x+x^2=2\implies$$
$$x^2+2x-2=0\implies x_{1,2}=\frac{-2\pm\sqrt{12}}{2}=-1\pm\sqrt3$$
as all above is positive we must have $\;x=-1+\sqrt3\;$ , and then $\;1+x=\sqrt3\;$ , as expected.

A: If you obtain a rational approximation of $\sqrt{3}$, for example $\frac{362}{209}$ you'll find its continued fraction is $$1+\frac{1}{1+\frac{1}{2+\frac{1}{1+\frac{1}{2+\frac{1}{1+\frac{1}{2+\frac{1}{3}}}}}}}$$ That 3 looks extraneous, so we might form the conjecture that $$\sqrt{3}=1+\frac{1}{1+\frac{1}{2+\frac{1}{1+\frac{1}{2+\frac{1}{1+\frac{1}{2+\ddots}}}}}}$$
Then we can prove that by calling the RHS x
$$x=1+\frac{1}{1+\frac{1}{1+\color{red}{1+\frac{1}{1+\frac{1}{2+\frac{1}{1+\frac{1}{2+\ddots}}}}}}}=1+\frac{1}{1+\frac{1}{1+x}}$$
Then by simple algebra we can verify that $x=\sqrt{3}$.
On a small digression, these rational approximations might seem hard to obtain but I found that with the chakravala method in a few minutes.


text:
Q: Find a Stirling-formula like for $(x!)!$ Hi working again on the gamma function I find that :
let $0<x\leq 1$ and $1\leq k\leq \infty$ then define :
$$f(x)=(x!)!,g(x)=\left(\left(x!\right)!\right)^{\frac{1}{e^{x^{k}}}}$$
Then a conjecture :
It seems $\exists k\in(1,\infty)$ such that $g(x)$ admits an asymptote as $x\to \infty$.
Then see here Trying to prove the Stirling approximation using concavity for $x\geq 1$ we can squeeze the function $f(x)$ and remains to determine some constant .
If my conjecture is true how to achieve this ?

A: Let $a$ to be the solution of $\psi^{(0)} (x+1)=0$ (I think that you know it).
Expand $f(x)=\log[(x!)!]$ around $x=a$ and write
$$f(x)=f(a)+\Gamma (a+1)\sum_{n=2}^\infty \frac {c_n} {n!}  \, (x-a)^n$$ The first terms are
$$\color{red}{c_2}=\psi ^{(1)}(a+1) \psi ^{(0)}(\Gamma (a+1)+1)$$
$$\color{red}{c_3}=\psi ^{(2)}(a+1) \psi ^{(0)}(\Gamma (a+1)+1)$$
$$\color{red}{c_4}=3 \Gamma (a+1) \psi ^{(1)}(a+1)^2 \psi ^{(1)}(\Gamma (a+1)+1)+$$ $$\left(3 \psi
   ^{(1)}(a+1)^2+\psi ^{(3)}(a+1)\right) \psi ^{(0)}(\Gamma (a+1)+1)$$
$$\color{red}{c_5}=10 \psi ^{(1)}(a+1) \psi ^{(2)}(a+1) (\psi ^{(0)}(\Gamma (a+1)+1)+$$ $$\Gamma (a+1) \psi
   ^{(1)}(\Gamma (a+1)+1))+\psi ^{(4)}(a+1) \psi ^{(0)}(\Gamma (a+1)+1)$$
and so on for as many terms as required.
Using the expansion to $O\left((x-a)^{n+1}\right)$, computing the norm
$$\Phi_n=\int_0^1 \Big[\log[(x!)!]-\text{approximation}_{(n)}\Big]^2\,dx$$
$$\left(
\begin{array}{cc}
n & \log_{10}\big[\Phi_n\big] \\
 2 & -5.0858 \\
 3 & -5.1547 \\
 4 & -6.3509 \\
 5 & -6.9713 \\
 6 & -7.9027 \\
 7 & -8.7240 \\
 8 & -9.5957 \\
 9 & -10.456
\end{array}
\right)$$

A: As I wrote in comment, the same work can be done for
$$g(x)=(x!)!$$
$$g(x)=g(a)+\Gamma (a+1) \Gamma (a!+1)\sum_{n=2}^\infty \frac {d_n} {n!}  \, (x-a)^n$$ The first coefficients being
$$\color{red}{d_2}=\psi ^{(1)}(a+1) \psi ^{(0)}(a!+1)$$
$$\color{red}{d_3}=\psi ^{(2)}(a+1) \psi ^{(0)}(a!+1)$$
$$\color{red}{d_4}=\left(3 \psi ^{(1)}(a+1)^2+\psi ^{(3)}(a+1)\right) \psi ^{(0)}(a!+1)+$$ $$3 \Gamma
   (a+1) \psi ^{(1)}(a+1)^2 \psi ^{(0)}(a!+1)^2+3 \Gamma (a+1) \psi ^{(1)}(a+1)^2
   \psi ^{(1)}(a!+1)$$
Computing again
$$\Psi_n=\int_0^1 \Big[[(x!)!]-\text{approximation}_{(n)}\Big]^2\,dx$$
$$\left(
\begin{array}{cc}
n & \log_{10}\big[\Psi_n\big] \\
 2 & -5.0613 \\
 3 & -5.0973 \\
 4 & -6.3083 \\
 5 & -6.7855 \\
 6 & -7.7200 \\
 7 & -8.3849 \\
 8 & -9.2041 \\
 9 & -9.9228 \\
10 & -10.691 \\
11 & -11.423
\end{array}
\right)$$
that is to say
$$\log_{10}\big[\Psi_n\big] \sim -\frac {3n+13}4$$


text:
Q: libmemcached fail over of a cluster's node i use libmemcached in "c" for write data whit MEMCACHED_DISTRIBUTION_CONSISTENT_KETAMA usage. All keys are well distributed along all clusters nodes, but when i shutdown one of these, the keys are not migrated. Searching on google is not clear how to setup libmemcached for doing' that automatically. Any one has some experience on that?

A: I think you'll have to use: http://docs.libmemcached.org/memcached_behavior.html#MEMCACHED_BEHAVIOR_REMOVE_FAILED_SERVERS
If you don't allow libmemcached to remove failed servers, they get stuck in the list, hence the keys are not redistributed.
Note that the dead server would be tested again after MEMCACHED_BEHAVIOR_DEAD_TIMEOUT (see 1, 2) seconds. So if it's up again, it will be brought back into the full servers' list.

A: Libmemcached does not internally handle key migration in case of memcached server failure. There will be cache miss in this case when the libmemcached tries to retrieve the key which was stored in a failed server.
If we use MEMCACHED_DISTRIBUTION_CONSISTENT_KETAMA, it will just make sure the cache miss is minimum as the keys are distributed and complete rehashing is not required.
Solutions:
You can replicate the keys across multiple nodes which will help you to retrieve the (key, value) pair in case of server failure. But note that it not a strongly consistent solution. There is possibility for stale data.
EVICT the servers that have failed, so that keys are hashed to new location and it gets removed from cluster.


text:
Q: How to save text from several UITextViews with one single Button in Swift
We have 4 outlets (UITextView) and finally a save Button.
I want to be able to save whatever we write in all of each TextViews with one simple Button. How to do that? I've made this work but saving one UITextView.
The code:
class agendaDeSuen_os: UIViewController , UITextFieldDelegate, UITextViewDelegate {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var primerTextView: UITextView!
    @IBOutlet weak var segundoTextView: UITextView!
    @IBOutlet weak var tercerTextView: UITextView!
    @IBOutlet weak var cuartoTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        //ScrollViewSize
        scrollView.contentSize.height = 1400

        //Hide keyboard with touching anywhere
        var tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
        view.addGestureRecognizer(tap)

        //Button
        let stringKey = NSUserDefaults.standardUserDefaults()

        segundoTextView.text = stringKey.stringForKey("savedStringKey")

    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()

        return true
    }

    //Hide keyboard with return button
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        if text == "\n"
        {
            primerTextView.resignFirstResponder()
            segundoTextView.resignFirstResponder()
            tercerTextView.resignFirstResponder()
            cuartoTextView.resignFirstResponder()

            return false
        }
        return true
    }

    @IBAction func botonGuardar(sender: AnyObject) {

        let myText = segundoTextView.text

        NSUserDefaults.standardUserDefaults().setObject(myText, forKey: "savedStringKey")
        NSUserDefaults.standardUserDefaults().synchronize()

        var alert = UIAlertController(title: "Guardado", message:"Tu texto se ha guardado", preferredStyle: UIAlertControllerStyle.Alert)

        alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))

        self.presentViewController(alert, animated: true, completion: nil)

    }

    //Hide keyboard with touching anywhere

    func DismissKeyboard(){

        view.endEditing(true)

    }

}

A: could you not just add three more NSUserDefualts in the botonGuardar function, eg.
let myPrimerText = PrimerTextView.text

NSUserDefaults.standardUserDefaults().setObject(myPrimerText, forKey: "savedPrimerStringKey")

A: I'll assume you're talking about saving all the text to NSUserDefaults.
Simply do what you've done but with different keys for each one.
NSUserDefaults.standardUserDefaults().setObject(myText, forKey: "textView1")
NSUserDefaults.standardUserDefaults().setObject(differentText, forKey: "textView2")
NSUserDefaults.standardUserDefaults().synchronize()

And then you just use the different keys to access different saved objects (in your case Strings).
Does this make sense?
Loic

A:
take outlets into an array. Use fast enumeration

let array:[UITextViews] = @[textview1,textview2,textview3,textview4];

func saveTextViewData() {

for textView in array {

saved.append(textView.text)

   }

}


text:
Q: Delete an entity without to delete the foreign key link to it I have a table Products the entity tva is link to the table Tva and the entity image is link to the table Media. I render in sonata admin all the products of the website. I would like to be able to delete a product from the administration.
I want be able to delete a product without to delete the foreign key link to it.
But i have this error:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails (fly.post,
  CONSTRAINT FK_5A8A6C8D4D79775F FOREIGN KEY (tva_id) REFERENCES
  tva (id))

This is my entity tva and image
/**
 * @ORM\ManyToOne(targetEntity="FLY\BookingsBundle\Entity\Tva", cascade={"persist", "remove"})
 * @ORM\JoinColumn(nullable=true)
 */

private $tva;

/**
 * @ORM\ManyToOne(targetEntity="FLY\BookingsBundle\Entity\Media", cascade={"persist","remove"})
 * @ORM\JoinColumn(nullable=true)
 */
private $image;

I decided to change the join column from this    * @ORM\JoinColumn(nullable=true)  to this * @ORM\JoinColumn(onDelete="CASCADE")  and it works i can delete the product but it also delete the foreign key and i don't want that because i have other product that use the same image and tva.

A: (onDelete="CASCADE") will delete the child record when parent record is deleted. If we don't want to delete the child record then we need to configure onDelete="SET NULL". This will set the foreign key value to null in child record.

A: I found a way to fix my problem :) I removed this line : cascade={"persist","remove"}and i changed this line * @ORM\JoinColumn(nullable=true) to * @ORM\joinColumn(onDelete="SET NULL")
/**
 * @ORM\ManyToOne(targetEntity="FLY\BookingsBundle\Entity\Tva")
 * @ORM\joinColumn(onDelete="SET NULL")
 */
private $tva;

/**
 * @ORM\ManyToOne(targetEntity="FLY\BookingsBundle\Entity\Media")
 * @ORM\joinColumn(onDelete="SET NULL")
 */
private $image;

Thank you so much @Darshan Mehta for your help. :)


text:
Q: Convert image byte array to PDF I'm looking to convert an Image (PNG, JPEG, GIF), in the form of a byte[] to a PDF.
I'm currently using this function, which works, but cuts off the bottom of images that over a certain height or specific proportions; for example 500x2000.
Where am I going wrong here?
public byte[] ConvertImageToPDF(byte[] bytes)
{
    byte[] pdfArray;
    using (var memoryStream = new MemoryStream())
    {
        using (var pdfWriter = new PdfWriter(memoryStream))
        {
            var pdf = new PdfDocument(pdfWriter);
            var document = new Document(pdf);
            ImageData imageData = ImageDataFactory.Create(bytes);
            document.Add(new Image(imageData));
            document.Close();
        }
        pdfArray = memoryStream.ToArray();
    }
    return pdfArray;
}

A: I suppose what you want is the PdfWriter to auto-scale the Image inside the Document.
Optionally, position the Image in the center of the Page.
You can change your code setting [Image].SetAutoScale(true) and [Image].SetHorizontalAlignment(HorizontalAlignment.CENTER):
Note: I've defined aliases for iText.Layout.Properties (alias: PdfProperties) and iText.Layout.Element.Image (alias: PdfImage), to avoid conflict with other .Net assemblies that have classes and enumerators with the same exact names. Just remove them in case you don't need them at all.
using iText.IO.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using PdfProperties = iText.Layout.Properties;
using PdfImage = iText.Layout.Element.Image;

public byte[] ConvertImageToPDF(byte[] imageBytes)
{
    using (var ms = new MemoryStream()) {
        using (var pdfWriter = new PdfWriter(ms)) {
            var pdf = new PdfDocument(pdfWriter);
            var document = new Document(pdf);

            var img = new PdfImage(ImageDataFactory.Create(imageBytes))
                .SetAutoScale(true)
                .SetHorizontalAlignment(PdfProperties.HorizontalAlignment.CENTER);

            document.Add(img);
            document.Close();
            pdf.Close();
            return ms.ToArray();
        }
    }
}

You can also specify the size, in floating point units, of the Image and use the [Image].ScaleToFit() method, to scale the Image within those bounds.
Here, using a PageSize set to PageSize.A4. You can of course set different measures.
using iText.Kernel.Geom;

// [...]
var document = new Document(pdf);

var page = document.GetPageEffectiveArea(PageSize.A4);
var img = new PdfImage(ImageDataFactory.Create(imageBytes))
    .ScaleToFit(page.GetWidth(), page.GetHeight())
    .SetHorizontalAlignment(PdfProperties.HorizontalAlignment.CENTER);

// [...]


text:
Q: if I give "no" as a response to any_toppings it asks what kind even though I said no favorite = input('What is your favorite kind of ice cream? ')

print(f'{favorite} is my favorite too!')

any_toppings = input('Do you put any kind of toppings on top? ')
print(any_toppings)

kind_of_toppings = input('Nice What kind? ')

if any_toppings.lower() == 'yes':
    print(kind_of_toppings)
elif any_toppings.lower() == 'no':
    print(" yea it is amazing by it's self!")
else:
    print('sorry i didnt catch that, try again')
    print(any_toppings)

A: Since you just have the input in the code, and it does not consider the if any_toppings.lower() == 'yes' when asking you for the input for kind_of_toppings = input('Nice What kind? '), it will run no matter what your input to any_toppings is so for your code you must move the input for kind_of_topping inside the if statement. It would look like:
favorite = input('What is your favorite kind of ice cream? ')

print(f'{favorite} is my favorite too!')

any_toppings = input('Do you put any kind of toppings on top? ')
print(any_toppings)

if any_toppings.lower() == 'yes':
    kind_of_toppings = input('Nice What kind? ')
    print(kind_of_toppings)
elif any_toppings.lower() == 'no':
    print(" yea it is amazing by it's self!")
else:
    print('sorry i didnt catch that, try again')
    print(any_toppings)


text:
Q: Why do we assume in the Principle of Strong/Complete Induction? I get induction.
(i) show that the statement holds when n=1 (or some basis)
(ii) show that the statement holds for a general subsequent case, $n+1$.
By PMI the statement holds for all cases.
Dominoes, and all that. I get it. It makes sense.
But when it comes to Principle of Strong/Complete Induction i don't understand why we are assuming it holds for a range. Honestly the whole 'assume' part of any induction is what gets me. Why do I need to assume anything? Isn't it adequate to show it works without assuming it?
I have added an example of PSI below.

Use PCI to prove that every natural number greater than or equal to $11$ can be written in the form $2s +5t$, for some natural numbers $s$ and $t$.

Approach:
I would think I need to show that it works for n=11, and it works for m=12, and then show how it will work for n+2 and m+2 (since both need a slightly different formula to compute).
$n=11 = 2(3) +5(1); s=3$ and $t=1$
$n=12 = 2(1) +5(2); s=1$ and $t=2$
so obviously, for each subsequent case n, you add another s to the n-2. I find it tricky to express this succinctly but here's my attempt at a proof.

Proof (by PCI):
(i) Let n be an integer greater than or equal to $11$.
When $n=11 = 2(3) +5(1); s=3$ and $t=1.$
When $n=12 = 2(1) +5(2); s=1$ and $t=2.$
Thus the statement holds for $n=11$ and $n=12$.
(ii) Assume the statement holds for $11\leq i \leq n$.
Because $n\geq 13$, $n-2 \geq 11$, so $n-2 = 2s =5t$ for some $s$, $t$ in $\mathbb{N}.$
Therefore $n=2(s+1) +5t$.
Therefore, by PCI, every natural number greater than or equal to $11$ can be written in the form $2s +5t$, for some natural numbers $s$ and $t$.

A: In some problems, the truth of the $(k+1)$-st case can require that more than just the $k$th case be true (maybe all cases, $1$ through $k$ are required). In these cases, strong induction, or a variant thereof is required (so that you have the relevant preceding cases true in order to complete the inductive step).
All proofs by induction are made up of two key parts: The base case, and the inductive step.
In the inductive step, you assume the truth of the $k$th case (or in the strong variant, all cases up to $k$) and use that to prove that the $(k+1)$-st case holds. What you establish in this step is the implication:
Previous case(s) $\Rightarrow$ Next case
This, of course, is a conditional statement, and hence, does not, on it's own, suffice to prove the original proposition (that it's true for all cases). This is what the base case does. It 'starts the dominoes falling'.
With the base case proven, then you get a chain of implications:
Base case $\Rightarrow$ 2nd case
With base case true, therefore 2nd case is true
2nd case (and base case in strong version) $\Rightarrow$ 3rd case
etc.
thus all cases in the chain are true (this is the dominoes falling part of the induction).


text:
Q: Powershell: Check csv file values against every line in another csv file I have 2 .csv files.
Examples:
1.csv:
Users
userA
userB

2.csv:
groupid,user,random
1,userA,randomtext1
2,userA,randomtest2
3,userA,randomtext3
3,userB,randomtext1
5,userB,randomtext2
6,userB,randomtext2

I want to take the value of the one column in 1.csv and check it against a column in 2.csv.
Basically what output I would like is:
UserA is a member of 1
UserA is a member of 2
UserA is a member of 3
UserB is a member of 3
UserB is a member of 4
UserB is a member of 5
UserB is a member of 6

I know I can use Import-Csv but I just can't get around how to do this?
I have tried to put 1.csv into an array but how can i then check the array against every line in 2.csv to check if the user is on a given line and then take the groupip?
$user = @()
$users = Import-Csv 1.csv | Foreach {$user += $_.Users}

I have tried a lot of different things and i cant get it to work.
Any tips appreciated.
/Rasmus

A: Read the usernames you're interested in into an array, use Where-Object to filter on rows that match those user names:
# Read user names into string array
$TargetUsers = Import-Csv .\1.csv |Select-Object -ExpandProperty Users

# Now import and filter the CSV with the relationships
Import-Csv .\2.csv |Where-Object {$TargetUsers -contain $_.user} |ForEach-Object {
    # Output the string with the information you need
    "$($_.user) is a member of $($_.groupid)"
} |Out-File .\output.txt


text:
Q: Oracle SQL Find First Match from single table I have a table that lists concurrent program IDs and names. However, the table allows more than one name for each program ID. I'm needing to report some data about the programs, but am having trouble getting it to display correctly, as the program name is what is being displayed and grouped by in Tableau.
So what I need is a way to pull the first name for each program ID from the table. Since I'm including the program name in my output, I can't use unique (it wouldn't filter the alternate names) & I can't use a join as there wouldn't be a unique match.

A: Several options (of varying efficiency) to get the (alphabetically) first name for each id.
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE PROGRAMS ( ID, NAME ) AS
          SELECT 1, 'Charlie' FROM DUAL
UNION ALL SELECT 1, 'Bob'     FROM DUAL
UNION ALL SELECT 1, 'Alice'   FROM DUAL
UNION ALL SELECT 2, 'Ed'      FROM DUAL
UNION ALL SELECT 2, 'Doris'   FROM DUAL
UNION ALL SELECT 3, 'Fern'    FROM DUAL
UNION ALL SELECT 3, 'Godfrey' FROM DUAL;

Query 1:
SELECT ID,
       MIN( NAME ) AS NAME
FROM   PROGRAMS
GROUP BY ID
ORDER BY ID

Results:
| ID |  NAME |
|----|-------|
|  1 | Alice |
|  2 | Doris |
|  3 |  Fern |

Query 2:
SELECT DISTINCT
       ID,
       FIRST_VALUE( NAME ) OVER ( PARTITION BY ID ORDER BY NULL ) AS NAME
FROM   PROGRAMS
ORDER BY ID

Results:
| ID |  NAME |
|----|-------|
|  1 | Alice |
|  2 | Doris |
|  3 |  Fern |

Query 3:
SELECT ID,
       NAME
FROM   PROGRAMS p
WHERE  NOT EXISTS ( SELECT 'X'
                    FROM   PROGRAMS x
                    WHERE  p.ID = x.ID
                    AND    p.NAME > x.NAME )
ORDER BY ID

Results:
| ID |  NAME |
|----|-------|
|  1 | Alice |
|  2 | Doris |
|  3 |  Fern |


text:
Q: BC30456: CultureInfo is not a member of Globalization I started getting the following error on an ASPX project in VS2015, suddenly out of the blue, seemingly after Windows 10 installed Feature update to Windows 10, version 1607:

BC30456: 'CultureInfo' is not a member of 'Globalization'.

This is occurring in a server-side code file that had no problem before. I use git to track changes, and the only thing that changed in the whole project was moving a comment from one place to another (I even tried undoing the change). Aside from that, this is my first time opening the project since Windows installed the version 1607 update, if that has anything to do with it. Specifically, I was using the project the previous day.
I found this post, which suggests adding a reference to System.Globalization for the project. I tried adding a reference to System.Globalization specifically, but there was no such entry to be found. I then tried adding a reference to mscorlib (both via the listed entry and via file browse), and it said mscorlib was already referenced. Also, in the source code the line using Globalization.CultureInfo appears just fine without any red markings. Mousing over shows information for the components, and Go to definition browses to a place in mscorlib where the CultureInfo class is defined.
The problem is when selecting View in Browser. This is a non-compiled project (no bin), although I did try Rebuild Solution, which made no difference in the error condition. I uploaded the code file in this exact state to the server, and it runs just fine on the actual server.
Update 1: I tried adding a reference in Web.Config as follows, but this did not resolve the issue:

<compilation>
  <assemblies>
    <add assembly="System.Globalization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
  </assemblies>
</compilation>

A: Although I cannot say exactly what was being referenced instead, apparently when I said Globalization.CultureInfo it was referencing a different "Globalization". Simply adding System to the front made the error go away. This is very peculiar. I tried searching the solution for Globalization, but nothing else came up. I have no idea why this started at this point since nothing in the project had changed, since the actual server does not require System to be prefixed, and since mouse-over info does not seem to care. Again, the solution is as follows:

System.Globalization.CultureInfo... // Try including "System." at the front.

A: On your code, you need to change this:
Globalization.DateTimeStyles
For this:
System.Globalization.DateTimeStyles
Hope this helps

A: I had a similar issue. The compiler was getting the error:
BC30456: 'DateTimeStyles' is not a member of 'Globalization'.
I just installed Windows 10 and using Visual Studio 2013. The OS installed an update and now is running the .Net Framework release: 4.6.1586.0.
Your solution solved my problem:
including System before globalization:
System.Globalization.DateTimeStyles

The strange thing is that before the upgrade to Win10 + .Net 4.6, I was using the same code without the need of specifing "System.".


text:
Q: Adding tasks to crontab does not work in docker container for image python:3.9.16-slim I'm creating a container for a Django website. I need a dump DB every two weeks and sent to Google mail as a backup.
To do this, I want to add two tasks to the crontab in the container where Django works, one will create a database dump, the other will archive it and send it to the mail.
But I faced with a problem.
I wrote the following in the Dockerfile:
RUN apt update && apt install -y cron
# Copy crontab2.txt file to the cron.d directory
COPY crontab2.txt /etc/cron.d/new_cron
# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/new_cron
# Apply cron job
RUN crontab /etc/cron.d/new_cron
# Create the log file to be able to run tail
RUN touch /var/log/cron.log
# Run the command on container startup
CMD ["cron", "-f"]

In the process of creating the container, I received the following log:
Step 4/27 : RUN apt update         && apt install -y cron
 ---> Running in 715c47ebdac4
...
The following NEW packages will be installed:
  ... cron
...
Get:2 http://deb.debian.org/debian bullseye/main amd64 cron amd64 3.0pl1-137 [99.6 kB]
...
Selecting previously unselected package cron.
Preparing to unpack .../1-cron_3.0pl1-137_amd64.deb ...
Unpacking cron (3.0pl1-137) ...
...
Setting up cron (3.0pl1-137) ...
...
Step 5/27 : COPY crontab2.txt /etc/cron.d/new_cron
 ---> acaadc156021
Step 6/27 : RUN chmod 0644 /etc/cron.d/new_cron
 ---> Running in aa8927eb26e0
Removing intermediate container aa8927eb26e0
 ---> 92631910ee2f
Step 7/27 : RUN crontab /etc/cron.d/new_cron
 ---> Running in fd439a3f2015
Removing intermediate container fd439a3f2015
 ---> a40708d2ce63
Step 8/27 : RUN touch /var/log/cron.log
 ---> Running in 0455e9efde80
Removing intermediate container 0455e9efde80
 ---> 889579d1a1fc
Step 9/27 : CMD ["cron", "-f"]
 ---> Running in f1889d79d147
Removing intermediate container f1889d79d147
 ---> af5b9b0f75ef
...

But after that, the tasks from the crontab2.txt file does not work, and when I try to execute in the image shell
crontab /etc/cron.d/new_cron

In response, I get : there is no such file.
What could be the matter and how to fix it?
Well, if there is an easier way to send a database backup to the mail for Django, I will also be grateful.


text:
Q: Delimited string to access assoc array I want to access an assoc array by using a delimited string.
Configuration::get('enviroment/database/default');
Below is what I have, and works, but it's far from perfect.
public static function get($key) {
    $array = explode('/', $key);
    switch(count($array)) {
        case 1:
            $value = self::$cfg[$array[0]];
            break;
        case 2:
            $value = self::$cfg[$array[0]][$array[1]];
            break;
        case 3:
            $value = self::$cfg[$array[0]][$array[1]][$array[2]];
            break;
    }
    return $value;
}

How can I clean up this function and remove the hardcoded 'depth' limit?

A: public static function get($path) {
    $result = self::$cfg;

    foreach (explode('/', $path) as $key) {
        if (!array_key_exists($key, $result)) {
            throw new InvalidArgumentException("Path $path is invalid");
        }
        $result = $result[$key];
    }

    return $result;
}

BTW, using a static class is not usually a good idea, you should instantiate it. See How Not To Kill Your Testability Using Statics.

A: You can just use a foreach() loop, and then assign that value to the key of a variable that will hold self::$cfg:
$confArr = self::$cfg;

foreach(explode('/', $key) as $cfg)
{
    $confArr = $confArr[$cfg];
}

return $confArr;

It might be wise to add in some error checking to make the key exists within self::$cfg, mind you.


text:
Q: A={$i+1 | i \in N \varphi_i(1393)=2015 $} is Recursive? I see that my prof. wrote:
A={$i+1 | i \in N \varphi_i(1393)=2015 $} is Recursive, but B={$n^2 + n | n \in N \varphi_n(n)= \uparrow $ } is not an r.e set.
Who can learn me, about this two example?

A: Neither are recursive, by Rice's theorem: They are both equivalent to a non-trivial index set.
$A$ is r.e. because you can check whether $i+1 \in A$ by just running $\varphi_i(1393)$, wait for it to halt, and if it does check whether its output is $2015$.
$B$ is not r.e. because it's complement is r.e. and $B$ is not recursive. We can check whether $n \notin B$ by checking whether it is of the form $m^2 + m$, if it is not, we know $n\notin B$, and, if it is, run $\varphi_n(n)$ and wait for it to halt. If it does, we know $n\notin B$. This procedure correctly determines $n\notin B$ so $B^c$ is r.e.


text:
Q: Computed array values in C# - reactive programming Example 1
As we know there's the concept of computed columns in databases where a column is computed based on adjacent columns' values.
The problem is that computed columns can't relate to other rows than current.
Example 2
Then we have spreadsheets (ie. Excel) where a cell can have a formula. This is similar to computed column, but more powerful. A formula can be related to any cell (or set of them) in the spreadsheet and not just current row/column as in RDB.
The problem
The concept of computed (or auto-updated values) is great but how can I do something similar in a set of values/objects in C#?
I would like to create a list (or array) of values where each of them is related to some other (or set of) value in the same list? It's like spreadsheet cell values... Change a value and related ones change along (and the whole related subtree values as well).
Is there a concept like that in C#?
How am I about to do this in the most clever way? I know I could have a LinkedList of objects where object's properties' values would relate to other objects in the same list and get evaluated whenever value gets accessed (evaluation on demand). This may mean that several (all ancestor nodes) get evaluated along the way. Is there a better way that would work more like spreadsheet cells where they get evaluated first and then accessed individually (propagated evaluation)?
This should of course be applicable to multidimensional arrays as well.

A: This concept is called Reactive Programming. .NET has something called Reactive Extensions that would allow you to achieve what you have described. Specifically you need to use something called Behavior

A: You could create an object with an indexer property which would contain your computation:
class Foo {
    public int this[int index] {
        get {
            return index*2; //Your computation here
        }
    }
}

or
class Foo {
    public int this[int row,int col] {
        get {
            return row*col; //Your computation here
        }
    }
}

Alternatively, if you want to use a linked list or somesuch, you could store "Cell" objects in the list structure and have a property or method on those "Cell" objects to perform the calculations:
class Cell {
    private int _row;
    private int _col;

    public Cell(int row,int col) {
        _row = row;
        _col = col;
    }

    public int Value {
        get {
            return _row * _col;
        }
    }
}

A: You can create your own array class that takes functions instead of values:
class ComputedArray<T>
{
    private Func<T>[] _array;

    public T this[int index] { get { return _array[index]( ); } }

    public void Set(int index, Func<T> func)
    {
        _array[index] = func;
    }

    public ComputedArray( int size )
    {
        _array = new Func<T>[size];
    }
}

Now you can store values using lambda expressions:
ComputedArray<int> ar = new ComputedArray<int>( 2 );
ar.Set( 0, ( ) => 2 );
ar.Set( 1, ( ) => ar[0]*2 );
Console.WriteLine( ar[0] );
Console.WriteLine( ar[1] );

A: This is perfect for OO languages as the way references work. At an abstract level I would handle this as such:
Create an abstract class, Expression, that will be the base type for all values in our program. Something like:
public abstract class Expression
{
    List<Expression> linkedExpressions;
    protected Expression lhs; // left hand side, right hand side
    protected Expression rhs;

    protected Expression(Expression x, Expression y)
    {
        List<Expression> linkedExpressions = new List<Expression>();
        lhs = x;
        rhs = y;
        // let the expressions know that they have a expression dependant on them
        lhs.NotifyExpressionLinked(this);
        rhs.NotifyExpressionLinked(this);
    }

    private void NotifyExpressionLinked(Expression e)
    {
        if (e != null)
        {
            linkedExpressions.Add(e);
        }
    }

    private void NotifyExpressionUnlinked(Expression e)
    {
        if (linkedExpressions.Contains(e)
        {
            linkedExpressions.Remove(e);
        }
    }

    // this method will notify all subscribed expressions that
    // one of the values they are dependant on has changed
    private void NotifyExpressionChanged()
    {
        if (linkedExpressions.Count != 0) // if we're not a leaf node
        {
            foreach (Expression e in linkedExpressions)
            {
                e.NotifyExpressionChanged();
            }
        }
        else Evaluate()
        // once we're at a point where there are no dependant expressions
        // to notify we can start evaluating
    }

    // if we only want to update the lhs, y will be null, and vice versa
    public sealed void UpdateValues(Expression x, Expression y)
    {
        if (x != null)
        {
            lhs.NotifyExpressionUnlinked(this);
            x.NotifyExpressionLinked(this);
            lhs = x;
        }

        if (y != null)
        {
            rhs.NotifyExpressionUnlinked(this);
            y.NotifyExpressionLinked(this);
            rhs = y;
        }

        NotifyExpressionChanged();
    }

    public virtual float Evaluate()
    {
        throw new NotImplementedException(); // we expect child classes to implement this
    }
}

Create a class for each of the types of expressions we will need. At the very bottom you will have a LiteralExpression, which is just a number:
public class LiteralExpression : Expression
{
    private float value;

    public LiteralExpression(float x)
        : base(null, null) { } // should not have any linked expressions

    public override float Evaluate()
    {
        return value;
    }
}

One thing to note about this class - because of the way it works, UpdateValue()  shouldn't be used on it. Instead, just create a new LiteralExpression to replace it.
Then, you need to build child classes for all expressions you will want (for example, here is addition):
public class AdditionExpression : Expression
{
    public AdditionExpression(Expression x, Expression y)
        : base(x, y) { };

    public override float Evaluate()
    {
        return lhs.Evaluate() + rhs.Evaluate();
    }
}

Not how this is all the code we have to write for each expression - all the heavy lifting is handled by the abstract class. There are a few design flaws in this program - it won't detect circular references, and it won't stop you from passing null values to expressions (which in the case of LiteralExpression is required), but those problems shouldn't be too hard to fix.
Then, all that needs to be done is to implement all of the child classes that inherit from expression.
There may be better methods to doing this, but from an OO viewpoint this is a nice example of making an generic abstract class that implements common behaviours and having a lot of small, specific implementations for each 'flavour' of that class.


text:
Q: Can I manually feed the language code to Django gettext()? I have a few strings in the backend I'd need to occasionally translate to other language before using them. I plan to save the user language selection into the database so it would be easy to get it from there. But, what is unclear for me, is if I implement localization and have a couple of different language files, how can I use the right language version? I can't read the language selection from cookies, url, user session etc. Can I use the language code from my database to choose which translation I'll use?

A: You can manually activate the language with activate. Here's an example, given the user has an language attribute with a valid language code:
from django.utils.translation import activate, deactivate
from django.utils.translation import gettext as _

user = MyUserModel.objects.get(username=username)
activate(user.language)
my_string_translated_into_users_language = _("Hello")
deactivate()

That way, you override the current session language. Then deactivate() will deactivate the currently active translation object so that further _ calls will resolve against the default translation object, again.


text:
Q: Java runtime illegastateexception. specified child has already a parent I am trying to play a video from the gallery. On button click it should start playing video in the videoView. But i get exception that spcified child already has parent. Following is my code:
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button bt= (Button) findViewById(R.id.button1);
    final String filename = "/sdcard/myvideo.mp4";
    Log.e("Video Error", "Problem Below");
     final VideoView videoView1 = (VideoView)findViewById(R.id.videoview);
        Log.e("Video Error", "Problem Above");
     setContentView(videoView1);
     videoView1.setVideoPath(filename);
    // videoView1.setMediaController(MainActivity.this);
     videoView1.requestFocus();
     bt.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
              //String fileName = "android.resource://" + getPackageName() + "/" + R.raw.sample;

                Toast.makeText(getApplicationContext(), "Hey Baby", 5000);
              //videoView1.start();
              //Exit after saved
             // finish();

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
}

when i try to initialize my VideoView it gives the following exception:
:12:11.838: E/AndroidRuntime(1124): FATAL EXCEPTION: main
03-12 19:12:11.838: E/AndroidRuntime(1124): java.lang.RuntimeException: Unable to start      activity ComponentInfo{com.et.getimages/com.et.getimages.MainActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

please help.

A: I suspect it'd because you're calling setContentView() twice. The first time creates the VideoView and then when setContentView(videoView1);
Without the full stacktrace it's impossible to tell however.
p.s. you'll want to add show() to your toast to make it display

A: You set content view in this statement:
setContentView(R.layout.activity_main);
then you take from view defined in layout/activity_main.xml another view:
(VideoView)findViewById(R.id.videoview);
which is actaually  child of layout/activity_main.xml
and then you again try to set content view:
setContentView(videoView1);
but videoView1 already has parent because it is part of layout/activity_main.xml so you cannot use this view in setContentView() as this method is setting up root for view given in parameter.


text:
Q: Constant Sum Voltage Divider With Thermistor/Temp Sensor I need a circuit with a thermistor/temp sensor that will essentially emulate a pot.  In other words, I need a voltage divider that varies with the resistance of the thermistor/sensor, but keeps the sum of R1 and R2 constant.  (Used to vary duty cycle with 555 timer PWM circuit.
I have a 10k thermistor, a tmp36 (though my supply voltage is 12, so that probably won't work) and an ad592, so if one of those worked it would be great.

A: If you don't care too much about the PWM frequency changing when the thermistor changes its resistance with temperature you can just use a fixed resistor for one side of the pot and the thermistor for the other side of the pot - I believe I know the circuit: -

To the left of the wiper, replace with a small value of resistance such as 100 ohms. To the right of the wiper connect your thermistor but, be aware - double check this - I may have the placement back to front. If the fan motor gets faster as the wiper moves to the right then it's OK!
By the way - lose the 470uF capacitor and definitely have a decent diode across the motor.


text:
Q: Filter geom_text value labels in a stacked bar chart I want to create a stacked bar chart with ggplot, and add (centered) labels to it: when values are too low, I don't want to show the label.
df<-data.frame(x=unlist(strsplit("AAAABBBB","")),
           z=unlist(strsplit("ABCDABCD","")),
           y=c(40,5,30,10,50,60,5, 40))

# this works fine
library(ggplot2)
ggplot(df, aes(x=x, y=y, fill = z)) + geom_bar(stat="identity") +
   geom_text(data  = df, aes(x=x, y=y, label = y), position = position_stack(vjust=0.5))

But when I filter the values like this (see below), it also changes the positioning for each label. This works fine for a scatterplot, but since the positioning is based on the stacked values, the labels are shown too low.
#don't show values 5 or less
ggplot(df, aes(x=x, y=y, fill = z)) + geom_bar(stat="identity") +
    geom_text(data = df[df$y > 5,], aes(x=x, y=y, label = y), position =
    position_stack(vjust=0.5))

A: We can create a column 'y1' with value that are less than or equal to 5 as blank ("") and use that in the label argument
df %>%
     mutate(y1 = replace(y, y<=5, ""))

p2 <- ggplot(df, aes(x=x, y=y, fill = z)) +
         geom_bar(stat="identity") +
         geom_text(data  = df, aes(x=x, y=y, label = y1),
                  position = position_stack(vjust=0.5))
p2

Checking for the position by comparing with the first plot from the OP's post
p1 <- ggplot(df, aes(x=x, y=y, fill = z)) +
                  geom_bar(stat="identity") +
                  geom_text(data  = df, aes(x=x, y=y, label = y),
                      position = position_stack(vjust=0.5))

library(ggpubr)
ggarrange(p1, p2, ncol =2, nrow = 1, labels = c("p1", "p2"))


text:
Q: Git doesn't show history using symbolic link I have created file and symbolic link to file in my git repository.
symfile1 --> file1
When I change file1, I can see history of change by
git log file1,
but I don't see the same history when I do
git log symfile1
Is there any way to see history change of real file, using git log to it's symbolic link?
The questions is related only history can I see the history change of file1 using symbolik1 ?

A: No. The symbolic link has not changed at all, it still points to the same destination. Neither can git tell you, not should it. If I would see git flagging a change on a symbolic link, the only if the link were now pointing to a different file name. Symbolic links generally are only concerned with file names, not file contents.
That said, you can create a short bash script which does that. Then you can create a git alias for it -scm.com/book/tr/v2/G . The script can use standard bash features to find the link target and then call the proper git command you want.

A: Just to add..
GIT treats a symbolic link the same as it does any file, but it stores the contents of the link it relates to.  What it doesn't do, is follow the link and then consider the target.  In fact, it has no clue about the target other than the value of the link that it contains.
when you checkout, GIT will recreate that symbolic link, with its original file path, but it wont consider the target file at all (unless thats also in version control, but it will be tracked independently of the symlink).
Think of it as a shortcut on the desktop, which is a file.  Put that into version control and it'll track the shortcut, not the thing it points to.


text:
Q: Errors in a log file in eclipse Please see my previous question:
Eclipse is not working after download
I deleted the config folder, and when I pressed the eclipse is a new create a new and different problem:
On the log file appears the problem this way:
!ENTRY org.eclipse.osgi 4 0 2012-12-17 10:27:25.247
!MESSAGE Application error
!STACK 1
java.lang.IllegalStateException: Unable to acquire application service. Ensure that the org.eclipse.core.runtime bundle is resolved and started (see config.ini).
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:74)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1438)

What is this problem?

A: Finally I solved the problem:
I added to the config file the location of the JVM.
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120522-1813
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vm
C:\Program Files\Java\jdk1.7.0_07\bin\javaw.exe
-vmargs
-Xms40m
-Xmx512m

Thank you all for the help

A: Try adding this to the end of you config.ini file.
Dosgi.bundles=org.eclipse.equinox.common@2:start,org.eclipse.update.configurator@3:start,org.eclipse.core.runtime@

Edit:
Further reference right here.


text:
Q: Consolidating columns by the number before the decimal point in the column name I have the following dataframe (three example columns below):
import pandas as pd
array = {'25.2': [False, True, False], '25.4': [False, False, True], '27.78': [True, False, True]}
df = pd.DataFrame(array)

    25.2    25.4    27.78
0   False   False   True
1   True    False   False
2   False   True    True

I want to create a new dataframe with consolidated columns names, i.e. add 25.2 and 25.4 into 25 new column. If one of the values in the separate columns is True then the value in the new column is True.
Expected output:
      25     27
0   False   True
1   True    False
2   True    True

Any ideas?

A: use rename()+groupby()+sum():
df=(df.rename(columns=lambda x:x.split('.')[0])
      .groupby(axis=1,level=0).sum().astype(bool))

OR
In 2 steps:
df.columns=[x.split('.')[0] for x in df]
#OR
#df.columns=df.columns.str.replace(r'\.\d+','',regex=True)
df=df.groupby(axis=1,level=0).sum().astype(bool)

output:
    25      27
0   False   True
1   True    False
2   True    True

Note: If you have int columns then you can use round() instead of split()

A: Another way:
>>> df.T.groupby(np.floor(df.columns.astype(float))).sum().astype(bool).T

    25.0   27.0
0  False   True
1   True  False
2   True   True


text:
Q: Thread first job first python #threads
lock = threading.Lock()
t1 = threading.Thread(target=job1, args = (lock, )).start()
t2 = threading.Thread(target=job2, args = (lock, )).start()

I am having two threads which are for job1 and job2 respectively.
Both are scheduled at the same time initially.
Job1 and Job2 are rescheduled at a interval of 10 seconds and 60 seconds respectively (recursively) .
But some time job1 runs first and some times job2 runs first. This happens after every seconds.

I want somehow job1 should be executed before job2.
so is there a solution?
The time taken by job1 is around less than a second
Where as job2 needs around  4 to 5 seconds to complete the task.


text:
Q: How do you edit a file in the node_modules folder on Heroku? Locally I needed to fix a bug in an npm package, but when uploading the server to heroku, the npm gets reinstalled and my fix is of course gone. Is there a way to edit the file inside the node_modules folder inside heroku?

A: You should use patch-package package for that
https://www.npmjs.com/package/patch-package


text:
Q: Does a black hole evaporate by the time an observer reaches the singularity? Assume you are an invincible observer who falls into a blackhole...
Your time runs slower than the universe outside, as you get closer and closer to the singularity, the ratio between your time and the time of the universe outside the blackhole increases exponentially.
Ergo, you will see the universe in a very rapid "fast-forward" (ignore the fact that you'll get fried by the immense amount of radiation that accumulates due to the time dilation).
Does this also not mean that the event horizon is aging much faster than you, and thus evaporating, and as you get closer and closer to the singularity, it evaporates more and more per second, according to you and at some point it will catch up to you?
Also by the time you reach infinitesimally close to the singularity, the universe outside has experienced such a long time, that the heat death or the big crunch has happened, in which case the black hole is also gone?
TLDR; As you approach the singularity, the event horizon will start moving towards you as it shrinks, at some point it will catch up right?


text:
Q: What is it and from where it is loaded? I am new at wordpress. I found a hook in theme back-combat.php file which is prevents to load previous version of wordpress for current theme customization. such as
add_action('load-customize.php', 'my_function_name');

My question is what is this hook and from where it is loaded because load-customize.php
and which way I can learn quick about wordpress core and learning plugin development?

A: This is from a dynamic hook that's generated in the wp-admin/admin.php file and fires right after the admin_init action.
Here's the inline documentation for the core screens part:
/**
 * Fires before a particular screen is loaded.
 *
 * The load-* hook fires in a number of contexts. This hook is for core screens.
 *
 * The dynamic portion of the hook name, `$pagenow`, is a global variable
 * referring to the filename of the current page, such as 'admin.php',
 * 'post-new.php' etc. A complete hook for the latter would be
 * 'load-post-new.php'.
 *
 * @since 2.1.0
 */
 do_action( "load-{$pagenow}" );

When we visit /wp-admin/customize.php the generated action is load-customize.php.
We can then e.g. check if it has already been fired with:
did_action( 'load-customize.php' );

that returns the number of times it has fired so far, during the page load.
Check the code reference for more info on did_action().
Another example is the wp-admin/edit.php and the corresponding load-edit.php action.


text:
Q: Need dotnet regex to replace an underscore (_) with 0% We have a card being scanned in which has ZZZZ_ss16 printed on the card and scans as ZZZZ0%ss16. The users are initially registering the cards with the wrong number due to the misprint. Card reprint would be great but isn't an option.
I have a javascript regex which should do the job but am having trouble translating this to work with dotnet.
s/^(\w{4}).(\w{4})/\10%\1/

We just need the first 4 characters, replace _ with 0%, followed by the last 4 characters.
Hope someone can assist.

A: In this case you can use
^(\w{4})_(\w{4})$

and replace with $10%$2
Regex Demo
For .net use this
var pattern = "^([A-Za-z0-9_]{4})_([A-Za-z0-9_]{4})$";
var template = "ZZZZ_ss16";
var replaceWith = "${1}0%$2";

Ideone Demo

A: You can create a regex that will capture the first four characters into capture group 1 and the last 4 characters into capture group 2, and then perform a replace to output group 1, followed by 0%, followed by group 2.
var pattern = new Regex(@"^(\w{4})_(\w{4})$");
var input = "ZZZZ_ss16";
var output = pattern.Replace(input, "${1}0%$2");
// RESULT: ZZZZ0%ss16

Demo
It is necessary to escape the digit after the $, otherwise it will get interpreted as the 10th capture group. Recommended reading: https://msdn.microsoft.com/en-us/library/ewy2t5e0%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396


text:
Q: JavaScript radio onclick processed before UI reflects selection I have the following JavaScript code:
var radios = form.elements["option_filter"];
for (var i = 0, max = radios.length; i < max; i++) {
    if (typeof (radios[i].value) !== 'undefined') {
        radios[i].onclick = function () {
            var l = this.nextElementSibling.innerText;
            <code to create a path containing selection>
            window.location.replace(dest);
        }
    }
}

which works fine, except that when a radio is clicked, the selection is considered checked in code, but that is not reflected in the UI ... the radio button remains blank as the redirect is processed.
I tried having it sleep a bit between the onclick firing and the redirect, to no avail.
How do I get the UI to reflect the selection change so that the user sees it selected while waiting for the new page to load?

A: To get the UI to reflect... you'll need to set the value of the target radio button to a value...
radio[i].value = "whatever"

Also remember that the value set must match the name of one of the radio buttons in your options...


text:
Q: How to make subset or powerSet quickly and efficiently in java from a list? I'm going through a problem of making subsets or powersets from an arrayList with may be 70 or 80 or more String elements and then further process those subsets(or powersets). For example I have some arrayLists which have non duplicate strings as element like the following (strings actually have more than one characters):
List<String> list = new ArrayList<>();
list.add("a");
list.add("c");
list.add("g");
list.add("n");
list.add("f");
and so on...

Then I need to get the subsets(or powersets) contains the 1st element. for example:{a,g}, {a,b}, {a,n,f}, {a,g,n,f}....
I've done the job by getting the powersets for the list elements except the first one and then adding the fist element with those subsets. But this works for few elements like 7 or 8 but could not work if the list grows. Is it required to do a powerSet algorithm like I'm doing for this job? If not then how can I get the expected results. And there have been a matter of memory-leak I think. As I need to store those results for some further processing.
I've done the job by following some of the suggestions regarding to the following links:
Obtaining a powerset of a set in Java
Calculating all of the subsets of a set of numbers
how to make all possible power set(or subset) from arrayList objects?
But those takes many hours for large list and could not get results at last because my netbeans IDE get hanged!
I need some suggestions or sample code related to this scenario.
Thanks!

A: Since the cardinality of a power set is 2^n where n is the number of elements in the beginning set I'd say that you are not going to compute a set of 2^70 elements.
My suggestion is to build elements of the power set on the fly and process them as you go, so you don't need to store all of them anywere.


text:
Q: Why is constraint optimization referred to as "X programming"? In many cases, constraint optimization will be referred to as some sort of "programming" like linear programming or quadratic programming. Why is this?

A: This doesn't have to do with computer programs. The word "programming" is used in the sense of "planning" -- think of the program for a party or event, for example.
Some of the earliest motivating examples for optimization theory were about moving (military) supplies between producers and users, through warehouses and vehicles of limited capacity. The outcome of solving the problem was a concrete program for how stuff would be moved around, which trucks to send where at which time, etc.


text: Q: CallContext в .Net 6.0 Core — как обмениваться данными между разными инстансами одного приложения не через файловую систему? Есть приложение написаное на WPF. Возникла необходимость обмениваться данными между разными инстансами этого приложения. Сразу вспомнил про System.Runtime.Remoting.Messaging.CallContext, но приложение написано на .Net 6.0 Core. Не хотелось бы для этого использовать файловую систему в т.ч. Settings файлы. Как лучше сделать?


text:
Q: Error utilizando Laravel estoy trabajando en un proyecto con Laravel y esta función me da un error. Lo que quiero obtener es el nombre del formador que da el curso.
{{ $course->owner->specialization->getName() }}

El error que aparece es el siguiente:

Relationship method must return an object of type
  Illuminate\Database\Eloquent\Relations\Relation

Y así están definidas las funciones en las clases:
Dentro de la clase Courses
public function owner()
    {
        return $this->belongsTo('App\User', 'user_id', 'id')->getResults();
    }

Dentro de la clase User
public function specialization()
    {
        if($this->isTrainer()) return $this->trainer();
        if($this->isCenter()) return $this->center();
        return null;
    }
private function trainer()
    {
        return $this->hasOne('App\Trainer');
    }

Dentro de la clase Trainer
public function getName()
    {
        $name = '';
        if(!empty($this->name)) {
            $name .= $this->name;
        }
        if(!empty($this->last_name)) {
            $name .= ' ' . $this->last_name;
        }
        if(!empty($this->second_name)) {
            $name .= ' ' . $this->second_name;
        }

        return $name;
    }

A: Para resolver tu problema de la forma más sencilla deberías utilizar los "accessors" de Laravel, para poder acceder de forma más natural semánticamente hablando:
En tu clase trainer, para obtener el nombre el accessor sería algo así:
public function getFullNameAttribute()
{
    // código de la función getName()
}

De esta forma puedes usarlo así en la vista:
{{ $course->owner->specialization->full_name }}

Puedes ver más información en la documentación: https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor

Pequeño punto aparte, y aunque no entiendo muy bien la lógica de tu aplicación y desconozco la razón por la que lo haces, podrías mejorar el código o la forma como haces el proceso en el método specialization(), así como la lógica con la que generas el nombre completo.

A: Veo que la función specialization() puede devolver valores nulos, entonces en la vista si llamas $course->owner->specialization->getName() te va a dar error en esos casos.
Una opción sería verificar en la vista si el valor viene nulo:
@if (empty($course->owner->specialization))
     Sin nombre
@else
     {{ $course->owner->specialization->getName() }}
@endif


text:
Q: Number of digits code I have a problem asking me to tell the amount of digits in a given number. I inserted conditional statements, but no matter what number I insert, it gives me "nine" digits. The code is below. I'm a math student and not computer science, so I figure I'm not using the most efficient method.
import java.util.Scanner;

public class E52 {
    public static void main(String[] args) {
        // part 1: import scanner
        Scanner sc = new Scanner(System.in);

        // part 2: ask user for a number
        System.out.println("Please enter a number: ");
        int number = sc.nextInt();

        // part 3: tell how many digits are in each number by using string and conditional statements
        String number1Str;
        if (number >= 0 || number <= 10) number1Str = "one";
        if (number >= 10 || number <= 100) number1Str = "two";
        if (number >= 100 || number <= 1000) number1Str= "three";
        if (number >= 1000 || number <= 10000) number1Str = "four";
        if (number >= 10000 || number <= 100000) number1Str = "five";
        if (number >= 100000 || number <= 1000000) number1Str = "six";
        if (number >= 1000000 || number <= 10000000) number1Str = "seven";
        if (number >= 10000000 || number <= 100000000) number1Str = "eight";
        if (number >= 100000000 || number <= 1000000000) number1Str = "nine";
        else number1Str = "undefined";

        System.out.println("There are " + number1Str + " digits in the given number.");

        sc.close();
    }
}

A: It would be much easier to create an Array, then get the input's length and pick let it pick the entry:
Scanner sc = new Scanner(System.in);

// part 2: ask user for a number
System.out.println("Please enter a number: ");
Integer number = sc.nextInt();
final String[] numNames = {
            "",
            "one",
            "two",
            "three",
            "four",
            "five",
            "six",
            "seven",
            "eight",
            "nine",
            "ten",
            "eleven",
            "twelve",
            "thirteen",
            "fourteen",
            "fifteen",
            "sixteen",
            "seventeen",
            "eighteen",
            "nineteen"
    };
System.out.println(numNames[number.toString().length()]);

A: This will give you number count no matter how big or small number is. Although there are corner scenarios which may fail the code but i still feel this will be of use to you in some other way around
public class CountNum {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String numAsString = sc.nextLine();
        System.out.println(numAsString.length());
        sc.close();
    }

}