text:
Q: Looping through column names with dynamic SQL I just came up with an idea for a piece of code to show all the distinct values for each column, and count how many records for each. I want the code to loop through all columns.
Here's what I have so far... I'm new to SQL so bear with the noobness :)
Hard code:
  select [Sales Manager], count(*)
  from  [BT].[dbo].[test]
  group by [Sales Manager]
  order by 2 desc

Attempt at dynamic SQL:
Declare @sql varchar(max),
@column as varchar(255)

    set @column = '[Sales Manager]'
    set @sql = 'select ' + @column + ',count(*) from [BT].[dbo].[test] group by ' + @column + 'order by 2 desc'

    exec (@sql)

Both of these work fine. How can I make it loop through all columns? I don't mind if I have to hard code the column names and it works its way through subbing in each one for @column.
Does this make sense?
Thanks all!

A: This is a bit of an XY answer, but if you don't mind hardcoding the column names, I suggest you do just that, and avoid dynamic SQL - and the loop - entirely. Dynamic SQL is generally considered the last resort, opens you up to security issues (SQL injection attacks) if not careful, and can often be slower if queries and execution plans cannot be cached.
If you have a ton of column names you can write a quick piece of code or mail merge in Word to do the substitution for you.

However, as far as how to get column names, assuming this is SQL Server, you can use the following query:
SELECT c.name
FROM sys.columns c
WHERE c.object_id = OBJECT_ID('dbo.test')

Therefore, you can build your dynamic SQL from this query:
SELECT 'select '
    + QUOTENAME(c.name)
    + ',count(*) from [BT].[dbo].[test] group by '
    + QUOTENAME(c.name)
    + 'order by 2 desc'
FROM sys.columns c
WHERE c.object_id = OBJECT_ID('dbo.test')

and loop using a cursor.
Or compile the whole thing together into one batch and execute. Here we use the FOR XML PATH('') trick:
DECLARE @sql VARCHAR(MAX) = (
    SELECT ' select ' --note the extra space at the beginning
        + QUOTENAME(c.name)
        + ',count(*) from [BT].[dbo].[test] group by '
        + QUOTENAME(c.name)
        + 'order by 2 desc'
    FROM sys.columns c
    WHERE c.object_id = OBJECT_ID('dbo.test')
    FOR XML PATH('')
)

EXEC(@sql)

Note I am using the built-in QUOTENAME function to escape column names that need escaping.

A: You can use dynamic SQL and get all the column names for a table. Then build up the script:
Declare @sql varchar(max) = ''
declare @tablename as varchar(255) = 'test'

select @sql = @sql + 'select [' + c.name + '],count(*) as ''' + c.name +  ''' from [' + t.name + '] group by [' + c.name + '] order by 2 desc; '
from sys.columns c
inner join sys.tables t on c.object_id = t.object_id
where t.name = @tablename

EXEC (@sql)

Change @tablename to the name of your table (without the database or schema name).

A: You want to know the distinct coulmn values in all the columns of the table ? Just replace the table name Employee with your table name in the following code:
declare @SQL nvarchar(max)
set @SQL = ''
;with cols as (
select Table_Schema, Table_Name, Column_Name, Row_Number() over(partition by Table_Schema, Table_Name
order by ORDINAL_POSITION) as RowNum
from INFORMATION_SCHEMA.COLUMNS
)

select @SQL = @SQL + case when RowNum = 1 then '' else ' union all ' end
+ ' select ''' + Column_Name + ''' as Column_Name, count(distinct ' + quotename (Column_Name) + ' ) As DistinctCountValue,
count( '+ quotename (Column_Name) + ') as CountValue FROM ' + quotename (Table_Schema) + '.' + quotename (Table_Name)
from cols
where Table_Name = 'Employee' --print @SQL

execute (@SQL)


text:
Q: Build error when linking Boost for Quantlib I'm trying to do a first build of Quantlib, but I'm getting the fatal error "LNK1104: cannot open file 'libboost_unit_test_framework-vc120-mt-gd-1_56.lib'".  There's a reasonable amount of discussion on this in the forum but nothing has helped me yet.
I'm using Visual Studio 2013 on a Win 8.1 box.
I built Boost by: b2 --build-dir="C:\Program Files\Boost\boost_1_56_0\boostBuild" --build-type=complete msvc stage .  The demonstration Boost regex program works fine.
Then I opened the Quantlib_vc11 solution and added the Linker Additional Library Directories as described on the Quantlib installation page.  But the build fails with the error message above.
I'm new to C++ and to Visual Studio, and I'm sure it's my lack of understanding that is giving me this problem, but if someone can give me some pointers it would be great.  Thanks

A: Can you please check if the file is really in the directory you give to VS? The error means VS couldn't find the file, not because the file is corrupted or built incorrectly.
Furthermore, if you're uninterested to build the boost library yourself, you can simply download those *.lib files online. You don't have to run the boost build commands. There're lots of sites offering you those library files.

A: I have the same problem before but I used vs2012. Hope my experience can help.
In my case, I opened property manager(View->Other Windows->Property Manger),
dropped down to
QuantLib->Debug(static runtime) |Win32 ->Microsoft.Cpp.Win32.user.
Right click 'property' and go to VC++ Directories, then on the right hand side, open Library Directories and add your boost address ".../boost_1_xx/stage/lib" here.
'libboost_unit_test_framework-vc120-mt-gd-1_56.lib' is used for project "testsuite".

redpajama_set_name: RedPajamaStackExchange


text:
Q: source of executable file for command line What are the "sources" where command line in windows (xp in my instance) is looking for commands to execute? I mean I write for example "java" in command line and then it run java.exe which is found in some directory listed in sytem/evnironment property PATH (you can list or set it by "SET PATH" command). Is there any other source for this lookup? If yes - where? and how can I set it?
I am asking because I have case where the command doesn't seem to be in any of that PATH's directories and despite of this it run that command (from somewhere..).
Thank you a lot.

A: In addition to the PATH variable, specific app paths may be configured in the registry.
If you take a look at HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths, you can see how this is done.

A: According to MSDN documentation for CreateProcess that is in the end called to start application

*

*The directory from which the application loaded.

*The current directory for the parent process.

*The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory.

*The 16-bit Windows system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System.

*The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

*The directories that are listed in the PATH environment variable. Note that this function does not search the per-application path specified by the App Paths registry key. To include this per-application path in the search sequence, use the ShellExecute function.

Regarding point 6. documentation for ShellExecute function doesn't describe when App Paths key is processed.

A: The system's path.  echo %PATH% should show it, from memory.

A: I have found that I can set this path by going to My Computer Properties->Advanced->Environment Variables.


text:
Q: How to get absolute path on linux when running from another location I want to run a crontab which will run my file every hour at 0 minutes. I have the (sudo) crontab set up with a single command as follows:
0 * * * * /usr/bin/python3 /usr/folder/test.py

The crontab is running and as far as I can tell is correct, but my python file is not returning the absolute path when the file is run from another location.
What I need is a way to guarantee the absolute path of this text file when it is accessed from the root so that my crontab can run the file.
I've tried using both Path(filename).resolve(), and os.path.abspath(filename) but neither of them work.
import os
print(os.path.abspath("checklist.txt"))

python3 usr/folder/test.py

When I run the file "test.py" while within the folder, I get the expected output

python3 test.py
/usr/folder/checklist.txt

however when I run the same file from the root and access it via a path I get a different result, making using crontab impossible in this context

python3 usr/folder/test.py
/checklist.txt

A: If checklist.txt is in the same folder as your test.py script, then you can use the __file__ variable to get the right path. For example
# The directory that 'test.py' is stored
directory = os.path.dirname(os.path.abspath(__file__))
# The path to the 'checklist.txt'
checklist_path = os.path.join(directory, 'checklist.txt')

A: __file__ attribute
import os
filename = 'checklist.txt'
abs_path_to_file = os.path.join(os.path.dirname(__file__), filename)

sys module
import os, sys
filename = 'checklist.txt'
abs_path_to_file = os.path.join(os.path.dirname(sys.argv[0]), filename)


text:
Q: Trim() String After the word is done What I am trying to accomplish here is to trim the String after the word is finished. But also trying to stay efficient, and not use StringArray.length since some String are longer than 2k characters.
int len = 140;
String str = Html.fromHtml((cureent.getTextContent().replaceAll("\n",""))).toString();
char[] StringArray;
StringArray = str.toCharArray();
for(int Index=140;Index < 150;Index++) {
    Log.d("Current Letter",String.valueOf(StringArray[Index]));
    if (String.valueOf(StringArray[Index]).equals(" ")){
        Log.d("Found E at" + String.valueOf(Index) ,"The Value is " + String.valueOf(StringArray[Index]));
    }
    item.setDescription(Html.fromHtml(cureent.getTextContent()).toString().replaceAll("\n", "").trim().substring(0,Index).replace((char) 65532, (char) 32).trim());
}

E in my log Stands for Empty space
here is a bit of what the log returns.
2018-05-17 17:46:47.492 2616-2653/com.apo.rssredaer D/Found E at148: The Value is
2018-05-17 17:46:47.495 2616-2653/com.apo.rssredaer D/Found E at141: The Value is
2018-05-17 17:46:47.498 2616-2653/com.apo.rssredaer D/Found E at145: The Value is

But I cant get it to trim right after the word. I still get words trimmed in the middle or whatever position they are trimmed at
Example. lets say I have this string that I got from My rss.
And so, in honor of the antechinus' tragic death, we give you a small sampling of the for the example I'll use 14 instead of 140 as my counter, and I'll count from 0.
Trimming it will return to me:
"And so, in hon"
But whenever this is the case. I want it to keep going and trim it at
"And so, in honor"
hope I make some sense.

A: OK try this:
int position = 0; //create a pointer
        for (int index = 140; index < 150; index++) {
            if (str.charAt(index).equals(" ")) {
                position = index;
                break; //stop the loop when you find a space

            }
        }

//create a substring from 0 to Index
 item.setDescription(Html.fromHtml(str.substring(0, position));

A: Alternatively you could do this:
private String truncateTextMaxLength(String text, int maxLength){
    String result = text;
    int len = text.length();
    if(len < maxLength){
        return result;
    }

    int i = text.lastIndexOf(0, maxLength);
    result = text.substring(0, i);

    return result;
}

Now you can call just like this:
String s = truncateTextMaxLength(myText, 150);

.
Note that with the other code there could be the possibility that there is no " " between the 140th and 150th character.


text:
Q: Proving finite unions and arbitrary intersections of bounded sets are bounded I'm completely stumped on this proof. I know that $E \subset X$ is a bounded set if $\exists R \in \mathbb{R}$ s.t. $E \subset N_R (x) $. I also know that finite unions of closed sets are close, and that arbitrary intersections of closed sets are closed.
I do have a rough idea for the finite union case. I know a set is bounded it is bounded above and below. I know there's the least upper bound property, but I can't wrap my head around how I would prove that.
Any guidance would be much appreciated.

A: For the finite union case, we will show that if $E_1 \subseteq X$ and $E_2 \subseteq X$ are bounded, then so is $E_1 \cup E_2$. That finite unions of bounded sets is bounded then follows by induction.
Since $E_1$ is bounded, there is some $x_1 \in X$ and $r_1 \in \mathbb{R}^+$ such that $E \subseteq B(x_1, r_1)$. Since $E_2$ is bounded, wer know that there is some $x_2 \in X$ and $r_2 \in \mathbb{R}^+$ such that $E_2 \subseteq B(x_2, r_2)$.
Let $r = r_1 + r_2 + d(x_1, x_2)$. Then if for any $x \in E_1 \cup E_2$, we have that either $x \in E_1$ or $x \in E_2$. If $x \in E_1$, then we know that $d(x, x_1) < r_1 < r$. If $x \in E_2$, then we have that $d(x, x_1) \leq d(x, x_2) + d(x_2, x_1) < r_2 + d(x_1, x_2) < r$ by the triangle inequality. Thus we have that $x \in B(x_1, r)$.
We see that $E_1 \cup E_2 \subseteq B(x_1, r)$, and hence $E_1 \cup E_2$ is bounded.
For the arbitrary intersection case, suppose that $\{E_i\}_{i \in I}$ is an arbitrary non-empty family of bounded sets. Let $E$ be their intersection. Then for any $i \in I$, we have that $B_i$ is bounded, and hence there is $x \in X$ and $r \in \mathbb{R}^+$ such that $E_i \subseteq B(x, r)$. But $E \subseteq B_i \subseteq B(x, r)$, and hence $E$ is also bounded.
Essentially, if you pick any set out of those that you're taking the intersection of, the intersection will be contained in that set. Since that set is bounded by assumption, so is the intersection.

A: The intersection is contained in any of the bounded sets, so any of the bounds will work for the intersection.
If you have $N_{R_1}(x_1),...,N_{R_n}(x_n) $, can you find an $x,R$ such that
$N_{R_k}(x_k) \subset N_{R}(x)$ for all $k$?
Hint:

 Choose $x=x_1$ and $R = \max(R_1, d(x_1,x_2)+R_2,..., d(x_1,x_n)+R_n)$.


text:
Q: Joomla 3.2, get works, post doesn't So I have this JS code:
myClass = new Class({
  initialize: function() {
    this.btnSubmit = document.id('btnSubmit');
    this.sendData = new Request({
      "url":"/",
      "method":"post",
      "data": {"option":"com_my4quiz", "controller":"conduit", "task":"save", "hrdata":"foo"},
      "onSuccess": this.handleResult.bind(this)
    });

    this.btnSubmitObserver = function() { this.sendData.send(); }.bind(this);
    this.btnSubmit.addEvent("click", this.btnSubmitObserver);
  },

  handleResult: function(stuff) {
    //do stuff
  }
});

If I'm posting this to my Joomla 3.2.0 component it returns the home page.  As soon as I switch to get, it sends the data to the correct place and I get what I expect.

A: I think its due to your controller page loads the entire view.
This may happen due to inside your controller save(). function not rendering any specific view .
So the solution is after the Ajax result just render the proper layout or just put an exit();
At the end of your save()
exit();

or
$view->setLayout($layoutName);
$view->display();

Hope its helps..


text:
Q: Find unique items of a list in Google Apps Script (JavaScript) I am working with Google Sheets and I would like to get a list with the unique items of another list. Namely the input is:
List = ['Nick','George','George','Nick','Nick','George','Nick','Alex']
The output will be :
[Nick, George, Alex]
Right now I am using a simple loop to check whether an element appears more than once. But I am sure there is going to be a more clever way.

A: The simplest way is to use a Set. This is defined as a collection that cannot have duplicates
var noduplicates = new Set(List);

You can convert this back to a list if you wish.

var List = ['Nick', 'George', 'George', 'Nick', 'Nick', 'George', 'Nick', 'Alex']

var noduplicates = new Set(List)

noduplicates.forEach(x => console.log(x))

A: The answer is quite straightforward thanks to ES6. You need a combination of filter() and indexOf().
Here is the solution:
var List = ['Nick','George','George','Nick','Nick','George','Nick','Alex']

const unique = (value,index,self) =>
{return self.indexOf(value) ===index;}
var Unique_List=List.filter(unique);

Unique_List will give you the desired result.
Output: [Nick, George, Alex]

References:

*

*filter()

*indexOf()


text:
Q: my screen doesn't update when i update my list flutter Hello i'm new in flutter development i try to make a simple quiz app and keep the score in a list.
I have a list of icons i put it in a Row widget so when i press the true or false button my list add a widget(icon) to my row and display it .
But my screen doesn't update when i press the button until i hot reload or hot restart the app
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(Quizzler());

class Quizzler extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.grey.shade900,
        body: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.0),
            child: QuizPage(),
          ),
        ),
      ),
    );
  }
}

class QuizPage extends StatefulWidget {
  @override
  _QuizPageState createState() => _QuizPageState();
}

class _QuizPageState extends State<QuizPage> {
  List<Widget> scorekepper = [];

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Expanded(
          flex: 5,
          child: Padding(
            padding: EdgeInsets.all(10.0),
            child: Center(
              child: Text(
                'This is where the question text will go.',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 25.0,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
        Expanded(
          child: Padding(
            padding: EdgeInsets.all(15.0),
            child: FlatButton(
              textColor: Colors.white,
              color: Colors.green,
              child: Text(
                'True',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.0,
                ),
              ),
              onPressed: () {
                scorekepper.add(Icon(
                  Icons.check,
                  color: Colors.green,
                ));
              },
            ),
          ),
        ),
        Expanded(
          child: Padding(
            padding: EdgeInsets.all(15.0),
            child: FlatButton(
              color: Colors.red,
              child: Text(
                'False',
                style: TextStyle(
                  fontSize: 20.0,
                  color: Colors.white,
                ),
              ),
              onPressed: () {
                scorekepper.add(
                  Icon(
                    Icons.close,
                    color: Colors.red,
                  ),
                );
              },
            ),
          ),
        ),
        Row(
          children: scorekepper,
        ),
      ],
    );
  }
}

A: setState(() {
              scorekepper.add(
                Icon(
                  Icons.close,
                  color: Colors.red,
                ),
              );
            });

A: You need to put setState(() {}); after your function. This will run the build function so that it can refresh your screen and display the icon. See more here.
 onPressed: () {
                scorekepper.add(Icon(
                  Icons.check,
                  color: Colors.green,
                ));
                setState(() {});
              },

A: What is happening that you are adding item to list but not refreshing the UI,so in order to refresh the UI you have many options, the easiest way is to do setState(){} on add, Although i recommend you to search about state management like:
Bloc, Provider ...etc, which will optimize the performance the app when rebuilding.


text:
Q: Getting "function did not throw" While Testing Async Function to Throw Error with Jest I'm trying to test an async function with Jest and I can't get my test to pass.
My Code
export class UnexpectedRequestError {
  constructor(public message: string = 'Unauthorized') {
    this.message = message;
  }
}

export const foo = async (arg: boolean) => {
  if (arg) {
    return true;
  } else {
    const message = 'message';
    await sendSlackMessage(message);
    throw new UnexpectedRequestError(message);
  }
};

Test Code
test('throws UnexpectedRequestError', async () => {
  await expect(foo(false)).rejects.toThrow(UnexpectedRequestError);
});

My test returns:
expect(received).rejects.toThrow(expected)

Expected constructor: UnexpectedRequestError

Received function did not throw

I've searched for other similar questions here on StackOverFlow but I couldn't find anything wrong with my codes. Any ideas what I'm doing wrong?

A: Your error class needs the "Error" inheritance.
export class UnexpectedRequestError extends Error {
  constructor(public message: string = 'Unauthorized') {
    super(message);
  }
}


text:
Q: check constraint for 2 columns can anybody help me in writing a trigger on a table ,
 the scenario is like this
i have a table named person with columns col1 and col2 ,
Person
col1 |  col2
0    |  1
1    |  0
2    |  3
3    |  1
4    |  2
5    |  3

these columns col1,col2  values are dependent on another table employee columns col3 col4
Employee
col3 | col4
0    | 1
1    | 0
2    | 1
3    | 3
4    | 0
5    | 3
6    | 1

now if combination of col1 and col2 values (eg 0,1 from person table exists in employee table then do not update the columns col1 and col2 in person table ,if col1 and col2 values are  2,3 value doesn't exists in employee table ,so in this case if there is any update on columns  col1 and col2  just print a message

A: This has a smell to it. Based on your question it seems as though you are trying to create a trigger for maintaining a relationship between tables. If this is the case, you should probably consider creating composite foreign keys rather than using a trigger. This post has a good example of creating composite keys: Creating a composite foreign key in SQL Server 2008 .
In my experience, Person/Employee tables typically have a 1:0..1 relationship. In this case your Person table would have a primary key; in your case the key would be composite. The employee table would have it's own primary key as well as a composite foreign key which referenced the Person table.


text:
Q: How to pass message from angular template node in node red I'm trying to pass input textbox value by clicking on button

Hot: <input type="text" ng-model="hot" ng-value="myHot">

Cold: <input type="text" ng-model="cold">

<md-button ng-click="send({payload:action()})">
    Click me
</md-button>

A: If you simply want to sent the angular model values back to your node-red flow, you can use a ui_template node with some generic ng code like this:

Hot: <input type="text" ng-model="myHot">

Cold: <input type="text" ng-model="myCold">

<md-button ng-click="send({payload: {hot: myHot, cold: myCold}})">
    Send values
</md-button>

The returned msg.payload object will contains whatever values were entered into the hot and cold input fields, with this structure:
{"hot":"123","cold":"4.5"}


text:
Q: Strange entry in registry I was looking through HKEY_CURRENT_USER/Software and I found this...

and when I open it up...

Is this normal? Could it be malware or am I overreacting?
Windows 8.1, and I have many programs (108) installed. Malware scans by Windows defender and malwarebytes anti-malware (full scan) return clean.
I just ran chkdsk as admin:


text:
Q: How to call a function in Javascript when a input changes value? How to call function xxx when input type text id="username" change value ?
first, when you fill data into
<input type="text" name="thingy" onkeypress="updateInput(this.value)" onkeyup="updateInput(this.value)" />

Then data in
<input type="text" name="thingy" onkeypress="updateInput(this.value)" onkeyup="updateInput(this.value)" />

will change value.
OK, when input name="thingy" change i want to call function xxx , i try this code but not work.
How can i do that ?

<form id="main_fid">
    input1 : <input type="text" name="thingy" onkeypress="updateInput(this.value)" onkeyup="updateInput(this.value)" />

    <input type="submit" value="OK"/>
</form>

<form id="username_send_value_fid">
    input2 : <input type="text" name="username" id="username" onchange="xxx()" readonly/>
</form>

A: $("#username").on( "change", handler )

or in short form
$("#username").change( handler )

And get rid of the inline onchange attribute. You will also need to wrap the code in a ready function:
$(document).ready(function(){
   $("#username").change( handler )
});

http://api.jquery.com/change/
Added after reading the question a bit more carefully:
If you want to link your input name="thingy" to username you can do something like this:
$('input[name="thingy"]').change(function(){
    $("#username").val( $(this).val() ).trigger('change');
});

This will update the value of username and then trigger a change event as if the user had typed in the input.
However if what you are trying to accomplish is something like validating the uniqueness of an input the is no reason to jump though so many hoops - just call your ajax handler straight from the username change event.

A: I think calling xxx() on "onchange" event or inside updateInput(ish) will give the same effect.
Try
function updateInput(ish){
  document.getElementById("username").value = ish;
  xxx();
}


text:
Q: Intellij Scala/Java add resource folder My project-structure:
-Project
--res
---test.jpg
---bla.xml
--src
---Main.scala

Now I want to load bla.xml in my Main.scala
object Main
{
   val test = getClass.getResource("res/bla.xml")
}

Throws an IOException right into my face. Now how can I add the res-folder to the projects-searchpath?
I've already marked it as "resource folder".
If I place bla.xml at the root and load it with "bla.xml" everything is just fine, so I'm wondering how to do this in Intellij.
edit: Sascha Kolberg had it right:
Just use val test = getClass.getResource("/bla.xml") if you've added res as an resourcefolder.

A: Try val test = getClass.getResource("[full_path_to_bla.xml]"). If this works, slightly adjust, then you will figure out the correct relative path.
Please update us the correct one when you found it.

A: My comment as answer:
afaik, all contents or resource folders are placed in the class path root. So just try
val test = getClass.getResource("/bla.xml")


text:
Q: Problem with Linking an Image to a PDF file with  I am creating a website that displays a couple of book covers as images. The images display properly except when I put a tags around an img tag (because I want to link the image to a pdf of the book):

Picture of the distorted image next to a normal image
I'm not sure if this error is due to an html, css, or javascript problem, but I posted the github and website below:
https://readcoloringbooks.netlify.com/
https://github.com/ShanRauf/ReadColoringBooks

A: I wrote an answer before and it was wrong sorry for that.
The solution is to replace all your
`<li class="book"></li>`

with
`<a class="book"></a>`

and at your file css/library.css
replace
.bookshelf li {
    margin: 0 30px 30px 0;
}

with
.bookshelf a {
    margin: 0 30px 30px 0;
}

and I'd recommend changing that

with a div

A: The Code worked fine for me. here is an example of how i would do it -

It's best not to have spaces in your URLs, so either encode them or remove spaces in the file name, e.g. /my title to /my%20title
And ensure that the image you're loading is actually high resolution. Also, check to see if there is any CSS overriding content wrapped by


text:
Q: Get all values of some parameter for all documents in Marklogic I'm trying to get 'xxx' parameter of all documents in Marklogic using query like:
(/doc/document)/xxx

But since we have very big documents database I get an error "Expanded tree cache full on host". I don't have admin rights for this server, so I can't change configuration. I suggest that I can use ranges while getting documents like:
(/doc/document)[1 to 1000]/xxx

and then
(/doc/document)[1000 to 2000]/xxx

etc, but I'm concerned that I do not know how it works, for example, what will happen if during this process database will be changed (f.e. a new document will be added), how will it affect the result documents list? Also I don't know which order it uses in case when I use ranges...
Please clarify, is this way can be appropriate or is there any other ways to get some parameter of all documents?

A: Depending on how big your database is there may be no way to get all the values in one transaction.
Suppose you have a trillion documents, the result set will be bigger then can be returned in one transaction.
Is that important ? Only your business case can tell.
The most efficient way of getting all "xxx" values is with a range index.  You can see how this works
with cts:element-values  ( https://docs.marklogic.com/cts:element-values )
You do need to be able to create a range index over the element "xxxx" to do this (ask your DBA).
Then cts:element-values() returns only those values and the chances of being able to return most or all of them
in memory in a signle transaction is much higher then using xpath (/doc/document/xxx) which as you wrote actualy returns all the "xxx" elements (not just their values).  The most likely requires actually loading every document matching /doc and then parsing it and returning the xxx element.  That can be both slow and inefficient.
A range index just stores the values and you can retrieve those without ever having to load the actual document.
In general when working with large datasets learning how to access data in MarkLogic using only indexes will produce the fastest results.


text:
Q: Debugging htcondor issue running python script I am submitting a python script to condor. When condor runs it it gets
an import error. Condor runs it as
/var/lib/condor/execute/dir_170475/condor_exec.exe. If I manually copy
the python script to the execute machine and put it in the same place
and run it, it does not get an import error. I am wondering how to
debug this.
How can I see the command line condor uses to run it? Can the file
copied to /var/lib/condor/execute/dir_170475/condor_exec.exe be
retained after the failure so I can see it? Any other suggestions on
how to debug this?

A: You can simply run an interactive job (basically just a job with sleep or cat as command) and do ssh_to_job to run it.
Generally you need to set-up your python environment on the compute node, it is best to have a venv and activate it inside your start script.


text:
Q: IBM Mobilefirst uploading .wlapp gives Throwable Connection Closed within 1 minute i'm using liberty 8.5.5.5 and database DB2 10.5 and MobileFirst 7.1
While i'm uploading wlapp file(file size 50mb and above) in worklight console it says

Throwable Connection Closed : Read failed. Possible end of stream encountered, while redirecting request to http://XX.XX.XX.XX:9080/wladmin/management-apint-apis/1.0/runtimes/sample/applications?async=true

kindly let me know, what can be the  maximum size of .wlapp file that i can upload to IBM Mobilefirst console
During upload an error is throwing approximately in 1 minute. Is there a way to increase the timeout in configuration.
Kindly advice.

A: There is no filesize restriction for .wlapp files.
Note that an iFix was recently publishing handling the timeout values when uploading .wlapp files via the console: http://www-01.ibm.com/support/docview.wss?uid=swg1PI59605
Make sure you are using an iFix level that is greater than 2016-03-23.
You can verify your iFix build number in the console's About screen.


text:
Q: unity 3d remote and c# error? I want to simulate unity 3d remote and c# script to test touch response.
In my android device and I am getting error on playing the referenced script on this is behaviour is missing.
Please solve this problem.
using UnityEngine;
using System.Collections;

public class TouchSripts : MonoBehaviour {

    // Use this for initialization
    void OnGui()
    {
        foreach (Touch touch in Input.touches)
        {
            string message = "";
            message += "ID: " + touch.fingerId + "\n";

            message += "phase :" + touch.phase.ToString() + "\n";
            message += "TapCount:" + touch.tapCount + "\n";
            message += "Pos x :" + touch.position.x + "\n";
            message += "Pos y:" + touch.position.y+ "\n";

            int num = touch.fingerId;
            GUI.Label(new Rect(0 + 130 * num, 0, 120, 100) ,message);
        }
    }

    // Update is called once per frame
    void Update () {
    }

}

A: This error is called when Unity can not access a script, usually because names are not matching up. So simply make sure your script inside the project window is the same as your class name (TouchSripts). Sometimes that doesn't correctly fix it so just Select All and Copy the script, go back into unity, delete the old script, create a new script (making sure to call it TouchSripts), and delete the content of the new script, and paste your script into it.
Hope it helps!

A: You probably mistyped a reference somewhere in your scripts. It's also possible you forgot to assign something in the inspector. This is not an unity remote issue, you should get the same error when testing in the Editor


text:
Q: A generalization of the discriminant of a polynomial Let $\mathbb{K}$ be a field and let $f \in \mathbb{K}[x]$ be a monic polynomial of degree $n$. Suppose that $\alpha_1, \ldots, \alpha_n$ are all the roots of $f$ (in some algebraic closure of $\mathbb{K}$) and define
$$\Delta_f(y) = \prod_{\substack{1 \leq i , j \leq n \\ i \neq j}} (y - (\alpha_i - \alpha_j)).$$
Clearly, $\Delta_f(0)$ is the discriminant of $f$, so $\Delta_f(y)$ can be considered as a generalization of the notion of discriminant of a polynomial. It is also easy to see that $\Delta_f(y) \in \mathbb{K}[y]$ and that $\Delta_f(y)$ satisfies the identity
$$\operatorname{Res}_x(f(x), f(x + y)) = y^n \Delta_f(y),$$
where $\operatorname{Res}_x$ is the resultant respect to $x$.
My questions are:
(1) Does $\Delta_f(y)$ have a name? Is there any article/book where $\Delta_f(y)$ is introduced and its properties are studied?
(2) Assume that $\mathbb{K}$ has characteristic 0. If $n = 2$ then $\Delta_f(y) = y^2 - \Delta_f(0)$ and it follows that $\Delta_f(y)$ is irreducible in $\mathbb{K}[y]$ if and only if $f(x)$ is irreducible in $\mathbb{K}[x]$. What can we say about the irreducibility of $\Delta_f(y)$ for $n \geq 3$?
Thanks for any suggestion/reference.

A: As to question (2): Suppose that $\Delta_f(y)$ is separable. Then $\Delta_f(y)$ is irreducible if and only if the Galois group of $f$ acts transitively on the set of differences $\alpha_i-\alpha_j$, $i\ne j$, which is equivalent to transitivity on the set of pairs $(\alpha_i,\alpha_j)$. This, however, is equivalent to the Galois group of $f$ acting doubly transitively on the roots $\alpha_i$ of $f$.


text:
Q: LVM entry for logical volume in /etc/fstab - /dev/mapper/group-volume or /dev/group/volume? I created a logical volume like the following.
lvcreate -L 300G MyVolGroup -n homevol

As for mounting this volume after initializing a filesystem on it, a few guides I read used /dev/MyVolGroup/homevol. However, I noticed the root partition (as part of the default OS install) was mounted using /dev/mapper/MyVolGroup-root (this is a vanilla install of Fedora 35 Server).
Both symlink to ../dm-1. But I'm wondering if there's a good reason to use one over the other (the path under /dev/MyVolGroup or the path under /dev/mapper?

A: It doesn't matter, you can use either of them. As you found out these are just symlinks and both are created by udev (the /dev/mapper/<vg>-<lv> one is created by the 10-dm.rules rule and the /dev/<vg>/<lv> by the 11-dm-lvm.rules) so these will be created at the same time so there isn't really a reason to prefer one over the other.
I guess the /dev/<vg>/<lv> symlink can be seen as a more user friendly and more LVM-specific one and the /dev/mapper/<vg>-<lv> can be seen as a more low level one, because all device mapper devices have symlinks in /dev/mapper, not only the LVM ones.
And why Anaconda (Fedora installer) prefers the /dev/mapper path? I have no idea, it's just used in Blivet (storage library Anaconda uses) as the default path for LVM devices, probably for no particular reason.
Two small notes:

*

*You definitely should not use the /dev/dm-X device, the number is not persistent, dm-1 will simply be the first device mapper device created.

*Using UUID is usually preferred in fstab, but this mostly for partitions where /dev/sda1 is not guaranteed to be the same device between boots. You can use UUID here too, but it's not necessary, because the LVM names must be unique in the system so MyVolGroup-root will be always the same device.


text:
Q: How do you send Image data to a WCF Service I've searched and tried all previous posted suggested solutions and have not had any luck. I am obviously doing something wrong which I just can't figure out and I'm hoping someone will be able to help me here.My problem is this:
I have a WCF Service, and a WCF client. When I call the service and try to pass a byte array (uploading an image to the service), I get a Target Invokation exception error which is very vague. So, I hooked up tracing and the trace log is telling me the message quota size exceeded the limit, but I have modified the configs on both ends (app.config & web.config) to contain a really large limit. The problem is, it's telling me that the limit of 65536 was exceeded, but as you can see from my configs below it's way larger than that amount, so it's as if my client is using some other configuration values or I just didn't configure it right and it's ignoring what I have. Can someone help me?
App.Config:

Web.Config:

Any help you guys could offer would be greatly appreciated. I've been stuck on this problem now for two days.
Thanks everyone.
Here's the actual configuration code:
<system.serviceModel>
    <bindings>
        <wsHttpBinding>
            <binding name="WSHttpBinding_IDataSyncService" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                allowCookies="false">
                <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
                    maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00"
                    enabled="false" />
                <security mode="Message">
                    <transport clientCredentialType="Windows" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="Windows" negotiateServiceCredential="true"
                        algorithmSuite="Default" />
                </security>
            </binding>
        </wsHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://localhost/DataSyncWCF/DataSyncService.svc"
            binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IDataSyncService"
            contract="IDataSyncService" name="WSHttpBinding_IDataSyncService">
            <identity>
              <dns value="localhost" />
            </identity>
      </endpoint>
    </client>
</system.serviceModel>

Web.Config:
<services>
  <service behaviorConfiguration="DataSyncWCF.Service1Behavior"
    name="DataSyncWCF.DataSyncService">
    <endpoint address="" binding="wsHttpBinding" bindingName="WSHttpBinding_IDataSyncService"
      contract="DataSyncWCF.IDataSyncService">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>
</services>
<bindings>
  <wsHttpBinding>
    <binding name="DataSyncWCF.Service1Binding" maxBufferPoolSize="2147483647"
      maxReceivedMessageSize="2147483647" allowCookies="true">
      <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
        maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="None">
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior name="DataSyncWCF.Service1Behavior">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>

Here's my code calling the WCF Service:
VehicleImage vi = new VehicleImage();
System.IO.FileStream fs = new System.IO.FileStream(@"C:\images\1FAHP35N18W1589_01.jpg",        System.IO.FileMode.Open, System.IO.FileAccess.Read);
int len = (int)fs.Length;
vi = new VehicleImage();
vi.Image = new Byte[len];
fs.Read(vi.Image, 0, len);

// Here's the call to the WCF Service. It never makes it to the Service because of the message size limit error.
ResponseContract rc = client.SyncImage(vi);

A: Everything in WCF is heavily limited (throttled), with reason.
I see a lot of 2G numbers in your config, that would not be a good idea in general. And you may have missed a few,  I can't spot a SerializationLimit (approx name) so quickly.
There are 2 basic ways to deal with large messages in WCF: MTOM and streaming.

A: In your web.config wsHttpBinding, set the maxReceivedMessageSize:
<binding name="www" maxReceivedMessageSize="2147483647">


text:
Q: How to check if a statement string contains a word in C++? I want to check in C++ if a statement string contains a word. Now the problem is that all over the internet they use string::find or the boost library but the problem with these methods is that it only detect the word in a string with no spaces so for example, if i am using the string::find method it will not detect the word happy in the following string: " I am happy" but it will detect it in: "iamhappy" so does anyone know how to do it ?

A: The following is taken almost verbatim from cpp reference string find. It prints "found: happy".
#include <iostream>
#include <string>

void print(std::string::size_type n, std::string const &s)
{
    if (n == std::string::npos) {
        std::cout << "not found\n";
    } else {
        std::cout << "found: " << s.substr(n) << '\n';
    }
}

int main(int, char**){
    const std::string s = "i am happy";
    auto n = s.find("happy");
    print(n, s);
    return 0;
}


text:
Q: Mongoose post-remove event doesn't fire I have this code in my model:
ContentSchema.post( 'remove', function( item ) {
    index.deleteObject( item._id )
})

Here's what's in my controller:
Content.find( { user: user, _id: contentId } )
.remove( function ( err, count ) {
    if ( err || count == 0 ) reject( new Error( "There was an error deleting that content from the stream." ) )

    resolve( "Item removed from stream" )
})

I expect that when the function in the controller runs, the function in the model should happen. I can see in the debugger it does not fire at all.
I'm using "mongoose": "3.8.23" and "mongoose-q": "0.0.16".

A: The remove events (and other middleware hooks) are not fired on model-level methods.  If you use an instance method, eg:
Content.findOne({...}, function(err, content){
    //... whatever you need to do prior to removal ...
    content.remove(function(err){
         //content is removed, and the 'remove' pre/post events are emitted
    });
});

... you will be able to remove the content instance and have the pre/post remove event handlers fire.
The reason for this is because in order for the model-level methods to work as you would expect, the instance would have to be fetched and loaded into memory, as well as go through all of the sugar that Mongoose does to models when loading.  By the by, this problem is not unique to remove, any model-level method would exhibit the same issue (eg, Content.update).
This is a known quirk (for want of a better word) of Mongoose.  For more information, check out Mongoose #1241.


text:
Q: How to handle Many to Many records, when using Rails as REST API In my app, you can sign up as Company, and a company can add services that the company provides for users. These services is pickable from a list, in the companies preferences.
So i have a Many to Many relationship between the two of them.
class Company < User
  has_and_belongs_to_many :services
  accepts_nested_attributes_for :services
end

class Service < ActiveRecord::Base
  has_and_belongs_to_many :companies
  default_scope order('name ASC')
end

Now my problem is that don't what Rails expects from in the put request, this is what i currently for for my companies controller.
  def update
    company = Company.find(params[:id])
    if company == current_user && company.update_attributes(company_params)
      respond_with company
    else
      render json: {errors: company.errors}
    end
  end

  private

  def company_params
    params.require(:company).permit(:name, :email, :phone, services_attributes: [:service_id])
  end

So i am trying to send the id's of the selected services the company made, and the request payload looks something like this.
{"company": {
  "name":"Elvar's biks",
  "email":"fsfsdfsdf@sdf.com",
  "service_attributes": [{"id":"3"},{"id":"6"}]}}

But this yields
ActiveRecord::RecordNotFound at /api/companies/2
================================================

> Couldn't find Service with ID=3 for Company with ID=2

How should i approach this?

A: I turns out i did't need the accepts_nested_attributes_for method, neither should i have used services_attributes: [:service_id], for working with Many to Many.
Instead rails expects
service_ids: []

Notice [], this tells Rails to expect a array.
Updating with,
company.update_attributes(company_params)

now correctly adds the relation records in companies_services tables.
The final company params
params.require(:company).permit(:name, :email, :phone, service_ids: [])


text:
Q: PostgreSQL - SELECT query with ORDER BY and LIMIT 4 very slow, same query much faster with LIMIT >= 40 I've got following sample query from our Postgres DB:
SELECT * FROM advertised_car a0_
LEFT JOIN car_check c1_ ON a0_.car_check_id = c1_.id
WHERE c1_.status  = 'ACCEPTED'
ORDER BY a0_.id
LIMIT 4;

The advertised_car table has about 2M rows, each advertised_car has at most 1 car_check.
The car_check_id is indexed on the advertised_car table. The primary keys and status as well.
This query is extremely slow - over 1s.
When I remove either the limit or order by clause, I get a result under 0.05s.
I suppose that since the results are filtered, the DB cannot utilize existing index on a0_.id and has to reorder all the results.
What I don't get is the fact that when calling this query:
SELECT * FROM advertised_car a0_
LEFT JOIN car_check c1_ ON a0_.car_check_id = c1_.id
WHERE c1_.status  = 'ACCEPTED'
ORDER BY a0_.id
LIMIT 40;

The query suddenly runs much faster, almost as fast as without LIMIT or ORDER BY clause.
The execution plans differ, but I don't understand why the index scan in the first plan takes so long
Full execution plans:
LIMIT 4:  https://pastebin.com/azvxT0ZY
LIMIT 40: https://pastebin.com/yABqQVCa
Visual:


text:
Q: chart control filter multiple series by date I have a dynamic chart control that's manipulated by the user during run time.
The user has the ability to add multiple series' to the chart.
I'm trying to implement a way for the user to filter each series by date.
MSDN provides:
// Filters all points where the X value is less than, or equal to, a specific date.
// The resulting data is stored in an output series, preserving the original data.
myDataManip.Filter(CompareMethod.LessOrEqual, DateTime.Parse("1/1/2001").ToOADate(), "MySeries", "ResultSeries", "X");

This would be fine if I had a single series and I knew the input series name.
The question is how would i implement this for a chart that has multiple series'
Here is a quick work around I did:
private void button2_Click(object sender, EventArgs e)
{
    var dt = dateTimePicker.Value;
    var tempSeries = new Series[chart1.Series.Count];
    try
    {
        for (var i = 0; i < chart1.Series.Count; i++)
        {
            tempSeries[i] = new Series
            {
                Name = chart1.Series[i].Name,
                IsVisibleInLegend = true,
                IsXValueIndexed = true
            };

            for (var j = 0; j < chart1.Series[i].Points.Count; j++)
            {
                if (DateTime.Parse(chart1.Series[i].Points[j].AxisLabel) <= dt)
                {
                    tempSeries[i].Points.Add(chart1.Series[i].Points[j]);
                }
            }
        }
        chart1.Series.Clear();
        for (var i = 0; i < tempSeries.Count(); i++)
        {
            chart1.Series.Add(tempSeries[i]);
        }
    }
    catch (Exception error)
    {
        MessageBox.Show(error.ToString());
    }
}


text:
Q: Move rows from table to table I try to move rows that expired from one table to another with this:
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();

cmd.Connection = connect;
cmd.Connection.Open();

string commandLine = @"INSERT INTO history SELECT clientid,userid,startdate,
                       enddate,first,city,imgurl,phone,type,seen
                       FROM events WHERE startdate<now();";

cmd.CommandText = commandLine;

cmd.ExecuteNonQuery();
cmd.Connection.Close();

The table are exactly the same (in each table I have id column with primary key, with auto increment) and when I run it i get this exception:
Column count doesn't match value count at row 1

Any idea why it crash?

A: The reason why you get the error is because the number of column on the table doesn't match on the number of values being inserted. This is usual when you have an auto-incrementing column on the table you are inserting.
In order to fix the problem, you need to specify the column name where the values will be inserted. Example,
INSERT INTO history (col1, col2,....) // << specify column names here
SELECT clientid, userid, startdate, enddate, first,
       city, imgurl, phone, type, seen
FROM   events
WHERE  startdate < now()

I'm not pretty sure of the column names of table history that's why you need to change the column names to your valid names on your table.
For instance you have an auto-incrementing column on table history and you want to leave the query as is, you can pass NULL on the SELECT statement just to match the total number of columns to the total number of values. Example,
INSERT INTO history
SELECT NULL, clientid, userid, startdate, enddate, first,
       city, imgurl, phone, type, seen
FROM   events
WHERE  startdate < now()

Keep in mind that in the case you won't specify the column names, the order of the values does matter.

A: Try :
string commandLine = @"INSERT INTO history (clientid,userid,startdate,enddate,first,city,imgurl,phone,type,seen) SELECT clientid,userid,startdate,enddate,first,city,imgurl,phone,type,seen FROM events WHERE startdate<now();";


text:
Q: Notice: Variable seems to be uninitialized For some reason I am getting this notice in my code.

Variable $conn seems to be uninitialized

I don't understand why I'm seeing this notice.  I think I'm including my include in the right place.
Class Calendar {

  public function show() {
    include './includes/dbconn.php';
    include_once './includes/functions.php';

    for ($i=0; $i<$weeksInMonth; $i++) {

      // Create days in a week
      for ($j=1;$j<=7;$j++) {

        $cal_date = (string)$this->currentDate;
        $tutor_date = display_tutor_schedule($conn,$cal_date);

        if(isset($tutor_date[$j]['date'])) {
          $content .= $this->_showDay($i*7+$j, $tutor_date[$j]['date']);
        }
        else {
          $content .= $this->_showDay($i*7+$j, 0);
        }
      }
      $content .="
";
    }
  }

}

My $conn variable is coming from include './includes/dbconn.php';. Since I am not getting any PHP database error, such as "Not connected to the database" or something like that, I assume that my connection is right.
functions.php
function display_tutor_schedule($conn,$tutor_date) {

  $query = "select * from [dbo].[TUTOR_SCHEDULE] "
          . "LEFT JOIN [dbo].[TUTOR] "
          . "ON [dbo].[TUTOR_SCHEDULE].tutor_id = [dbo].[TUTOR].tutor_id "
          . "LEFT JOIN [dbo].[STATUS] "
          . "ON [dbo].[STATUS].status_id = [dbo].[TUTOR_SCHEDULE].status_id "
          . "WHERE [dbo].[TUTOR_SCHEDULE].date = '$tutor_date' " ;

  $stmt = sqlsrv_query($conn, $query);

  $i = 0;
  $appt_detail = array();
  while ($row = sqlsrv_fetch_array($stmt)) {
      $appt_detail[$i]['date']         = $row['date'];
      $appt_detail[$i]['t_shedule_id'] = $row['t_shedule_id'];
      $appt_detail[$i]['start_time']   = $row['start_time'];
      $appt_detail[$i]['end_time']     = $row['end_time'];
      $appt_detail[$i]['tutor_fname']  = $row['tutor_fname'];
      $appt_detail[$i]['tutor_lname']  = $row['tutor_lname'];
      $appt_detail[$i]['status_name']  = $row['status_name'];
      $appt_detail[$i]['status_id']    = $row['status_id'];

      $i++;
  }
  return $appt_detail;
}

my_class.php
<?php
    $calendar = new Calendar();
    echo $calendar->show();
?>

dbconn.php
$serverName = "myserver";
$connectionInfo = array("Database" => "my_database", "UID" => "user", "PWD" => "pwd");
$conn = sqlsrv_connect($serverName, $connectionInfo);

A: If you are using NetBeans or PhpStorm, then this might be IDE issue.
Check https://netbeans.org/projects/php/lists/users/archive/2013-03/message/49 and PhpStorm warning PHP variable might not have been defined
However, it is advisable that you show us the files you include to check them.

A: Since the variable is first initialized in the dbconn.php, the IDE might not recognize it. Insert
 $conn = null;

after the line
public function show() {

A: Don't use includes or global for your variables. It's bad.
Instead you should be using classes:
class Database {

    private $conn;

    public function __construct(){
        $serverName = "myserver";
        $connectionInfo = array("Database" => "my_database",
                                "UID" => "user",
                                "PWD" => "pwd");
        $this->conn = sqlsrv_connect($serverName, $connectionInfo);
    }

    public function  get_connection(){
        return $this->conn;
    }
}

Calendar.php
class Calendar
{
    private $conn;
    public $weeksInMonth;

    function __construct($conn){
        $this->conn = $conn;
    }

    public function show()
    {
        $content = "";
        for ($i = 0; $i < $this->weeksInMonth; $i++) {
            //Create days in a week
            for ($j = 1; $j <= 7; $j++) {
                $cal_date = (string)$this->currentDate;
                $tutor_date = display_tutor_schedule($cal_date);

                if (isset($tutor_date[$j]['date'])) {
                    $content .= $this->_showDay($i * 7 + $j, $tutor_date[$j]['date']);
                } else {
                    $content .= $this->_showDay($i * 7 + $j, 0);
                }
            }
            $content .= "
";
        }
        return $content;
    }

    function display_tutor_schedule($tutor_date)
    {
        $query = "select * from [dbo].[TUTOR_SCHEDULE] "
            . "LEFT JOIN [dbo].[TUTOR] "
            . "ON [dbo].[TUTOR_SCHEDULE].tutor_id = [dbo].[TUTOR].tutor_id "
            . "LEFT JOIN [dbo].[STATUS] "
            . "ON [dbo].[STATUS].status_id = [dbo].[TUTOR_SCHEDULE].status_id "
            . "WHERE [dbo].[TUTOR_SCHEDULE].date = '$tutor_date' ";

        $stmt = sqlsrv_query($this->conn, $query);

        $appt_detail = array();
        while ($row = sqlsrv_fetch_array($stmt)) {
            $appt_detail[] = $row;
        }
        return $appt_detail;
    }

}

Usage
$db = new Database();
$conn = $db->get_connection();
$calendar = new Calendar($conn);
$calendar->weeksInMonth = 4;
echo $calendar->show();


text:
Q: Character of a permutation representation I am self-studying representation theory, and I would like to make sure my proofs are complete.
Following Serre's notation, let $X$ be a finite set, and let $G$ be a group that acts on $X$. Let $\rho$ be the corresponding permutation representation i.e., for $s \in G$, and a basis $(e_x)_{x \in X}$ [the basis is indexed by the set $X$] of a vector space $V$, let $\rho_s(e_x) = e_{sx}$. Let $\chi_X$ be the character of $\rho$.
For $s \in G$, show that $\chi_X(s)$ is the number of elements of $X$ fixed by $s$.
My Work
Attempting to convince myself that this is indeed the case, I considered the standard basis of $\Bbb R^n$:
$$
\begin{pmatrix}
e_1 & e_2 & \cdots & e_{n-1} &e_n \\
 \end{pmatrix},
$$
where $e_i$ is an $n \times 1$ column vectors of $0$'s with a $1$ in the $i$th position. Now if $s = 1$, then $\chi_X(1) = n$ because the trace of an $n \times n$ identity matrix is just $1 + \cdots +1$ $n$ times. Then if $e_{sx} \ne e_x$, then we have a $0$ in this diagonal, and so it does not contribute anything to $\chi_X(s) = \operatorname{Tr}(R_s)$ for $R_s$ the matrix associated to $\rho_s$.
My Question
How would I formally write this out? I am a little too new to see a way forward with regards to proving this in generality.
Thanks for any help.

A: You have basically already done it. Namely, consider the basis $\{e_x\}_{x\in X}$ as you have labeled it. Let $A_g$ denote the matrix of $\rho(g)$ where $\rho$ is the permutation representation corresponding to the action $G\curvearrowright X$. Note then that $A_g=[a_{x,y}]$ where $a_{x,y}=\delta_{gy,x}$ (where $\delta$ is the Kronecker delta function). Thus, we see that
$$\text{tr}(A_g)=\sum_{x\in X}a_{x,x}=\sum_{x\in X}\delta_{gx,x}=\#X^g$$
where $X^g$ is the set of elements of $X$ fixed by $g$.


text:
Q: Manage assets in Laravel 5 Could someone explain the right approach in managing assets in Laravel 5?
For example, let's imagine I want to install some plugins using bower. The recommended way, as I got it, to keep all files into /vendor/bower_components. So I got some css, some images, fonts and javascript files withing the plugins.
Also I have a "app.less", where I import everything I need, like @import ('../../../vendor/bower_components/someplugin/somestyle.css'). The problem though that I don't have images/js/fonts in my public directory. Okay, I saw that you can use gulp copy function. However, when the number of plugins is getting higher, how I am supposed to manage where each plugin keeps its pictures or other files?
Actually I wanted to try semantic ui. I've downloaded it with bower. I know nothing about semantic ui, but there is a dist folder with semantic-ui.css. Also there are some fonts files withing themes/basic/assets/fonts. If I just copy it to public, it'll be public/themes/basic/assets/fonts. Then I import semantic-ui.css into my app.les and it'll find necessary fonts. What if I have some other plugins, it'll become unbearable to manage it all.
What is the typical workflow for this problem? The most simple way is just something like put everything into public and include it manually using <link> and <script> tags, but it'll require a lot of queries.
And why it's bad to keep all bower_components inside public? On the analogy of composer, we don't have autoloader for bower, so there is a mess of assets.

A: You are correct in the recommended place to put bower_components.  It's not recommended to put bower_components in the public directory because it contains ALL the files in that specific package, not just the file you need to include in your HTML.
Since your talking about Laravel5, it is recommended to utilize laravel-elixir to manage assets.  http://laravel.com/docs/5.0/elixir which utilizes gulp and can compile less, sass or various other files.  I don't have any experience with semantic ui, but it looks to be similar to bootstrap.  Without a SaaS or Less version available on npmjs.org you would need to copy the necessary files to your public directory.  Elixir provides a simple way to copy files or whole directories from bower_components to your public directory.
The easiest way to include all the files needed without a ton of  or  is to use saas or less.

A: Personally what I do is this using node

var elixir = require('laravel-elixir');

var nodeDir = './node_modules/'; //This is the node directory(base directory) where all vendor files are downloaded in your case might be different

/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Sass
 | file for our application, as well as publishing vendor resources.
 |
 */
elixir(function(mix) {
mix the styles and copy fonts to my public/css folder

    mix.styles([
        'bootstrap/dist/css/bootstrap.css',
        'font-awesome/css/font-awesome.css'
    ], './public/css/app.css', nodeDir)
        .copy(nodeDir + 'font-awesome/fonts', 'public/fonts')
        .copy(nodeDir + 'bootstrap/fonts', 'public/fonts');

//mix javascript from node directory and output to public/js/ folder

    mix.scripts([
        'jquery/dist/jquery.js',
        'bootstrap/dist/js/bootstrap.js'

    ], './public/js/app.js', nodeDir);

});


text:
Q: Win10 going into recovery mode after installing Ubuntu, Gparted shows 290GB partition as unallocated as done several times before(on other pc's), I installed Ubuntu next to Win10-64bit.
It's a BIOS not UEFI, on an Lenovo Laptop
To summarize:

*

*during install using Ubuntu installation resized and partitioned the main HD

*installed Ubuntu

*Ubuntu and Windows10 show up in GRUB

*Booting Ubuntu is OK

*Booting Windows10 NOT OK, goes into recovering mode, no way to boot into win10, even not safe-mode

*tried to fix mbr via USB booting, then windows goes directly into recovery mode, no help

*tried fixing GRUB again, so all entries are there again, same issues

*Gparted sees the 290GB windows partition, but says it's unallocated, same like empty

*I did not empty nor format this partition

*tried several tools like Testdisk and it says that some sectors are not having the correct size

Now I don't really care if Windows is going to run or not, but I need to get the data from that partition like photos and that kind of stuff, else my wife is gonna kill me, so you understand it's a state of emergency...she already got a new laptop.
I'm not being able to select that partition to be able to recover any data or use an undelete program to find data.
Any clue on what I could do on this matter?
Thanks a lot.


text:
Q: How to use j2objC for conversion in iOS code? I want to use my android code for i OS. I have seen many links recommends using of j2objC translator. But i don't know how to use this translator. can any body tell the all steps involved in this conversion??
I need the step-wise method

A: J2ObjC is a sophisticated tool and requires a certain amount of setup. You must have access to the source code and experience as a software engineer. The best starting point is the documentation:
https://github.com/google/j2objc/wiki/Getting-Started


text:
Q: How does Transaction Merge really work? I am repeating my unanswered question about MERGE operation. As I understand, to do MERGE md-sal has to read a tree into memory. Is it right? Can this read data be used for another MERGE within the same transaction or within the same transaction chain? If I need to do lots of merges of subtrees, will it improve performance if within the same transaction chain I preliminary read the entire tree that includes all these subtrees?

A: The tree is already fully stored in memory so it does not need to read it per transaction. When a transaction is created, it merely takes a snapshot of the current tree which is very fast. Subsequent transaction operations work on the snapshot, including reads. When a transaction is committed, the updates in the snapshot are validated and applied to in-memory tree.


text:
Q: Flutter - Debugging iOS 14 background message (when the app is closed) Trying to build a chat app, which gets FCM messages and shows notifications even when the app is closed.
Clearly, something in my top-level onBackgroundMessage function for FCM is wrong as the notifications are not showing (on a physical device- iOS emulators don't work with FCM).
In Android, I've debugged a similar situation by using adb logcat (and logs/print command).
Obviously, adb isn't available for an iPhone, and I don't know how to see the logs after the app is closed (I've tried to look at the console at Xcode but no Flutter messages are showing).
Because I can't run the app again after it's closed (see https://docs.flutter.dev/development/ios-14 the application can no longer be re-launched by tapping the application's icon) I'm installing it on my device via "flutter install release".
How do I see the logs after install release, or otherwise how can I debug functionality (at least view flutter's logs and prints) when the app is closed?


text:
Q: In the figure, how do I find the value of the variable?
According to the problem, I have to find the value of the variable in simplest radical form. I began with the equation 18√9 = 6 (1/3)x, so x = 9√3. Now, I know we have to find the area of the base in terms of x. But how do I find the height; do I use Pythagorean Theorem?

A: You can use Heron's formula for example.
Or since it is an equilateral triangle by the sine formula:
$$A=\frac12x^2\sin60°=\frac{x^2\sqrt 3}{4}$$
You can find many other formulas here Equilateral triangle.

A: In an equilateral triangle, the heights are exactly the medians. Whence, the heights have length:
$$\frac{\sqrt{3}}{2}x.$$

A: Your initial equation is a little strange, it uses $x$ to designate the area of the base of the pyramid, while in fact on the picture $x$ has another meaning, which is the length of the edges of the base. Also some $\sqrt{3}$ became $\sqrt{9}$, but the result still good, I suspect a typo here.
I would write for a pyramid $V=\frac 13 BH\implies B=\dfrac{3V}H=\dfrac{3\times 18\sqrt{3}}6=9\sqrt{3}$

Note: on this picture I found on the web, they used $a$ in place of $x$.
Now the base is an equilateral triangle.
Area is $B=h\times \frac x2$
And by Pythagoras $(\frac x2)^2+h^2=x^2$ so $h=\frac{\sqrt{3}}2x$
Thus you get $B=\frac{\sqrt{3}}4x^2=9\sqrt{3}\implies x^2=36\implies x=6$

A: \begin{gathered}
V\ =\ \frac{Bh}{3} \ \ \ where\ B\ is\ the\ base\ area\ of\ the\ equilateral\ triangle\ of\ length\ x\\
\\
B\ =\ \frac{1}{2} \ ( base\ triangle\ length)( base\ triangle\ height) \ =\ \ \frac{1}{2} \ ( x)\left(\frac{\sqrt{3} x}{2} \ \right) \ =\ \frac{\sqrt{3} x^{2}}{4}\\
\\
V\ =\ \frac{1}{3} \ *\ \frac{\sqrt{3} x^{2}}{4} \ *\ 6\ \ =\ \frac{6\sqrt{3} x^{2}}{12} \ =\ \frac{\sqrt{3} x^{2}}{2}\\
\ \ \\
\ 18\sqrt{3} \ =\ \frac{\sqrt{3} x^{2}}{2}\\
\\
36\ =\ x^{2} \ \ \ \ \ \ \ \ \ so\ \ \ \ \ \ \ \ x\ =\ 6\\
\end{gathered}

A: You are asking how to find the height of an equilateral triangle.
Pythagorean theorem is a good idea. Drop the height to the base; it will hit the base in the midpoint (by symmetry of the equilateral triangle), so it divides the equilateral triangle into two right triangles, each of which has a leg length $\frac{x}{2}$ and hypotenuse length $x$. The last leg is the height.


text:
Q: Select row from a DataFrame based on the type of the object(i.e. str) So there's a DataFrame say:
>>> df = pd.DataFrame({
...                 'A':[1,2,'Three',4],
...                 'B':[1,'Two',3,4]})
>>> df
       A    B
0      1    1
1      2  Two
2  Three    3
3      4    4

I want to select the rows whose datatype of particular row of a particular column is of type str.
For example I want to select the row where type of data in the column A is a str.
 so it should print something like:
   A      B
2  Three  3

Whose intuitive code would be like:
df[type(df.A) == str]

Which obviously doesn't works!
Thanks please help!

A: This works:
df[df['A'].apply(lambda x: isinstance(x, str))]

A: It's generally a bad idea to use a series to hold mixed numeric and non-numeric types. This will cause your series to have dtype object, which is nothing more than a sequence of pointers. Much like list and, indeed, many operations on such series can be more efficiently processed with list.
With this disclaimer, you can use Boolean indexing via a list comprehension:
res = df[[isinstance(value, str) for value in df['A']]]

print(res)

       A  B
2  Three  3

The equivalent is possible with pd.Series.apply, but this is no more than a thinly veiled loop and may be slower than the list comprehension:
res = df[df['A'].apply(lambda x: isinstance(x, str))]

If you are certain all non-numeric values must be strings, then you can convert to numeric and look for nulls, i.e. values that cannot be converted:
res = df[pd.to_numeric(df['A'], errors='coerce').isnull()]

A: You can do something similar to what you're asking with
In [14]: df[pd.to_numeric(df.A, errors='coerce').isnull()]
Out[14]:
       A  B
2  Three  3

Why only similar? Because Pandas stores things in homogeneous columns (all entries in a column are of the same type). Even though you constructed the DataFrame from heterogeneous types, they are all made into columns each of the lowest common denominator:
In [16]: df.A.dtype
Out[16]: dtype('O')

Consequently, you can't ask which rows are of what type - they will all be of the same type. What you can do is to try to convert the entries to numbers, and check where the conversion failed (this is what the code above does).


text:
Q: Select GStreamer Element Based on Source Capabilities Using gst-launch is there any way to select a GStreamer Element based on the capabilities determined by a source element? For example, if I have a network source element which could download an MP3, M4A, or WAV file, can I select which element to pipe the data to based on the file type received? The file type is not actually known until after the network source element is loaded. See the linked image below for the pipeline I have in mind. Any ideas?

A: you can use decodebin2 or uridecodebin element. These elements contain autodetct capabilities.
http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-base-plugins/html/gst-plugins-base-plugins-uridecodebin.html


text:
Q: Problem in Creating a View Dynamically ( in Android ) [Error : couldn't save which view ...] I'm trying to create a View dynamically (on click). Any person have any idea why this does not work. It just opens a blank (BLACK) screen. When i click back it moves to previous screen as well. And i need to know the way i'm trying to set the team is correct.
public class Details extends Activity {

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        //setTheme(android.R.style.Theme_Dialog);

        TextView label = new TextView(this);
        label.setText("Hello This text");
        label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        label.setTextSize(20);
        label.setGravity(Gravity.CENTER);

        TableRow tr = new TableRow(this);
        tr.addView(label);

        TableLayout tl = new TableLayout(this);
        tl.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        tl.setGravity(Gravity.CENTER);
        tl.addView(tr);

        ScrollView sv = new ScrollView(this);
        sv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        sv.addView(tl);

        setContentView(sv);
    }
}

There is an msg in LogCat as following
couldn't save which view has focus because the focused view ##### has no id

A: Is the activity declared in the Manifest.xml?

A: Well one obvious thing is that you are using generic LayoutParams, not the correct parameters for the layout manager.  For example you are not using a TableLayout.LayoutParams for the TextView so you are not actually telling it how to layout the text view within the table structure.
I also suggest using hierarchyviewer to look at what is going on with your view hierarchy.

A: You must to put
@Override
I had the similar problem


text:
Q: Running Python scripts in Slurm I've recently started a new job and need to run some scripts on the HPC through Slurm.
My scripts are written in Python, and therefore I want to execute these using python script.py in my .slurm file.
However, when I try to run the .slurm file, it doesn't seem to be able to call the python scripts. I've tried loading the python environment using module load anaconda3, and variations thereof (e.g. module load python, etc.). Attached is my array.slurm file, for reference(.slurm file). I've left the account and mail-user empty for uploading here for anonymity, but I have these in when I run the script.
The error file output by Slurm indicates the following:
/var/spool/slurmd/job220829/slurm_script: line 19: module: command not found

Can someone offer practical guidance? I need to run these Python scripts as soon as possible.

A: As md2perpe mentioned every HPC system is different. They customize the slurm scheduler up to some extent. Still many HPCs share the same basic commands.
For instance, here is a job submission script that I created to run a python file on a GPU node.
#!/bin/bash
#SBATCH --nodes=1
#SBATCH --time=00:00:40
#SBATCH --ntasks=1
#SBATCH --job-name=gpu_check
#SBATCH --output=gpu.%j.out
#SBATCH --error=gpu.%j.err
#SBATCH --gres=gpu:1
#SBATCH --account=scw1901
#SBATCH --partition=accel_ai

module load anaconda/3
source activate base
python gpu.py

I can suggest you the following:

*

*After loading anaconda module you should activate the conda virtual environment. For example, source activate base. To see a list of available conda environments type this conda env list. Then activate the conda environment of your choice.

*I don't know what your python script is, so can't really comment on the argument that you used.

*Make sure you have access to the partition. To see a list of partition type sinfo. Also check the state. If it is drain or reserved then you simply can't use that partition.

*Maybe you can run your script without --ntasks-per-nodes and --array. Why not try my job script?

*If nothing works, please paste the output of error file in your question. In my case, the JOBID is defined by %J not %a as in your case.

*You can remove those email arguments --mail if you don't need it.

*What is SLURM_ARRAY_TASK_ID? If you don't know please remove it.

*You said you don't have module command. The error is in line 19. But you used module command in line 18. Are you sure you are sharing the correct job script?

*Can you run module load anaconda/3 in the login node? Just copy and paste this after SSHing. If yes then module is available.


text:
Q: Update pandas dataframe column with another column in another dataframe on index overlap I wish to update column A in dfA with column B in dfB on index overlap
dfA
     A
1    1
2    1
3    1
4    1

dfB
     B
3    2
4    2
5    2
6    2

Desired result:
     A
1    1
2    1
3    2
4    2

What is the simplest way to do this?

A: Try with update
dfA.update(dfB.rename(columns = {'B':'A'}))


text:
Q: Get Amazon ECS container to exit if Flask Entrypoint fails I am updating my ECS service to use a new task definition. The task definition in this case is a flask application running on gunicorn.
Under certain conditions, I want the flask application to exit and subsequently the update to the ECS service to fail. In this case, I want to check the database connection (and exit if the database connection is not running).
However, I am not seeing this. Whenever I exit or kill the flask application (using sys.kill or os.kill for example), the task definitions still continue to be updated.
How do I kill the update to the ECS service as well given that my entrypoint fails?
I saw this as well: https://aws.amazon.com/blogs/containers/graceful-shutdowns-with-ecs/ but the SIGTERM also doesn't work.

A: To update this, the problem was that the service kept crash-looping. To resolve this, I used the ECS deployment breaker: https://aws.amazon.com/blogs/containers/announcing-amazon-ecs-deployment-circuit-breaker/ which allows you to exit out of this loop.


text:
Q: Disable all caching when implementing ICacheClient Good Morning,
We have a servicestack implementation that uses caching.
We can swap between:

*

*Redis

*Memcached

*In Memory

because they all implement ICacheClient. We change which cache is getting used by just changing a cache setting node in the web.config.
My question is, how do I go about switching a config setting to "Cache:None" for example.
I suppose I could have my own CacheClient that implements ICacheClient that actually does nothing but implement the ICacheClient interface but this feels hacky and dirty.
The reaason we want to be able to switch off caching is to just get a base line on performance for testing.
thanks
Russ

A: You would have to register your own NullCacheClient since if there's no ICacheClient registered, ServiceStack defaults to using the in-memory MemoryCacheClient as a fallback.


text:
Q: Image thumbnail not generating properly using PHP I have writen a script in PHP to upload an image.
To the point, my goal is to upload and to send 2 images to the server, 1 the original and 1 is the thumbnail. My script works, but is not perfect.
This is my script
<?php

     //this is script for get  data type file

      $acak        = rand(000000,999999);// for random
      $lokasi_file = $_FILES['fupload']['tmp_name'];
      $nama_file   = $_FILES['fupload']['name'];

      $nama_file_acak = $acak.$nama_file;

      $ukuran_file = $_FILES['fupload']['size'];
      $tipe_file   = $_FILES['fupload']['type'];
      $direktori   = "fkendaraan/$nama_file_acak";

       $uplod = move_uploaded_file($lokasi_file,"$direktori"); //to move image from local to the server folder

     //to handle uplod thumbnail image
      $img = imagecreatefromjpeg($direktori);

      $width = imagesx($img);
      $height = imagesy($img);

      $new_width = 200;

      $new_height = ($new_width/$width) * $height;

      $tmp_img = imagecreatetruecolor( $width, $height );

      imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

      //imagecopyresized( $tmp_img, $img, 200, 200, 0, 0, $new_width, $new_height, $width, $height );

      imagejpeg( $tmp_img, $direktori."thumb-".$nama_file_acak );

      imagedestroy($tmp_img);
      imagedestroy($direktori);

//---------------------------------------------------------------
//I have no Problem with query and database, it works fine
$sql = "";
$query = mysql_query($sql);

?>

This can run but not perfect because the result like this

Any one can help me to fix this? Im very nubie in php

A: Try changing this:
$tmp_img = imagecreatetruecolor( $width, $height );

To this:
$tmp_img = imagecreatetruecolor( $new_width, $new_height );

Anyway I would recommend you to make use of some classes for these tasks such as:
Shiege Iseng Resize Class.
But of course, if you are trying to learn with this, that's ok :)


text:
Q: Updating a nested list object in the global environment from within a function in R Here are the set of circumstances that have gotten me stuck:
The Problem
I have written a function in R that will need to execute within a for loop with the goal of manually adjusting some values and then updating a large nested list in the global environment. I have 2 functions more.points() and get.num.pts() that ask for user input. These are part of a larger function add.points() which runs everything and will be wrapped in a for loop. Unfortunately, I cannot figure out how to update the nested list to the correct place in the list's hierarchy from within the function. I must do it from within the function in order to make sure I dont run lines of code in the for loop after the function because this will cause readlines() to fail and take the next line of code as user input. How do I update the hierarchical list object in the correct place from within the add.points() function? assign() does not appear to be up to the task, at least to my limited knowledge. Any help is greatly appreciated. I am making a pipeline for aligning an atlas to brain images so I can localize cells that fluoresce to their respective brain regions.
more.points <- function(){
  more.pts <- readline(prompt = "Do you need to add correspondence points to adjust the atlas registration? (y/n): ")
}

get.num.pts <- function(){
  num.pts <- readline(prompt = "How many additional points are required? (You will be able to add additional points later if you need to): ")
}

add.points <- function(){

  mo.pts  <- as.character(more.points());
  if(mo.pts == "y" || mo.pts == "Y" || mo.pts == "Yes" || mo.pts == "yes"){
    while(mo.pts == "y" || mo.pts == "Y" || mo.pts == "Yes" || mo.pts == "yes") {
      #ask for user input about number of new points to be created
      n.pts <- as.integer(get.num.pts());
      reg.fun.obj <- paste0(n.pts," updated!");
      print(reg.fun.obj)
      #do other stuff
#assign totally works here just fine because it isnt a hierarchical list being updated
      assign("reg.obj", reg.fun.obj, envir = .GlobalEnv);
      #Need to update the correct position in the list object hierarchy with new info.
      assign(i.data[[reference.df$i[[i]]]][[reference.df$j[[i]]]][[reference.df$k[[i]]]], reg.obj, envir = .GlobalEnv);
      #But this cannot take `i.data[[reference.df$i[[i]]]][[reference.df$j[[i]]]][[reference.df$k[[i]]]]` for the name argument. it must be a string.
      mo.pts = as.character(more.points())
    }

  }

}

Reproducible example:
Here is an example of the global environment hierarchical list I need to update from an object within the add.points() function:
#Hierarchical List Object Example

#The image objects have more complexity in my real implementation i.e. image_1 is itself a list object with multiple attributes.
list.i <- c("channel1", "channel2", "channel3")
list.j <- c("m1", "m2", "m3")
list.k <- c("image_1", "image_2", "image_3")

k.tmp <- list()
j.tmp <- list()
i.data <- list()

for(i in seq_along(list.i)){
  for(j in seq_along(list.j)){
    for(k in seq_along(list.k)){
      k.tmp[[k]] <- list.k[[k]]
      names(k.tmp)[[k]] <- paste0("img", k)
    }
    j.tmp[[j]] <- k.tmp
    names(j.tmp)[[j]] <- paste0("m", j)
    k.tmp <- list()
  }
  i.data[[i]] <- j.tmp
  names(i.data)[[i]] <- paste0("channel", i)
  j.tmp <- list
}
remove(k.tmp,j.tmp)

#Additional example list I am using to know which elements of the hierarchy need to be updated/adjusted as the for loop cycles.

reference.df <- data.frame(i = c(rep(1, 9), rep(2, 9), rep(3, 9)), j = c(rep(c(1, 1, 1, 2, 2, 2, 3, 3, 3),3)), k = c(rep(c(1, 2, 3),9)))

Code to run function:
reg.obj <- i.data[[reference.df$i[[i]]]][[reference.df$j[[i]]]][[reference.df$k[[i]]]]

for(i in seq_along(reference.df$k)){

  add.points()

}

Remember: I am unable to run anything after the function within the for loop because R will interpret the next line as the user input being fed to readlines(). Thus, the whole point of this loop and function - getting user input, saving, and cycling to the next image for the user to provide input on - will not occur.

A: For anyone else who runs into an issue like this. Don't be stupid like me. Use the return() function within your function to convert your variable into an output that you can feed into your nested list thusly:
in the function:
myfun(){
#do stuff to make object containing update
return(update.obj)
}

#run the function:

list[[x]][[y]][[z]] <- myfun()

#is equivalent to below occurring outside a function:
list[[x]][[y]][[z]] <- update.obj

Yes this was stupid but hopefully I helped someone avoid my fundamental mistake here. If you can avoid it, don't use assign() in a function.


text:
Q: Update sqlite3 dll in PHP on Windows I run PHP 5.4.16 on Apache on Windows. It uses sqlite3 3.7.7, I'd like to update it to 3.7.11.
Can I just overwrite the php_sqlite3.dll in the ext subdirectory, or do I need to compile PHP?

A: You should be able to just replace the library without recompiling.
You will, however, need to restart the web server before PHP will pick up the new library.


text:
Q: What Do These Errors mean When Trying To Upload Video File? The following is my php script for you to upload video files (max 100MB) to my server.
Problem is, it uploads one mp4 file without any problems. But when I try uploading others it gives these errors.
When I try uploading "T.J. Hooker (1982) - Season 1 OPENING.mp4" which is 2.57MB, I get this error:
array(1) { ["id_verification_video_file"]=> array(5) { ["name"]=>
string(41) "T.J. Hooker (1982) - Season 1 OPENING.mp4" ["type"]=>
string(0) "" ["tmp_name"]=> string(0) "" ["error"]=> int(1) ["size"]=>
int(0) } } Array ( [id_verification_video_file] => Array ( [name] => T.J.
Hooker (1982) - Season 1 OPENING.mp4 [type] => [tmp_name] => [error] => 1
[size] => 0 ) )

Q1. What does this error mean ?
When I try uploading another file "Taekwondo vs Jeet Kune Do.mp4" which is 9.32MB, I get the following error:
"array(0) { } Upload your video file".
Q2. Why am I getting line 17 triggered when I am trying to upload a video (mp4) file ?
Line 17:
if(!isset($_FILES["id_verification_video_file"]))
    {
        echo "Upload your video file";
        exit;
    }

Full Script:
<?php

$conn = mysqli_connect("localhost","livefoll_user","livefollow_2019*","livefoll_live
follow");

if (!$conn)
{
    $error = mysqli_connect_error();
    $errno = mysqli_connect_errno();
    print "$errno: $error\n";
    exit();
}

if($_SERVER["REQUEST_METHOD"] == "POST")
{
    var_dump($_FILES);
    //Check whether the file was uploaded or not without any errors.
    if(!isset($_FILES["id_verification_video_file"]))
    {
        echo "Upload your video file";
        exit;
    }

    elseif (!$_FILES["id_verification_video_file"]["error"] == 0)
    {
        $Errors = Array();
        $Errors[] = "Error: " . $_FILES["id_verification_video_file"] ["ERROR"]; print_r($_FILES); ?>
<?php
        print_r($_ERRORS);
        exit();
    }
    else
    {

        $user = 'livefoll_user';
        //Feed Id Verification Video File Upload Directory path.
        $directory_path = 'uploads/videos/id_verifications/';
        //Make Directory under $user in 'uploads/videos/id_verifications' Folder.
        $directory_path_and_user_dir = "uploads/videos/id_verifications/$user";

        if(!is_dir($directory_path_and_user_dir))
        {
            $user = 'livefoll_user';
            $mode = 0755;
            mkdir($directory_path_and_user_dir,$mode, TRUE);
        }

        //Grab Uploading File details.
        $Errors = Array(); //
        $file_name = $_FILES["id_verification_video_file"]["name"];
        $file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
        $file_type = $_FILES["id_verification_video_file"]["type"];
        $file_size = $_FILES["id_verification_video_file"]["size"];
        $file_error = $_FILES['id_verification_video_file']['error'];

        //Grab Uploading File Extension details.
        $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);

        $directory_path_and_user_dir_and_user_file = "$directory_path_and_user_dir/$file_name";

        if(file_exists($directory_path_and_user_dir_and_user_file)) //THIS LINE IS NOT GIVING THE ERROR THAT FILE ALREADY EXISTS. INSTEAD SHOWING A BLANK WHITE PAGE. -> I changed it with 'echo'. It was not giving error because you were just storing the error into the Errors array without throwing the error.
        {
            echo "Error: You have already uploaded a video file to verify your ID! No need to upload and do it again!";
            exit();
        }
        else
        {
            //Feed allowed File Extensions List.
            $allowed_file_extensions = array("mp4" => "video/mp4");

            //Feed allowed File Size.
            $max_file_size_allowed_in_bytes = 1024*1024*100; //Allowed limit: 100MB.
            $max_file_size_allowed_in_kilobytes = 1024*100; //Allowed limit: 100MB.
            $max_file_size_allowed_in_megabytes = 100; //Allowed limit: 100MB.

            $max_file_size_allowed = "$max_file_size_allowed_in_bytes";

            //Verify File Extension.
            if(!array_key_exists($file_extension, $allowed_file_extensions))
            {
                echo "Error: Select a valid video file format. Select an Mp4, Wav, etc. files.";
                exit();
            }
            //Verify MIME Type of the File.
            elseif(!in_array($file_type, $allowed_file_extensions))
            {
                $Errors[] = "Error: There was a problem uploading your file $file_name! Make sure your file is a video file. You may try again."; //IS THIS LINE CORRECT ? -> yes but won't print if you don't use throwerror or echo ... echo "error: there was a problem... etc..."
                exit();
            }
            //Verify File Size. Allowed Max Limit: 100MB.
            elseif($file_size>$max_file_size_allowed)
            {
                $Errors[] = "Error: Your Video File Size is larger than the allowed limit of: $max_file_size_allowed_in_megabytes.";
                exit();
            }

            $move_to = $directory_path_and_user_dir."/".$file_name;
            //Move uploaded File to newly created directory on the server.
            if(!move_uploaded_file($file_tmp, $move_to))
            {
                //user = 'livefoll_user'; //Not necessary
                $mode = 0755;  //Not necessary

                //Notify user their Id Verification Video File uploading failed.
                echo "Your Video File \"$file_name\" has failed to be uploaded! You may try some other time.";
                exit();
            }
            else
            {
                //Notify user their Id Verification Video File was uploaded successfully.
                die("Your Video File \"$file_name\" has been uploaded successfully!");
            }
        }
    }
}
?>

<?php //SWITCH FOLLOWING UPLOADING WEB FORM TO HTML5 DESIGN WITH CAPTCHA
AND HIDDEN FIELD/S. FOIL BOTS FROM UPLOADING FILES. MUST BE SQL INJECTION
AND HACKING PROOF.?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
    <fieldset>

<?php $site_name ?> ID Video Verification
Form

        <p align="left"Video File:
        <input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'">

    </fieldset>

<button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button>

</form>

Q4. How to solve these issues ? I mean, if the script code is not buggy and manages to upload one mp4 file then it should be able to upload other mp4 files too without showing errors.

A: Problem solved. The .ini file was restricting the file size.


text:
Q: good books that explained optimization using SA,Genetics and ... algorithm I don't know this is right place for asking this but I had no Other options
In Operation Research Course My professor give us some lecture note about nonlinear optimization and some algorithm for solving them but I can't understand them.
I'll be appreciate if recommend me good resourced(book is preferred) for study nonlinear optimization and related algorithms


text:
Q: Referencing ajax calls to multiple divs i have to two pages in jquery mobile and in each of the pages is a div called content and inside the divs i call external pages into it by means of ajax. for "page1" the call works perfectly but for "page2" the call isn't working. though the div in "page2" is having the same name as that of "page1".
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />

Page 1

        Content

        Go to Page 2

Footer

Page 2

        Content

        Go to Page 1

Footer

A: try using:
$("div").find("[data-role='content']").load('total.asp');

because you have given it as data attribute. you can better use class if you have multiple id with same name in that case it will be:
$(".content").load('total.asp');

A: ID has to be unique. try changing id="content" to class="content" and then try the below code
$.ajaxSetup({ cache: false });
    setInterval(function() {
        $('.content').load('total.asp');
    }, 3000);
});


text:
Q: GWT Deobfuscator Builder ClassCastException I have a GWT webapp which uses a RequestFactory - the app seems to launch just fine, but as soon as I try to open it in a browser, it blows up with this exception:
com.google.web.bindery.requestfactory.server.RequestFactoryServlet doPost
SEVERE: Unexpected error
java.lang.ClassCastException: class com.myapp.console.shared.MyAppRequestFactoryDeobfuscatorBuilder
    at java.lang.Class.asSubclass(Class.java:3126)
    at com.google.web.bindery.requestfactory.vm.impl.Deobfuscator$Builder.load(Deobfuscator.java:52)
    at com.google.web.bindery.requestfactory.server.ResolverServiceLayer.updateDeobfuscator(ResolverServiceLayer.java:43)
    at com.google.web.bindery.requestfactory.server.ResolverServiceLayer.resolveRequestFactory(ResolverServiceLayer.java:176)
    at com.google.web.bindery.requestfactory.server.ServiceLayerDecorator.resolveRequestFactory(ServiceLayerDecorator.java:172)
    at com.google.web.bindery.requestfactory.server.ServiceLayerDecorator.resolveRequestFactory(ServiceLayerDecorator.java:172)
    at com.google.web.bindery.requestfactory.server.ServiceLayerDecorator.resolveRequestFactory(ServiceLayerDecorator.java:172)
    at com.google.web.bindery.requestfactory.server.ServiceLayerDecorator.resolveRequestFactory(ServiceLayerDecorator.java:172)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.google.web.bindery.requestfactory.server.ServiceLayerCache.getOrCache(ServiceLayerCache.java:233)
    at com.google.web.bindery.requestfactory.server.ServiceLayerCache.resolveRequestFactory(ServiceLayerCache.java:198)
    at com.google.web.bindery.requestfactory.server.SimpleRequestProcessor.process(SimpleRequestProcessor.java:215)
    at com.google.web.bindery.requestfactory.server.SimpleRequestProcessor.process(SimpleRequestProcessor.java:135)
    at com.google.web.bindery.requestfactory.server.RequestFactoryServlet.doPost(RequestFactoryServlet.java:133)
    ....

The MyAppRequestFactoryDeobfuscatorBuilder class is auto-generated (my class is MyAppRequestFactory), so it's proving very difficult to debug. This didn't used to happen a few weeks ago when I last used this app. What's causing this error and how do I fix it? I'm not a GWT expert, so small words and understandable explanations would be appreciated!

A: This is likely a classloader issue, Deobfuscator.Builder being loaded from a different (and sibling or child, not parent) classloader than MyAppRequestFactoryDeobfuscatorBuilder, so the Deobfuscator.Builder parent class of MyAppRequestFactoryDeobfuscatorBuilder is not the same as the Deobfuscator.Builder class that tries to load it.
Did you change anything between the time it worked and now?
(note: GWT 2.6.0's DevMode has a classloader issue, so if you updated to GWT 2.6.0 and don't strictly follow the expected project layout –i.e. some libs missing from your WEB-INF/lib and/or your compiled classes not being in WEB-INF/classes– then you could run on such issue)


text:
Q: Как сделать суммирование в сводной таблице? Мой код:
new6 = new3.groupby(['YrSold', 'Flag'])['SalePrice'].aggregate('sum')
new6

Как сделать то же самое, но с помощью new6 = new3.pivot_table(...?
Так пыталась, не работает:
new6 = new3.pivot_table(values=['YrSold', 'Flag'], index=['SalePrice'], aggfunc='sum')

Так должно быть:

И как этот столбец, где сумма, именовать, чтоб надпись была над ним была 'Summa'?

A: Не совсем понятно зачем вам PIVOT. Для такой простой задачи df.groupby().sum() - более идиоматическое решение.
In [10]: new3.groupby(['YrSold', 'Flag'])['SalePrice'].sum().reset_index(name="Summa")
Out[10]:
   YrSold  Flag     Summa
0    2006     0  28193621
1    2006     1  29126909
2    2007     0  30848091
3    2007     1  30366686
4    2008     0  26948329
5    2008     1  26969366
6    2009     0  32986315
7    2009     1  27661736
8    2010     0  14862208
9    2010     1  16181685

Если все же нужен PIVOT:
In [8]: (new3.pivot_table(index=['YrSold', 'Flag'], values=['SalePrice'], aggfunc='sum')
             .rename(columns={"SalePrice":"Summa"})
             .reset_index()
Out[8]:
   YrSold  Flag     Summa
0    2006     0  28193621
1    2006     1  29126909
2    2007     0  30848091
3    2007     1  30366686
4    2008     0  26948329
5    2008     1  26969366
6    2009     0  32986315
7    2009     1  27661736
8    2010     0  14862208
9    2010     1  16181685