text:
Q: $f:[-1,1]\to\Bbb{R}$ be continuous function, and let $g(x)=\int_{0}^{1}f(xy)dy\forall x\in[-1,1]$ The whole question is
Suppose $f:[-1,1]\to\Bbb{R}$ be continuous function and define $g(x)=\int_{0}^{1}f(xy)dy\ \forall x\in[-1,1]$. Prove that $g$ is continuous on $[-1,1]$.
I have tried it in the following manner-
Choose $\varepsilon>0$
$f$ is uniformly continuous on $[-1,1]$, so $\exists\delta>0$ such that $|f(a)-f(b)|<\varepsilon$ if $|a-b|<\delta$.
Let $x_1,x_2\in[-1,1]$, my target is to find a $\delta'>0$ such that $|g(x_1)-g(x_2)|<\varepsilon$ if $|x_1-x_2|<\delta'$.
Now choose $y\in[0,1]$, $|f(x_1 y)-f(x_2 y)|<\varepsilon$ if $|x_1y - x_2 y|<\delta$ i.e. $|y||x_1 - x_2 |<\delta$. From this I can't proceed further, how can I get a fixed $\delta'>0$ for any $y\in[0,1]$. Then I can get the required relation for $g$
 just by integrating both sides with respect to $y$ on $[0,1]$.
Thanks for assistance in advance.

A: Note that if $|x_1-x_2|<\delta$, where $\delta$ is given by the uniform continuity of $f$, then $|x_1y-x_2y|<\delta$ for all $y\in [0,1]$, since $|x_1y-x_2y|=|x_1-x_2| |y|\leq |x_1-x_2|.$


text:
Q: why copy constructor & assignment operator both are called in this case Can anybody explain me, why in my below code, where ms3 = ms1 is done,  both copy and assignment operator get called in this line. In the above mentioned line only overloaded assignment operator should get called as per my knowledge. But both the copy constructor and assignment operator are getting called. Please explain me.. why this happens?
class MyString {
private:
    char* string;
public:
    MyString(char *ptr = NULL);
    MyString(MyString &str);
    MyString &  operator =(MyString  str);
    ~MyString();
};

MyString::MyString(MyString &str) {
    printf("Copy Constructor called !!!\n");
    int len = strlen(str.string);
    string = new char[len+1];
    strcpy_s(string, len+1, str.string);
}

MyString::MyString(char* str) {
    printf("Constructor called !!!\n");
    if (str != NULL) {
        int len = strlen(str);
        string = new char[len + 1];
        strcpy_s(string, len + 1, str);
    }
    else {
        string = NULL;
    }

}
MyString & MyString::operator=(MyString str) {
    printf("Assignment Operator!!!\n");
    if (&str == this) {
        return *this;
    }

    delete[] string;
    if (&str != NULL) {
        int len = strlen(str.string);
        string = new char[len + 1];
        strcpy_s(string, len+1, str.string);
    }
    return *this;
}
MyString::~MyString() {
    printf("Destructor\n");
    delete[] string;
}

int _tmain(int argc, _TCHAR* argv[])
{
    MyString ms = "ABC";
    MyString ms1("EFG");
    MyString ms2 = ms1;
    MyString ms3;
    ms3 = ms1;
    MyString ms4 = ms3 = ms1;
    return 0;
}

A: The assignment operator takes its argument by value; the copy constructor is used to set up that argument.

A: To avoid this, your need to rewrite your assignment operator so that it takes a reference, like the copy constructor does. Also you should use const :
MyString(MyString const &str);
MyString & operator=(MyString const &str);

redpajama_set_name: RedPajamaStackExchange


text:
Q: postges_fdw покдлючение к localhost, пользователь не прошел проверку подлинности по паролю
Пытаюсь перенести данные между таблицами двух баз данных на одном postgres (12) сервере с помощью postgres_fdw.
Есть две базы source_db и dest_db, права на них - у пользователя postgres:
```
 dest_db   | postgres | UTF8      | ru_RU.UTF-8 | ru_RU.UTF-8 | =Tc/postgres         +
           |          |           |             |             | postgres=CTc/postgres
 source_db | postgres | UTF8      | ru_RU.UTF-8 | ru_RU.UTF-8 | =Tc/postgres         +
           |          |           |             |             | postgres=CTc/postgres
```
В source_db создаю сервер, маппинг роли с актуальным паролем и импортирую схему dest_schema в локальную local_dest_schema:
create extension postgres_fdw;
CREATE SERVER local_dest_srv FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'localhost', dbname 'dest_db', port '5432');
CREATE USER MAPPING FOR postgres SERVER local_dest_srv OPTIONS(user 'postgres', password 'password');
CREATE SCHEMA local_dest_schema;
IMPORT FOREIGN SCHEMA dest_schema from server local_dest_srv into local_dest_schema;

В результате - ошибка:
source_db=# IMPORT FOREIGN SCHEMA dest_schema from server local_dest_srv into local_dest_schema;
ОШИБКА:  could not connect to server "local_dest_srv"
ПОДРОБНОСТИ:  ВАЖНО:  пользователь "postgres" не прошёл проверку подлинности (по паролю)

Не подскажете, в чем может быть проблема?
Спасибо


text:
Q: SneakyJoystick - Movement by certain points/tiles I have SneakyJoystick up and running but I want to move my sprite tile by tile in a certain frequency ... I am pretty new to iphone programming and cocos2d so I don't exactly know how the whole SneakyJoystick thingy works.
I got the code from a book and again: I just want my Sprite to move like in the game Pokèmon tile by tile...
-(void)initJoystickAndButtons {
    CGSize screenSize = [CCDirector sharedDirector].winSize;
    CGRect joystickBaseDimensions =
    CGRectMake(0, 0, 128.0f, 128.0f);
    CGRect jumpButtonDimensions =
    CGRectMake(0, 0, 64.0f, 64.0f);
    CGRect attackButtonDimensions =
    CGRectMake(0, 0, 64.0f, 64.0f);
    CGPoint joystickBasePosition;
    CGPoint jumpButtonPosition;
    CGPoint attackButtonPosition;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        // The device is an iPad running iPhone 3.2 or later.
        CCLOG(@"Positioning Joystick and Buttons for iPad");
        joystickBasePosition = ccp(screenSize.width*0.0625f,screenSize.height*0.052f);
        jumpButtonPosition = ccp(screenSize.width*0.946f,screenSize.height*0.052f);
        attackButtonPosition = ccp(screenSize.width*0.947f,screenSize.height*0.169f);
    } else {
        // The device is an iPhone or iPod touch.
        CCLOG(@"Positioning Joystick and Buttons for iPhone");
        joystickBasePosition = ccp(screenSize.width*0.07f,
                                   screenSize.height*0.11f);
        jumpButtonPosition = ccp(screenSize.width*0.93f,
                                 screenSize.height*0.11f);
        attackButtonPosition = ccp(screenSize.width*0.93f,
                                   screenSize.height*0.35f);
    }

SneakyJoystickSkinnedBase *joystickBase = [[[SneakyJoystickSkinnedBase alloc] init] autorelease];
joystickBase.position = joystickBasePosition;
joystickBase.backgroundSprite =[CCSprite spriteWithFile:@"dpadDown.png"];
joystickBase.thumbSprite =[CCSprite spriteWithFile:@"joystickDown.png"];
joystickBase.joystick = [[SneakyJoystick alloc]initWithRect:joystickBaseDimensions];

leftJoystick = [joystickBase.joystick retain];
leftJoystick.isDPad = YES;
[self addChild:joystickBase];

SneakyButtonSkinnedBase *jumpButtonBase =[[[SneakyButtonSkinnedBase alloc] init] autorelease];
jumpButtonBase.position = jumpButtonPosition;
jumpButtonBase.defaultSprite =[CCSprite spriteWithFile:@"jumpUp.png"];
jumpButtonBase.activatedSprite =[CCSprite spriteWithFile:@"jumpDown.png"];
jumpButtonBase.pressSprite = [CCSprite spriteWithFile:@"jumpDown.png"];
jumpButtonBase.button = [[SneakyButton alloc]initWithRect:jumpButtonDimensions];
jumpButton = [jumpButtonBase.button retain];
jumpButton.isToggleable = NO;
[self addChild:jumpButtonBase];
SneakyButtonSkinnedBase *attackButtonBase =[[[SneakyButtonSkinnedBase alloc] init] autorelease];
attackButtonBase.position = attackButtonPosition;
attackButtonBase.defaultSprite = [CCSprite spriteWithFile:@"handUp.png"];
attackButtonBase.activatedSprite = [CCSprite spriteWithFile:@"handDown.png"];
attackButtonBase.pressSprite = [CCSprite spriteWithFile:@"handDown.png"];
attackButtonBase.button = [[SneakyButton alloc]initWithRect:attackButtonDimensions];
attackButton = [attackButtonBase.button retain];
attackButton.isToggleable = NO;
[self addChild:attackButtonBase];

> }

    > -(void)applyJoystick:(SneakyJoystick *)aJoystick toNode:(CCNode *)tempNode forTimeDelta:(float)deltaTime{
    >     CGPoint scaledVelocity = ccpMult(aJoystick.velocity, 44.0f); // 1
    >     CGPoint newPosition = ccp(tempNode.position.x + scaledVelocity.x * deltaTime,tempNode.position.y + scaledVelocity.y * deltaTime);
    >     [tempNode setPosition:newPosition];
    >     if (jumpButton.active == YES) {
    >         CCLOG(@"Jump button is pressed.");
    >         if (attackButton.active == YES) {
    >             CCLOG(@"Attack button is pressed.");
    >         } }
    >      }

>

    > # pragma mark -
    > # pragma mark Update Method

> -(void) update:(ccTime)deltaTime {
>     [self applyJoystick:leftJoystick toNode:dude
>            forTimeDelta:deltaTime];
>      }

A: I did something similar for my game. There are many steps and cannot go much into detail.
First you need to know when is the joystick being used.
Second you need to interpet the direction of the joystick. For a game like Pokemon, you only need to check for up/down/right/left directions. It is possible to access the degrees of the joystick. Simply interpret the degrees like "if degrees are between -45 to 45, it means the joystick is mainly facing right" etc.
Third you will have to unlink the joystick from your player object. That tutorial, somewhere, makes you link both of them so that the joystick will automatically move the player. You have to undo that.
Fourth make up a schedule somewhere in your scene. The schedule will interpret the joystick direction (if it is being used), and will run a CCMoveBy action on the player. If the joystick directs to the right and the map's tile size is 32, then the CCMoveBy movement parameter would be (32,0). Remember to not run a nother action if the player is already running one.
There are many details and so much to polish. You better try to ask each thing individually instead of everything in one shot.


text:
Q: Wireless: (if harmful) is a bigger WiFi antenna a bigger health hazard?
This question has been reworded to not assume that radio waves are
  harmful to human beings.

The official message claims there is no real danger to human health in wireless radiations, like the WiFi ones.
But, as long as such official message has been the same for decades concerning to things like tobacco or even radioactivity, many people have fears about the possibility.
Such people would prefer, when possible, to deploy wireless systems that will potentially emit a lesser perturbation to their bodies.
So, for those that have decided (I am one of them) to believe that:

*

*A radio wave is potentially harmful.

*WiFi devices emit radio waves.

*A WiFi device with more power (say a 2000mW wireless device instead of a 200mW one) could potentially damage more the health of persons who are nearby.

Can we say the same about antennas? Is a higher gain antenna (more dB/dBi/dBm) more (potentially) troublesome for the health of people?
As long as there are probably many computing-related persons that think the Prudence Directive must be kept for new technologies, answers to this question could be worthful for a computer technical.

Further info (due to documentation requests from the forum) that
  points to relationship between radio waves and human diseases
  (hard to find googling as for today, on July 2015... why could it
  be?):

*

*Leif G. Salford et al., "Nerve Cell Damage in Mammalian Brain After Exposure to Microwaves from GSM Mobile Phones," Environmental Health
  Perspectives 111, no. 7 (2003): 881-883.

*Allan H. Frey, Sondra R. Feld and Barbara Frey, "Neural Function and Behavior," Annals of the New York Academy of Sciences 247 (1975):
  433-439.

*Allan H. Frey, "Evolution and Results of Biological Research with Low-Intensity Nonionizing Radiation," in Modern Bioelectricity , ed.
  Andrew A. Marino (New York: Dekker, 1988), 785-837, at 809-810.

*California EMF Program, The Risk Evaluation: An Evaluation of the Possible Risks From Electric and Magnetic Fields (EMFs) From Power
  Lines, Internal Wiring, Electrical Occupations and Appliances (2002),
  app. 3.

*Örjan Hallberg and Olle Johansson, "1997 - A Curious Year in Sweden," European Journal of Cancer Prevention 13, no. 6 (2004):
  535-538.

*Örjan Hallberg and Olle Johansson, "Does GSM 1800 MHz Affect the Public Health in Sweden?" in Proceedings of the 3rd International
  Workshop Biological Effects of EMFs," Kos, Greece, October 4-8, 2004,
  361-364.

*Örjan Hallberg and Olle Johansson, "Cancer Trends During the 20th Century," Journal of Australian College of Nutritional and
  Environmental Medicine 21, no. 1 (2002): 3-8.

*David E. Janes Jr., "Radiofrequency Environments in the United States," in 15th IEEE Conference on Communication, Boston, MA, June
  10-14, 1979, vol. 2, 31.4.1-31.4.5.

*(Spanish): "Salud y Antenas Móviles - El experimento biológico más grande de la historia" - Rebelion.Org

*(Portuguese): Censored article "Saude e Antena Telemovel" at Planetary Association for Clean Energy, Volume 10, number 1, pages 5-6
  .

A: If we don't have to back up our claims with evidence, we can say whatever we want. So sure, we can say: "It is clear that bigger antennas are more dangerous."

A: "Can we say the same about antennas?" - NO, it is just a piece of metal, it does not radiate on its own.
"Is a better (more gain) antenna (more dB/dBi/dBm) more (potentially) troubleous for the health of people?" - It depend where you stay. If you are behind of focal focus - then there practically no any radiation at all, but if one stay in direction of focal focus - then he/she will get more radiation than a simple omni (piece of stick) antenna that radiate almost in all direction.
BTW, Do you use a cell phone ? It radiate much much more than Wi-Fi, especially when you far from cell tower. Try also to barrow oscilloscope and touch central lead - you will see that electrical field all around your home, because all your home is powered and since it is AC with 60 Hz it radiate much more than Wi-Fi, especially closer to wires with big loading.
Ahh, almost forget, if you aren't in a rural area, - do you know that power meter outside of your home has embedded cell phone unit that makes "smart power grid", it radiates too much more than Wi-Fi...
IMHO, you can't escape from "civilization" especially just eliminating a Wi-Fi only.


text:
Q: Determine likelihood that a list of N items contains no negative results after examining X items I have a large (N) list of results from a process that is either positive or negative.  After examining X of them and receiving only positive results, how certain can I be that the list only contains positive results (with probability P)?
Context: I'm processing the results (between several thousand and several billion) of a process and am given a list of values that take a few seconds each to evaluate as passing/failing.  I only need to be reasonably certain that everything passed to pass the batch for most jobs.  For some jobs, 100% certainty is necessary, and they'll all need to be checked.  For the others, how many do I need to check to be P% certain that there are no fails?


text:
Q: How to end node js execution in case of a API usage error I am currently writing a node js library. Now I came up with the question what would be the best approach to indicate a usage error by the programmer.
For example if I got the following function in my public API:
function doSomething(aNumber) {
    // ...
}

and I need to make sure that aNumber actually is a number, what way of error handling should I go if the API user passes a parameter that is not.
By convetion functions in node should return an Error object if an error occurs. But in my case this is no error the programmer should catch.
So my question is what would be the most appropriate way to maybe simply "end" the program with an error message, telling the programmer that he did not use my API in the correct way.

A: I would simply do the following:
console.log("Incorrect api usage.");
process.exit(-1);

You may want to wrap that in a helper function to make the calls simpler...


text:
Q: Is it possible to run xunit Test cases in Visual Studio Professional 2012 I have tried out many options like installing NuGet Packages for X Unit Test Runner, cleaning the solution. But nothing worked. I had installed Unit Test generator for Visual Studio. I could be able to generate test methods using Nunit Framework in my Visual Studio. But in Test Explorer, no test results are displaying. Even no updates.
On the other hand, MSTest is working fine. The list of test methods I had generated is displaying in Test Explorer and able to run the tests.
So, is it possible to run xunit test methods in Visual Studio 2012
Professional Edition?


text:
Q: How to get mouse position from a iframe that contains a page? I want to get mouse position from an IFRAME that contains a HTML page .
But before Iframe HTML page load , this code work nice .
After loading Iframe HTML page , this code don't work !
Here is my code :
    <!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta charset="utf-8" />
<style>
#divid {
  height: 600px;
  width: 300px;
  border: 2px solid black;
  transform: scale(0.5, 0.5);
}

</style>
</head>
<body>

<iframe id="iframe" src="http://www.google.com/" >
</iframe>

<script
              src="http://code.jquery.com/jquery-3.3.1.js"
              integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
              crossorigin="anonymous"></script>
<script>
var iframepos = $("#iframe").position();

$('#iframe').contents().find('html').on('mousemove', function (e) {
    var x = e.clientX + iframepos.left;
    var y = e.clientY + iframepos.top;
    console.log(x + " " + y);
})
    </script>

</body>
</html>

can you help me please ?


text:
Q: Why is rails not inserting data during create, only nil? (New scaffold) I had an annoying problem with a freshly generated scaffold. Everything would run nicely, but while I could enter data, everytime I tried to save he would commit nil successfully. For all fields.
Looks like this:
Started POST "/spraches" for 127.0.0.1 at 2012-08-26 23:34:03 +0200
Processing by SprachesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"nMf1+rBegI9BKoSAekzq8iLPQPAHpiiPk2DlmhEQxsQ=", "sprache"=>{"name"=>"23", "level"=>"23", "zertifikat"=>"124", "zertifikat_anders"=>"213", "zertifikat_note"=>"f23"}, "commit"=>"Create Sprache"}
  [1m[36m (1.0ms)[0m  [1mBEGIN[0m
  [1m[35mSQL (29.0ms)[0m  INSERT INTO "spraches" ("created_at", "level", "name", "updated_at", "zertifikat", "zertifikat_anders", "zertifikat_note") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["created_at", Sun, 26 Aug 2012 21:34:03 UTC +00:00], ["level", nil], ["name", nil], ["updated_at", Sun, 26 Aug 2012 21:34:03 UTC +00:00], ["zertifikat", nil], ["zertifikat_anders", nil], ["zertifikat_note", nil]]
  [1m[36m (1.0ms)[0m  [1mCOMMIT[0m
Redirected to http://localhost:3000/spraches/1
Completed 302 Found in 35ms (ActiveRecord: 31.0ms)

The reason become obivous to me after looking at the code in detail: I named my table in German (Sprache -> Language) and Rails tried to set it to plural. However, the controller only had it in the singular form.
@sprach = Sprache.new(params[:sprach])

I addded an "e" in the params to match the incoming code. Works.

A: The reason become obivous to me after looking at the code in detail: I named my table in German (Sprache -> Language) and Rails tried to set it to plural. However, the controller only had it in the singular form.
@sprach = Sprache.new(params[:sprach])

I addded an "e" in the params to match the incoming code. Works.


text:
Q: Is there a way to unlock features right off the bat? In Cities: Skylines, some features are locked by default, like the fire department, dense zoning, and districts. You need to reach a certain population to unlock them. Is there a way to unlock these from the start?

A: Cities: Skylines ships with three "mods" in the game.
They are:

*

*Hard Mode - More challenge for experienced players

*Unlimited Money - Money never runs out

*Unlock All - Progression milestones are always unlocked

You want the third one. To enable this mod, from the main menu, go to Content Manager. In the left panel select the Mods category. Then, click the On/Off checkbox under Unlock All.
It should look like this:


text:
Q: In texinfo, how to specify a bash single quote? I am writing a package using the GNU build system. The documentation hence is in the texinfo format. As a result, executing make converts the texinfo file into the info format, and executing make pdf automatically produces a pdf file.
In the texinfo file, I have something like this:
@verbatim
awk '{...}' data.txt
@end verbatim

However, in the pdf, the "basic" single quotes (U+0027) in the awk command above are transformed into "curvy" single quotes (U+2019) so that, if one does a copy-paste of the command from the pdf into a terminal, bash complains ("syntax error"). This forces the user to edit the command he just copy-pasted. Same problem occurs if I replace @verbatim by @example. I searched the texinfo manual but couldn't find a way to specify apostrophes. I am using texinfo version 5.2.

A: Karl Berry (via the bug-texinfo mailing list) told me to add 2 lines to my texi file (more info):
@codequoteundirected on
@codequotebacktick on

as well as add the latest version of texinfo.tex to my package.


text:
Q: Visual Studio 2015 CE vs. XCode 6.4 - Different Compile-time errors I usually use both above mentioned IDEs but I have noticed that this little code (below) in VS 2015 CE compiles and works, while in XCode it returns me an error:
#include <iostream>
#include "std_lib_facilities.h"

char* findx(const char* s, const char* x)
{
    int count_s = 0;

    while (s[count_s] != 0)
    {
        int count_x = 0;
        while (x[count_x] != 0)
        {
            if (s[count_s] == x[count_x])
            {
                cout << "Found match " << x[count_x] << " at X[" << count_x
                << "] with " << s[count_s] << " at S[" << count_s
                << "]" << endl;
                return 0;
                break;
            }
            ++count_x;
        }
        ++count_s;
    }

    cout << "Match " << *x << " not found" << endl;
    return 0;
}

int main()
{
    char* p = new char[6]{ "Zorro" };
    char* p1 = new char[4]{ "Zio" };
    findx(p, p1);
    delete[] p;
    delete[] p1;
    keep_window_open();
    return 0;
}

The error I got in XCode are:
char* p = new char[6]{ "Zorro" }; // Initializer-string for char array is too long
char* p1 = new char[4]{ "Zio" }; // Initializer-string for char array is too long

Thank you!
P.S. What do you feel to advice? I prefer XCode but I am not an experienced programmer so I trust you!
EDIT


text:
Q: how to group data entries with same id into a single entry? I am a beginner in MySQL as well as Typeorm. So my query returns data with the same ID like:
[
  {
    id: "1",
    name: "john",
    place: "San Francisco"
  },
  {
    id: "1",
    name: "john",
    place: "Mumbai"
  }
]

Now I want data where there is an entry with a unique id, let's say:
[
 {
  id: "1",
  name: "john",
  place: ["San Francisco", "Mumbai"]
  }
]

can someone help me, how do I groupBy to achieve this result?

A: I doubt that you can get an array, but you could use group_concat.
https://mariadb.com/kb/en/group_concat/
The query would be something like
SELECT `id`, group_concat(`name`), group_concat(`place`) FROM <table_name> GROUP BY `id`

if the name doesn't need to be concatenated
SELECT `id`, `name`, group_concat(`place`) FROM <table_name> GROUP BY `id`

And then in your code you can split that string in array. Either use ',' which I think it's the default separator or use a custom one like '!#$!'

A: With MySQL you can use GROUP_CONCAT:
SELECT
  id, name, GROUP_CONCAT(place)
FROM
  <table_name>
GROUP BY
  id

With TypeScript you can use Array.prototype.reduce():

const data = [{id: "1",name: "john",place: "San Francisco"},{id: "1",name: "john",place: "Mumbai"}]

const dataHash = data.reduce((a, { id, name, place }) => {
  a[id] = a[id] || { id, name, place: [] }
  a[id].place.push(place)
  return a
}, {})
const result = Object.values(dataHash)

console.log(result)


text:
Q: how to get values from class to jsp using arraylist? hi i have some problem in retriving data from database using arraylist.i am only able to get the last entry of the column.here is my code any help is appreciated.thank you in advance.
this is where iam fetching data from database
VariableIntialization location = new VariableIntialization();
            HttpSession session = request.getSession();
          String sql = "SELECT * FROM country";
        Database db= new Database();
                          PreparedStatement pst = db.getConnection().prepareStatement(sql);
                         ResultSet i = pst.executeQuery();

                            while (i.next()) {
                                String country_id = i.getString(1);
                                String country = i.getString(2);
                            ArrayList<String> countries = new ArrayList<String>();
                                countries.add(country);
                                location.setcountry(countries);
                                location.setcountry_id(country_id);
                            }
    session.setAttribute("deshopa_country", location);
                response.sendRedirect("admin/stateadd.jsp");

here is my .java class where data goes in to..
package requirementlogic;

import java.util.ArrayList;

public class VariableIntialization {
    private ArrayList<String> content =new ArrayList<String>();
        public void setcountry(ArrayList<String> content)
                    {
                        this.content = content;

                    }
                 public ArrayList<String> getcountry() { return content; }
}

here is my jsp page where i want to display data
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
 <%@ page import = "requirementlogic.*"  %>
 <%@ page import = "java.util.ArrayList" %>
      <%VariableIntialization ds_country =(VariableIntialization)session.getAttribute("deshopa_country"); %>

    <% ArrayList<String> desham =new ArrayList<String>();
            desham = ds_country.getcountry();

<form method="get" action="../State" name="location" id="location">
<%if(session.getAttribute("deshopa_country") != null){ %>

<select name="country_ref" id="country_ref" class="clear">
<%for(int i=0; i<desham.size() ;i++){ %>
<option><%=desham.get(i)%></option>

<%} %>
</select>

<%} %>
</form>

A: here every time you are making a new list of countries since its been added inside a loop declare it outside of your loop so that the result set is added to the list.Since u are adding it inside u are always getting a new list with an entry of only one country


text: Q: Malayalam font embed in adobe flash professional cs5 I want to create malayalam supported font using adobe flash professional cs5, in embed option i can choose malayalam font family dropdown but character range is not available for malayalam


text:
Q: using scanf to parse hh:mm:ss, strange error with some inputs The following code is used to parse times like 07:04:51:
#include <stdio.h>

int main() {
    int hh, mm, ss;
    scanf("%i:%i:%i\n", &hh, &mm, &ss);
    printf("%i:%i:%i\n", hh, mm, ss);
}

Some times can be parsed and other ones don't:
$ echo 07:04:51 | ./test.exe
7:4:51
$ echo 08:04:51 | ./test.exe
0:0:32767
$ echo 09:04:51 | ./test.exe
0:0:32766
$ echo 10:04:51 | ./test.exe
10:4:51
$ echo 11:09:10 | ./test.exe
11:0:32764

What is the reason?
ideone

A: In this case it would be better to use %d instead of %i. With %i, if the value has a leading zero, the value will be read as an octal value (base 8). 08 and 09 are not valid octal values.
scanf will return the number of items successfully scanned. use
if ( scanf("%d:%d:%d", &hh, &mm, &ss) == 3)

to verify that three items were scanned.


text:
Q: ¿cómo sustitur valores que cumplan la condición de otro data frame? Estoy trabajando con datos de la ENIGH 2018 y en una base de datos hay una variable llamada "entidad" conformada por 5 dígitos, los primeros dos correspondientes al estado y los restantes al municipio.

En otro data frame están los nombres que le corresponden a cada dato número.

Sustituí el código con su nombre correspondiente usando la fórmula "BUSCARV" en excel pero quisiera saber como se hace en R studio.

A: En la jerga de base de datos, esto se lo conoce como un left join, es decir las filas de una tabla principal, mas las coincidentes por una o más columnas, de otra secundaria. Considerando que tuvieras dos data.frames como estos:
read.table(text="ubica_geo Gasto
1001 98323225
1002 5856263.28
1003 1091044.08
1004 741336.48
1005 3511879.02
1006 748698.74", header=TRUE, stringsAsFactor=FALSE) -> df1

read.table(text="codigo mun
0 'No aplica No aplica'
1000 'Aguascalientes No identificado'
1001 'Aguascalientes Aguascalientes'
1002 'Aguascalientes Asientos'
1003 'Aguascalientes Calvillo'
1004 'Aguascalientes Cosío'
1005 'Aguascalientes Jesús María'
1006 'Aguascalientes Pabellón de Arteaga'
1007 'Aguascalientes Rincón de Romos'", header=TRUE, stringsAsFactor=FALSE) -> df2

Dónde la relación está dada por ubica_geo en uno y codigo en el otro, puedes hacer lo siguiente:
1. Usar R base y la función merge():
merge(x = df1, y = df2, by.x = "ubica_geo", by.y = "codigo", all.x = TRUE)

2. Usar dplyr/tidyverse y el verbo left_join()
library("tidyverse")

df1 %>%
  left_join(df2, by = c("ubica_geo" = "codigo"))

En ambos caso la salida sería algo así:
  ubica_geo      Gasto                                mun
1      1001 98323225.0      Aguascalientes Aguascalientes
2      1002  5856263.3            Aguascalientes Asientos
3      1003  1091044.1            Aguascalientes Calvillo
4      1004   741336.5               Aguascalientes Cosío
5      1005  3511879.0         Aguascalientes Jesús María
6      1006   748698.7 Aguascalientes Pabellón de Arteaga

Para mayor información: ¿Cómo resuelvo operaciones básicas con datos al estilo SQL?


text:
Q: How do I redirect the output of a Perl script to another file in %TEMP%? I need a Perl script on Windows which deletes the newline characters from a file and merges all the lines into one line and then writes into another file into the %temp% directory on a Windows system. For example, this script is to delete newlines and create a single line and write into another file in %TEMP%.
I have script which deletes the newlines but the output goes to STDOUT. I am not able to create a file in %TEMP% and redirect the output to that file.
Following is my script which is not working:
my $inFile = $ARGV[0];
$ENV{'TEMP'} = 'C:\\TEMP';

if ($inFile eq "") {
    print "Input file is missing\n";
    print "perl file_into_one_line.pl <input fil>\n";
    exit 0;
}

open(INFILE, "< $inFile") || die "$0, FEJL: can't open $inFile: $!";
foreach (<INFILE>) {
    chomp;
    if (eof()) {    # check for end of last file
        print "$_\n";
    } else {
        open FILE, ">$ENV{'TEMP'}//temp//tst.txt" or die;
        print FILE "${_}$separator";
    }
}

close(INFILE);

A: Note that %TEMP% is DOS syntax for accessing a environment variable. You can access the value of environment variables inside perl through the %ENV hash like so:
$ENV{k}

where k is a string expression that gives the name of the variable. Try this in your windows command line:
perl -e "print $ENV{'TEMP'};"

You should be able to do the rest from here on.

A: The script should be:
my $separator = " "; # I think you should have this some where~~~

my $inFile = $ARGV[0];
$ENV{'TEMP'} = 'C:\\TEMP';

if ($inFile eq "") {
    print "Input file is missing\n";
    print "perl file_into_one_line.pl <input fil>\n";
    exit 0;
}

open(INFILE, "< $inFile") || die "$0, FEJL: can't open $inFile: $!";
open FILE, ">$ENV{'TEMP'}\\tst.txt" or die $!;
foreach (<INFILE>) {
    chomp;
    print FILE "${_}$separator";
}

print FILE "\n";

close(INFILE);
close(FILE);


text:
Q: How to output invalid input on character limit and a space switch case? This is the assignment I got, which is based on C++ program to Convert Letters into a Phone Number.
However, my lecturer ask for added details including:

*

*Insert alphabet as an input

*The entire alphabet to input is 15, including "space"; if it exceeds the count, display an appropriate message.

*Program will display the digit as the representation of the alphabet value, as a phone number.

*Digit for the alphabet is from 2 to 9; each digit per alphabet's representation refers to the program provided.

*1 is for "space."

*Add a sentinel loop in the program. Control by the user entering digit "0" to stop the program from looping

Unfortunately, I've yet to figure out how to implement number 2 and 5. Here's my current code:
#include <iostream>

using namespace std;

int main()
{
    char letter;
    int counter = 0;

    cout << "Enter Name" << endl;

    while (cin.get(letter) && counter < 15) {

        if (letter == '0') {
            break;
        }

        if (letter != ' ' && letter >= 'A' && letter <= 'z') {
            counter++;
            if (letter > 'Z') {
                letter = (int)letter-32;
            }

            if (counter < 15); {
                cout << "";
            }

            if (counter > 15); {
                cout << "Invalid Input" << endl;
                break;
            }

            switch (letter) {
                case ' ':
                case '\n':
                case '\t':
                    cout << "1";
                    break;
                case 'A':
                case 'B':
                case 'C':
                    cout << "2";
                    break;
                case 'D':
                case 'E':
                case 'F':
                    cout << "3";
                    break;
                case 'G':
                case 'H':
                case 'I':
                    cout << "4";
                    break;
                case 'J':
                case 'K':
                case 'L':
                    cout << "5";
                    break;
                case 'M':
                case 'N':
                case 'O':
                    cout << "6";
                    break;
                case 'P':
                case 'Q':
                case 'R':
                case 'S':
                    cout << "7";
                    break;
                case 'T':
                case 'U':
                case 'V':
                    cout << "8";
                    break;
                case 'W':
                case 'X':
                case 'Y':
                case 'Z':
                    cout << "9";
                    break;
                default:
                    cout << "Invalid input";
                    break;
            }
        }
    }

    return 0;
}

I've tried googling, yet there's barely answers, especially the switch case space part!

A: #include<iostream>
using namespace std;

int main()
{
    string phone;
    int counter=0;
    cout<<"Enter Name:";
    getline(cin,phone);
    counter = phone.length();
    if(counter>15) {
        cout<<"Invalid Input"<<endl;
        return 0;
    }
    for(int i=0;i<phone.length();i++)
    {
        char letter = phone[i];
        switch(letter)
        {
            case ' ': cout<<"1 "; break;

            case 'A':
            case 'B':
            case 'C':
            if(letter=='A') cout<<"2 ";
            else if(letter=='B') cout<<"22 ";
            else if(letter=='C') cout<<"222 "; break;

            case 'D':
            case 'E':
            case 'F':
            if(letter=='D') cout<<"3 ";
            else if(letter=='E') cout<<"33 ";
            else if(letter=='F') cout<<"333 "; break;

            case 'G':
            case 'H':
            case 'I':
            if(letter=='G') cout<<"4 ";
            else if(letter=='H') cout<<"44 ";
            else if(letter=='I') cout<<"444 "; break;

            case 'J':
            case 'K':
            case 'L':
            if(letter=='J') cout<<"5 ";
            else if(letter=='K') cout<<"55 ";
            else if(letter=='L') cout<<"555 "; break;

            case 'M':
            case 'N':
            case 'O':
            if(letter=='M') cout<<"6 ";
            else if(letter=='N') cout<<"66 ";
            else if(letter=='O') cout<<"666 "; break;

            case 'P':
            case 'Q':
            case 'R':
            case 'S':
            if(letter=='P') cout<<"7 ";
            else if(letter=='Q') cout<<"77 ";
            else if(letter=='R') cout<<"777 ";
            else if(letter=='S') cout<<"7777 "; break;

            case 'T':
            case 'U':
            case 'V':
            if(letter=='T') cout<<"8 ";
            else if(letter=='U') cout<<"88 ";
            else if(letter=='V') cout<<"888 "; break;

            case 'W':
            case 'X':
            case 'Y':
            case 'Z':
            if(letter=='W') cout<<"9 ";
            else if(letter=='X') cout<<"99 ";
            else if(letter=='Y') cout<<"999 ";
            else if(letter=='Z') cout<<"9999 "; break;

            default:
            cout<<"Invalid Input"<<endl;
        }
    }
}


text:
Q: 400 Bad request when using Get-IntuneConditionalAccessSetting within the Microsoft.Graph.Intune module It appears that the other get commands for Intune are working, such as compliance and configuration policies but when I attempt to use the Get-IntuneConditionalAccessSetting command I always get the following:
Get-IntuneConditionalAccessSetting : 400 Bad Request
{
  "error": {
    "code": "BadRequest",
    "message": "{\r\n  \"_version\": 3,\r\n  \"Message\": \"An error has occurred - Operation ID (for customer support): 00000000-0000-0000-0000-000000000000 -
Activity ID: 66a698b9-a2ae-4559-ad06-9a22fd2d69f7 - Url:
https://fef.amsub0102.manage.microsoft.com/StatelessOnboardingService/deviceManagement/conditionalAccessSettings?api-version=2018-08-13\",\r\n
\"CustomApiErrorPhrase\": \"\",\r\n  \"RetryAfter\": null,\r\n  \"ErrorSourceService\": \"\",\r\n  \"HttpHeaders\": \"{}\"\r\n}",
    "innerError": {
      "request-id": "66a698b9-a2ae-4559-ad06-9a22fd2d69f7",
      "date": "2020-04-30T08:08:24"
    }
  }
}
At C:\Data_TempFilesOnly\PowerShell\ConditionalAccess.ps1:131 char:26
+             $IntuneObj = Get-IntuneConditionalAccessSetting | ForEach ...
+                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ConnectionError: (@{Request=; Response=}:PSObject) [Get-DeviceManag...lAccessSettings], HttpRequestException
    + FullyQualifiedErrorId : PowerShellGraphSDK_HttpRequestError,Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets.Get_DeviceManagement_ConditionalAccessSettings

I have tried the command on its own and it produced the same error so I don't think its the actual code and is specific to the command. Any suggestions?

A: https://graph.microsoft.com/v1.0/deviceManagement/conditionalAccessSettings is for on-premise Exchange Conditional Access, so returns error 400 if on-prem exchange isn't configured.
If you're looking for AzureAD Conditional Access, use https://graph.microsoft.com/beta/conditionalAccess/policies

A: {
    "error": {
        "code": "Forbidden",
        "message": "{\r\n  \"_version\": 3,\r\n  \"Message\": \"Application is not authorized to perform this operation. Application must have one of the following scopes: DeviceManagementServiceConfiguration.Read.All, DeviceManagementServiceConfig.Read.All, DeviceManagementServiceConfiguration.ReadWrite.All, DeviceManagementServiceConfig.ReadWrite.All - Operation ID (for customer support): 00000000-0000-0000-0000-000000000000 - Activity ID: afb69295-20c4-424e-b55b-15274fd6ab1a - Url: https://fef.amsub0102.manage.microsoft.com/StatelessOnboardingService/deviceManagement/conditionalAccessSettings?api-version=2018-08-13\",\r\n  \"CustomApiErrorPhrase\": \"\",\r\n  \"RetryAfter\": null,\r\n  \"ErrorSourceService\": \"\",\r\n  \"HttpHeaders\": \"{}\"\r\n}",
        "innerError": {
            "request-id": "afb69295-20c4-424e-b55b-15274fd6ab1a",
            "date": "2020-04-30T09:29:01"
        }
    }
}
If this is a permissions problem how do I add the permissions to this application?


text:
Q: test responsebody with Jest and supertest I have a simple express http server that returns "Hello worl" when issuing a get to /
And I have the following test:
import request from 'supertest';
import app from '../app/app';

test('test http server', async () => {
  const res = await request(app).get('/')
  expect(res.body).toEqual('Hello world');
});

The test fails like this:
● test http server
expect(received).toEqual(expected)
Expected: "Hello world"
Received: {}
   7 |   const res = await request(app).get('/')
   8 |
>  9 |   expect(res.body).toEqual('Hello world');

How can I get the response.body as text to check it?

A: it seems like then returning only text (no json) you have yo use res.text, like this:
test('test http server', async () => {
  const res: request.Response = await request(app).get('/')

  expect(res.type).toEqual('text/html');
  expect(res.text).toEqual('Hello world');
});

On the other hand, when testing an endpoint that returns json I can do like this:
test('test valid_cuit with a valid case', async () => {
  const cuit: string = '20-24963205-9'
  const res: request.Response = await request(app).get(`/api/valid_cuit/${ cuit }`)

  expect(res.type).toEqual('application/json')
  expect(res.body.cuit).toEqual(cuit)
  expect(res.body.isValid).toBe(true)
});


text:
Q: Confusion with city/country when bringing database to third normal form I'm trying to normalize a table and bring it in the third-normal-form, but I'm confused about this case:
Take this simple table:
stores
-------

id   name   type    city    country

Is country transitively dependent on id via city? I rushed to say yes, but then I thought the a city with the same name might exist on another country. Does that mean this table is in 3rd normal form, or is there something that needs to be amended?

A: Interesting question.  You're right, country doesn't depend on city (e.g. 'Paris' isn't sufficient to determine the country - is it France or Texas, USA?)
The city column on its own doesn't represent the domain we want to relate, but if the combination of city and country does then I would consider (city, country) to be a composite value, similar to how a date is a composite of (day, month, year).  That would mean the relation is in 3NF having 3 FDs: id->name, id->type and id->(city,country), since the dependency (city,country)->country is considered trivial.  Practically, I would consider introducing a surrogate key in this case.
If the combination of city and country isn't unique, then we still have a 3NF table with FDs id->name, id->type, id->city and id->country and no dependency between the last two.

A: I'd say city and country need a separate table. Think that cities can change their name (India is still renaming cities: Bombay to Mombai happened years ago but it seems that this is still happening). Also Scotland recently had a referendum to remove themselves from the UK; they voted 'stay', but the issue seems far from over.
So I'd put city/country in a separate table. I might even put them in two separate tables, but unless you had some functionality (e.g. tax calculations) dependant on the country I'd probably stick to one.


text:
Q: How to programmatically add new crontab file without replacing previous one I am working on a small home automation project using raspberry pi (OS -Raspbian).
I want to know how to add more than one crontab file using python-crontab module without replacing the previous entries in crontab -e?
I want to programatically (without manually going to crontab -e and adding the files there) schedule two python scripts - first script executes after every 5 minute and another executes after every 2 min.
I was successfully able to schedule first script using python-crontab module
but when I scheduled second script, it replaced the first one in crontab -e.
So how to schedule the new crontab file without replacing the previous one ?
If there is another way of crontab scheduling please do suggest with an example code :)
Note:- I want to schedule python scripts in crontab using python scripting only not manually adding the files at crontab -e.

A: If you want to write a script to add entries in cron (without using the text editor via crontab -e), it would be something like:

*

*run crontab -l to a temporary file

*check if your latest command is already in the file.  If so, stop.

*append the latest command to the temporary file

*run crontab with the temporary file as a parameter, to replace the scheduled commands

For reference:

*

*crontab(1)- maintain crontab files for individual users

*crontab(5) - tables for driving cron


text:
Q: Searching for element in a list I have a list as such:
$DistrictCodes = "EA,BC,OC,NC,ME,RA,CM,NE";

I am trying find nth value in the list whose value equals "ME".
So here is what I do:
$Mydistrict = "ME";
$DistrictCodes = "EA,BC,OC,NC,ME,RA,CM,NE";
$MyDistrictArray = array($DistrictCodes);
$MyDisPos = array_search($Mydistrict, $MyDistrictArray);
echo "MyDisPos = $MyDisPos
";

However, it is not working? Why?
What I need is to figure out which element of the list has a value of ME and come up with 0,1,2,3,4,5,6 or 7.

A: You were almost there, to convert $DistrictCodes to an array you can use explode.
<?php

$Mydistrict = "ME";
$DistrictCodes = "EA,BC,OC,NC,ME,RA,CM,NE";
$MyDistrictArray = explode(',', $DistrictCodes);
$MyDisPos = array_search($Mydistrict, $MyDistrictArray);
echo "MyDisPos = $MyDisPos
";

// MyDisPos = 4

http://3v4l.org/DYV0K

A: You do not need to convert this into array, in PHP we have this awesome function that represents search from a string: http://php.net/manual/en/function.strpbrk.php
<?php

$Mydistrict = "ME";
$DistrictCodes = "EA,BC,OC,NC,ME,RA,CM,NE";
$output = strpbrk($Mydistrict, $DistrictCodes);

echo $output;
//output-> ME

http://3v4l.org/ah1h8

A: My 5 pences :)
$Mydistrict = "ME";
$DistrictCodes = "EA,BC,OC,NC,ME,RA,CM,NE";

$MyDisPos = strpos($DistrictCodes,$Mydistrict) / 3;
echo "MyDisPos = $MyDisPos
";


text:
Q: Slot on list widget item data object never called (in PyQt 5.7) In PyQt 5.5 the following code worked, but not so in PyQt 5.7 (the list shows 'example' rather than 'new example', and indeed debugging shows that the slot is never hit). Does anyone know what is wrong with it:
from PyQt5.QtWidgets import QListWidgetItem, QListWidget, QApplication
from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal, Qt

class MyListItemData(QObject):
    def __init__(self, list_widget_item, obj):
        super().__init__()
        self.list_widget_item = list_widget_item
        obj.sig_name_changed.connect(self.__on_list_item_name_changed)

    # @pyqtSlot(str)
    def __on_list_item_name_changed(self, new_name: str):
        self.list_widget_item.setText(new_name)

class Data(QObject):
    sig_name_changed = pyqtSignal(str)

class SearchPanel2(QListWidget):
    def __init__(self, parent=None):
        QListWidget.__init__(self, parent)
        obj = Data()
        hit_item = QListWidgetItem('example')
        hit_item.setData(Qt.UserRole, MyListItemData(hit_item, obj))
        self.addItem(hit_item)
        obj.sig_name_changed.emit('new_example')

app = QApplication([])
search = SearchPanel2()
search.show()
app.exec

Although probably not the way this was supposed to be done, in PyQt 5.5 it was an acceptable workaround for a PyQt 5.5 bug (that prevented us from simply deriving from QListWidgetItem so the item could be directly connect to signals).
Post-answer edit
After Ekhumoro answered, I was confronted with a harsh reality: this fixed the example code posted, but not my app, because my app was doing exactly what the solution said to do. So I revisited: in the real app, the items are created later, and the signal for name change is emitted later. Therefore a better minimal example to reproduce my problem would have had the following:
class SearchPanel2(QListWidget):
    def __init__(self, obj, parent=None):
        QListWidget.__init__(self, parent)

        hit_item = QListWidgetItem('example')
        data = MyListItemData(hit_item, obj)
        hit_item.setData(Qt.UserRole, data)  # slot not called

        self.addItem(hit_item)
        # self.data = data

    def emit(self):
        obj.sig_name_changed.emit('new_example')

app = QApplication([])
obj = Data()
search = SearchPanel2(obj)
search.show()
QTimer.singleShot(2000, search.emit)
app.exec()

assert search.item(0).text() == 'new_example'

This fails assertion. The assertion passes if data is kept by strong reference (uncomment last line of init). So it is likely that setData() keeps only a weak reference to its second argument, causing data to get deleted at end of init unless it is stored somewhere.

A: There seems to be some kind of garbage-collection issue. Try this instead:
    hit_item = QListWidgetItem('example')
    data = MyListItemData(hit_item, obj)
    hit_item.setData(Qt.UserRole, data)


text:
Q: Api определение местоположения пользователя как это сделать с переменной? Есть API
http://www.site.com/whereami?locale=ru&callback=useriata

Ответ:
useriata({"iata":"MOW","name":"Москва"})

И есть ссылка на странице у меня вида
http://site.com/flights/?origin_iata=??????????&destination_iata=SPB&adults=1&children=0&infants=0&trip_class=0&marker=marker&with_request=true

, мне нужно, создать переменную, которая будет равна классу IATA из API и эту переменную вставить заместо ??????? в ссылку. Подскажите пожалуйста как это сделать? Спасибо, с уважением.

A: можно сделать так:
    $ip = $_SERVER['REMOTE_ADDR'];

    $response = file_get_contents('http://www.travelpayouts.com/whereami?locale=ru&callback=useriata&ip='.$ip);

    preg_match('/\((.+)\)/', $response, $data);

    $data = json_decode($data[1]);

ссылка в переменной php:
$url = "http://site.com/flights/?origin_iata={$data->iata}&destination_iata=SPB&adults=1&children=0&infants=0&trip_class=0&marker=marker&with_request=true";

ссылка в html:
<a href="http://site.com/flights/?origin_iata=<?=$data->iata?>&destination_iata=SPB&adults=1&children=0&infants=0&trip_class=0&marker=marker&with_request=true">


text:
Q: C# - Disposed Object Dependent on where Mouse is Located? I am experiencing a problem in my C# code.
A bit of background: I am working on an HMI where I need to detect mouse movement anywhere on the HMI screen. The screen is divided into many different controls, so I use this recursive function in order to be able to detect a mouse movement over any control:
private void SetMouseTriggers(Control c1)
{
    // For all of the child controls in this control
    for (int i = 0; i < c1.Controls.Count; i++)
    {
        // Get the individual child control
        Control c2 = c1.Controls[i];

        // Add a MouseEventHandler to this control's MouseMove event
        c2.MouseMove += new MouseEventHandler(OnMouseMove);

        // Recursively call this function
        SetMouseTriggers(c2);
    }
}

// This function is entered whenever the mouse moves anywhere on screen
private void OnMouseMove(object sender, MouseEventArgs e)
{

}

I call this function for the parent control (i.e. SetMouseTriggers(ParentControl)) to check all child controls. This part works fine.
My issue is that I encounter an error "Cannot access a disposed object" when I attempt to use a specific feature of the HMI, which is to change users.

The strange part is, the error only occurs when the mouse is located over certain controls of the HMI. When the mouse is located over other HMI controls, the program works with no issues.
I tried to debug the program but I don't have access to the source of where the problem is actually occurring.

If it helps, here is the disassembly:

My next thought was to check the isDisposed property of each control to see if I can at least determine which control is causing the problem. See below the recursive function I created to detect this. I placed the program into debug mode and set a breakpoint if the control was disposed, but I could never hit this breakpoint in various scenarios that I tested.
private void CheckAllControls(System.Windows.Forms.Control c1)
{
    // For all of the child controls in this control
    for (int i = 0; i < c1.Controls.Count; i++)
    {
        // Get the individual child control
        System.Windows.Forms.Control c2 = c1.Controls[i];

        // Check if the control is disposed
        if (c2.IsDisposed)
        { // Breakpoint set here
        }

        // Recursively call this function
        CheckAllControls(c2);
    }
}

This tells me that the control must be disposed somewhere in the System.Windows.Forms.dll library.
My questions are:

*

*Is there a way around this even though I don't have access to the code where the problem is occurring?

*Even if there isn't a way around this, can someone explain what is happening and why? (i.e. Why is this problem only occurring when the mouse is located over certain controls?)

A: try that example,
I just subscribed into the disposed event, and unsubscribed from the delegate when it disposed.
and added some writes that might help to debug and understand the code later.
private void CheckAllControls(System.Windows.Forms.Control c1)
        {
            // For all of the child controls in this control
            for (int i = 0; i < c1.Controls.Count; i++)
            {
                // Get the individual child control
                System.Windows.Forms.Control c2 = c1.Controls[i];

                // Check if the control is disposed
                if (c2.IsDisposed)
                { // Breakpoint set here
                }
                c2.Disposed += C2_Disposed;
                // Recursively call this function
                CheckAllControls(c2);
            }
        }

        private void C2_Disposed(object sender, EventArgs e)
        {
            try
            {
                 Debug.WriteLine(string.Format("{0} just disposed", ((Control)sender).Name));
                ((Control)sender).MouseMove -= OnMouseMove;
                ((Control)sender).Disposed -= C2_Disposed;
            }
            catch (Exception ex) {
                Debug.WriteLine(ex);
            }
        }
        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            //your logic...
        }

A: The Exception is probably occurring because some part of the user control which have fired the event is disposed afterwards it has fired the event and before the event handler has actually run.
It depends on the controls your application is using. I can see on the error message that the exception is coming from an object called "UserGrid". Grids, tables etc. are usually consist of several smaller controls. As the number of the controls can be handled efficiently is finite, most of these controls only maintain ONE subcontrol (one table line / cell, one grid element etc.) for the currently edited cell (where the mouse is), and all the others are just rendered pictures. This may cause several object creation / disposal in the background. This is just an idea, but it can cause your disposal problem.
I think this exception occurs in the event handler, so you should not put the lines
// Check if the control is disposed
if (c2.IsDisposed)
{ // Breakpoint set here
}

into the recursive registration method, but into the event handler:
// This function is entered whenever the mouse moves anywhere on screen
private void OnMouseMove(object sender, MouseEventArgs e)
{
    // Check if the control is disposed
    if (sender.IsDisposed)
    { // Breakpoint set here
    }
}

Regarding the recursive solution, it would be much more efficient to register a low-level event filter to capture mouse move events all over your window. You can find an example for it here: How do I capture the mouse move event


text:
Q: Как передать шаблон повторяемого элемента в компонент? Хочу передать что-то типа ng-content в ngFor внутри моего компонента. Но дело в том, что мне нужно передать повторяемый элемент в элемент, который трансклюдится. Нашёл нечто подобное для первого ангуляра: http://plnkr.co/edit/aZKFqPJmPlfTVRffB0Cc?p=preview.
А как это сделать на втором?
PS: Этот вопрос на английском.

A: Для этого следует использовать ngForTemplate:
https://plnkr.co/edit/mpuQse2QuyP7QHXL7wM1?p=preview
@Component({
  selector: 'foo',
  template: `

I am foo

      <template ngFor [ngForOf]="data" [ngForTemplate]="itemTemplate"></template>

  `
})
export class Foo {
  @Input() data: any[];
  @ContentChild(TemplateRef) itemTemplate: TemplateRef<any>;
}

@Component({
  selector: 'my-app',
  template: `
Angular 2 Systemjs start

    <foo [data]="items">
      <template let-item>

item: {{item}}

      </template>
    </foo>
 `,
  directives: [Foo],
})
export class AppComponent {
    items = [1, 2, 3, 4];
}

Тег template можно заменить атрибутом:
https://plnkr.co/edit/jB4qzx9Zd3JLkyenu9f3?p=preview
<foo [data]="items">

item: {{item}}

</foo>

Каким скоупом обладает затрансклюженное содержимое?

Ему полностью доступен скоуп передающего компонента, в который добавляется переменная, прописанная в let. Если в том скоупе уже была такая переменная, она переопределяется. Скоуп компонента-репитера шаблону не доступен.
http://plnkr.co/edit/VzT9koNXzAx3B1qvHuJ8?p=preview

PS: Это дополненный перевод ответа от yurzui.


text:
Q: Binding SSRS report to complex Business Layer Object I have a Business Layer class which has few properties as a List of object. The search method returns a List of objects. So the list returned contains, few members, which are list of object themselves.
Now, when I try to bind my SSRS report, the normal members are getting bound with the report elements, however, I am not able to bind report elements to the property of list items, which themself are list of objects. e.g.
A list item looks like this
Id
Name
Address
List
where Subjects is an object having properties {SubjectId, SubjectName, SubjectDescription}
I want a report as follows:
Id                   Name                     Address                 Subjects
1                    A                        AddressA                Physics
                                                                      Maths
2                    B                        AddressB                Maths
                                                                      Chemistry
                                                                      Botany
3               C                  AddressC          Physics


text:
Q: Google Api PHP Client Syntax Error on PHP 7
*

*OS: macOS Big Sur

*PHP version:  7.4.1

*Package name and version:  google/apiclient: ^2.12.3

Whenever I switch the PHP version to 7.4.1 I get this error
Parse error: syntax error, unexpected 'static' (T_STATIC) in /Users/webtechstreet4/Local Sites/fvtest/app/public/wp-content/plugins/form-vibes-pro/vendor/psr/cache/src/CacheItemInterface.php on line 75
The library works great on PHP 8 but gives the above error when switching to PHP 7.
Screenshot

A: Actually, I sorted it out by changing the system PHP version and running composer update.
I thought I needed to change the site PHP version but it was actually the system PHP version.
here is the GitHub issue link: https://github.com/googleapis/google-api-php-client/issues/2246

A: it is because, static return type is available only for PHP 8, I have same issue, just for temporary you can change
.\vendor\psr\cache\src\CacheItemInterface.php
line number 75 just remove return type static like this
public function set($value);


text:
Q: Removing Rows based on Condition, SQL Oracle I have a table that that stores an EVENT_NUMBER and its EVENT_TYPE_CODE(s). Something like:

EVENT_NUMBER
EVENT_ITEM_CODE

400001
M

400002
M

400002
S

400003
T

400004
L

400004
S

400004
M

400005
L

400005
T

400006
S

400006
M

400006
L

400006
T

The data is populated into the table from a form. For each event, the user will choose from a list of items. When the data is populated into the table, it is normalized across one row. So, for example, for event 400001, the user entered one type of code (M). When the user entered data for event 400002, they choose both M and S.
I want to query this table so that if the event ever had an M entered into it, I want to remove the event number from the result. For example, we would completely remove all rows for event #400004 because at least one row for that even has an 'M'.
I have been struggling with this for a bit and most likely overthinking it at this stage. I tried a few things like compiling a list via LISTAGG and then searching through the list for an 'M' and then removing the row, however, I don't feel like that's an efficient enough approach, given the larger query I am creating.
I appreciate any suggestions.

A: You could use a delete with exists logic here:
DELETE
FROM events e1
WHERE EXISTS (
    SELECT 1
    FROM events e2
    WHERE e2.EVENT_NUMBER = e1.EVENT_NUMBER AND
          e2.EVENT_ITEM_CODE = 'M'
);

Edit: If you want to view your table this way, then use:
SELECT e1.*
FROM events e1
WHERE NOT EXISTS (
    SELECT 1
    FROM events e2
    WHERE e2.EVENT_NUMBER = e1.EVENT_NUMBER AND
          e2.EVENT_ITEM_CODE = 'M'
);


text:
Q: How to reload twitter button? For ajax pages I call:

twttr.widgets.load()

but never happens, it doesn't reload twitter button.
I tried also with

twttr.widgets.load("nameDiv")

but I get this error:
TypeError: Object nameDiv has no method 'getElementsByTagName'
What am I doing wrong?

A: I solved with this solution (jQuery):
function reload_twitter_button() {
  $('.social-tw').html('');
  $('.social-tw').html('Tweet');
  // refresh the widgets
  twttr.widgets.load();
}

A: I had the same issue. In my case, the page wasn't loaded before the load call was made. Wait for document ready to fire with:
$(function () {
    function loadWidgets(){
       twttr.widgets.load();
    }

    loadWidgets();
});


text:
Q: Getting the least significant byte I haven't tested on a big endian processor but would this always give me least significant byte?
int i = 12345678;
unsigned char c = static_cast<unsigned char>(i);

A: Yes, this will always give you the least-significant byte.  The C++ spec (§4.7/2) guarantees that narrowing conversions always discard the most-significant bytes by giving back the smallest value congruent to the original integer, modulo 2n, where n is the number of bits in the target type.
That said, there's no guarantee that an unsigned char is a single byte.  All that's guaranteed is that sizeof(char) == 1.  However, if you treat a byte as the smallest memory unit capable of holding a character, then this should work just fine.

A: Wouldn't the following also work?
int i = 12345678;
unsigned char c = (i % 256);

or
int i = 12345678;
unsigned char c = (i & 255);


text:
Q: Is there an SQL function that you can exclude results with integer and characters I have a number of records in my results that follow the following format:
TJ12345
So, any 2 characters followed by a set of integers. Is there a way I can exclude these records from my results?
Other records within the results have all characters for at least the first three letters so;
tfydu734, fdsha21344, hdsifhsidufh2
SELECT name, Filername
FROM [Permissions] with (nolock)
WHERE  (Name like '" & txtSearch.Text & "'
           or ACEName like '" & txtSearch.Text & "')
           and (ACEName not like '%Error%'
           and ACEName not like '%nas_%'
           and ACEName not like '%NASA%')

Thanks for any help

A: Well, task "determine if string contains two letters followed by digits" can be solved like:
declare @x nvarchar(max)
select @x = 'TJ12345'
select
   case
        when @x like '[A-z][A-z]%' and isnumeric(right(@x, len(@x) - 2)) = 1 then 1
        else 0
   end as Should_Be_Excluded

Key idea: first check if it starts with two letters, then strip them out and check if remaining string contains only digits using isnumeric fuction.
So literally you need to invert this criteria and put it into where condition in order to exclude these records.
select *
from your_table
where
    your_field not like '[A-z][A-z]%'
    or isnumeric(right(your_field, len(your_field) - 2)) = 0

A:
Other records within the results have all characters for at least the first three letters

so you could simply use
WHERE ACEName LIKE '[A-z][A-z][A-z]%'


text:
Q: Django: how to build an endswith filter I need to render image adobe_illustrator_file_logo.png if file.url ends with .ai.
But if file.url ends with other termination like .png for exmaple I'll render the image of the object.
I've searching documentation but apparently there is not a endswith built in filter.
So I ended up playing with ifequals and slice filter.
Logic it is the same: "if string is identical to the last 3 letters do this".
However, it is not working, as nothing gets displayed.

   {% ifequal cart_item.file.url|default:""|slice:"-3" ".ai" %}

   {% endifequal %}

Note:

{{ cart_item.file.url  }}

HTML renders:

/media/files/working_precisely.ai

Also, adobe_illustrator_file_logo.png renders correctly if it is put outside if condition.
Update 1:
Created my own filter, but gettting error:
TemplateSyntaxError at /cart/
    endswith requires 2 arguments, 1 provided
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter(is_safe=False)
@stringfilter
def endswith(value, suffix):
    return value.endswith(suffix)

Template
{% if cart_item.file.url|endswith: ".ai" %}

{% endif %}

A: You dont need a(nother) custom filter, you already almost had it. Your |slice:"-3" did a [:-3] slice in python, but you want a [-3:] slice. So, beeing just a tiny bit more explicit:
{% if object.image.url.lower|slice:"-3:" == "gif" %}
  # note the added : in "-3:", to make it a [-3:]
  # sidenote: arbitry code snippet from my current project...
{% endif %}

Though it is not a real endswith, strictly spoken, but works quite well, without adding another template filter to your project.


text:
Q: Evaluating an hcl.Expression which expected value is a Go interface I am writing a HCL-based configuration language where some types of blocks can reference other blocks using expressions, as follows:
source "my_source" {
  // some blocks and attributes...

  to = destination.my_kafka_topic
}

destination "kafka" "my_kafka_topic" {
  // some blocks and attributes...
}

destination "elasticsearch" "my_es_index" {
  // some blocks and attributes...
}

(The goal is the model the flow of events in a messaging system, and then materialize the actual system in terms of infrastructure.)
During parsing, I simply perform a partial decoding of the static attributes and blocks and ensure "to" hcl.Attributes can be interpreted as hcl.Traversals, but don't evaluate them (yet).
type Source struct {
    Name string // first HCL tag

    /* ... */

    To hcl.Traversal
}

type Destination struct {
    Type string // first HCL tag
    Name string // second HCL tag

    /* ... */
}

Later, referenceable blocks (e.g. destination in the example above) are associated with a certain Go type based on their Type label, and this Go type always implements an interface called Referenceable.
type Referenceable interface {
    AsReference() *Destination
}

type Destination struct {
    // fields that represent the destination in terms of address, protocol, etc.
}

At that stage, I know how to build a map of referenceables map[string]Referenceable where the key is <block_type>.<block_name> (e.g. "destination.my_kafka_topic"), but I am unsure how to leverage that in an hcl.EvalContext in order to evaluate the variables to Go Referenceables.
What I would like to know is: how to express a Go interface in the cty type system used by hcl.EvalContext? Is is even possible? If not, is it advised to inject instances of *Destination in the hcl.EvalContext instead?


text:
Q: puppeteer fingerprint - I am unable to override webGL vendor and render I am writing an puupeteer project for scraping web site.
I use stealth plugin for puppeteer because website detect me as a bot.
And everything was going well until I decided to check my browser on iphey.com
It shows me that I am trying to spoof my hardware
https://prnt.sc/1qk7t01
In details of hardware section I cannot get some useful info except to https://prnt.sc/1qk7wu3
As I understand it is hashs or something like this.
I decided to go further and check my puppeteer instance on https://browserleaks.com/
all the sections of the site are next
ip - https://drive.google.com/file/d/1__U5UK0D2xZVttXPhzUKzn06iUhUR9Jy/view?usp=sharing
rest in the comments bellow
And if I trully understand main problem with my puppeteer is WebGL Vendor and Rernder.
I would like to override them but have no idea how to do that.
Can you help me to ecome undetectable for iphey.com with my instance of puppeteer.
github - https://github.com/Golofaevap/myBrowser
I hope you will help me to find some solution


text:
Q: When does $f(x_0)$ maximum $\implies \det \mathrm{Hess}_f(x_0)\neq 0$? Let $f:\mathbb{R}^n\to\mathbb{R}$ be a smooth function and let $x_0\in \mathbb{R}^{n+1}$ be a critical point of $f$ such that $f(x_0)$ is a local maximum.
Question: Under which conditions does it follow that the Hessian $\mathrm{Hess}_f(x_0)$ has nonzero determinant? Note that this is clearly false if $f$ is a constant function, since then $\mathrm{Hess}_f$ is identically zero. If we assume $f$ is nonconstant, is this sufficient to ensure that $\det \mathrm{Hess}_f(x_0)\neq 0$?
The second derivative test says that $\mathrm{Hess}_f(x_0)$ being positive definite is sufficient for $x_0$ to be a maximum. So the question is in some sense a converse to that theorem, although I am only interested $\det \mathrm{Hess}_f(x_0)$ being nonzero.

A: If if $f$ is not constant, the determinant of the Hessian may be $0$. Take, for instance, $f(x,y)=-x^4-y^4$. Then $f$ has an absolute maximum at $(0,0)$ and, even so, the Hessian of $f$ at $(0,0)$ is the null matrix.


text:
Q: Plotando circulos em diferentes planos Eu necessito plotar circulos nos planos zy e zx, mas só consigo no plano xy, pois ao trocar de lugar as variaveis x, y e z, perdo o formato de corculo. Como posso consertar isso?
import numpy as np
from matplotlib import pyplot as plt
import mpl_toolkits.mplot3d.axes3d

theta = np.linspace(0, 2.*np.pi, 100)
phi = np.linspace(0, 2*np.pi, 100)
theta, phi = np.meshgrid(theta, phi)
c, a = 1, 0.05
x = (c + a*np.cos(theta)) * np.cos(phi)
y = (c + a*np.cos(theta)) * np.sin(phi)
z = a * np.sin(theta)

fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
ax1.set_zlim(-10,10)
ax1.plot_surface(x, y, z, color='b', edgecolors='b')
ax1.view_init(36, 26)

plt.show()

A: Vc deve zerar a coordenada do eixo que não quer que apareça o circulo. Por exemplo, se vc deseja plotar o circulo no plano zy, então
ax1.plot_surface(xzero, y, z, color='b', edgecolors='b')
onde xzero é um vetor de zeros ([0,0,0,..]) com a mesma dimenssão de y e z.
A mesma coisa vc faz para os demais planos.


text:
Q: How to select cells of a specific row using nth-child I have a 3x3 table.
I want to select each td within a specific row. (2nd row for example)
$('table > tbody > tr:nth-child(2) > td').css("background-color","red");

Above code sets only 2nd rows 1st column to red.
I expected it to modify each td in 2nd row but seems i'm missing something.
Why does above code doesn't work as expected?
(EDIT: I'm using Chrome 13 with jquery 1.7.1)

A: Chrome seems to be bugged again View this demo in Chrome (observed bug in Chromium 17).
Instead of > td, you can use .children(), which is equivalent:
$('table > tbody > tr:nth-child(2)').children().css("background-color","red");

Demo: http://jsfiddle.net/kYZWY/2/

A: You could simplify this using standard DOM properties that work in every major browser and while you're at it target it to the actual table you're interested in rather than all tables (which is what your current selector does). This will run faster and more reliably than the jQuery equivalent.
Live demo: http://jsfiddle.net/N3MAg/
var cells = document.getElementById("your_table_id").rows[1].cells;
for (var i = 0, len = cells.length; i < len; ++i) {
    cells[i].style.backgroundColor = "red";
}

A: May be you'll set the bg to the whole row like this
$('table > tbody > tr:nth-child(2)').css("background-color","red");

This approach also gives an identical result
$('table > tbody > tr:nth-child(2)').children().css("background-color","red");


text:
Q: Unit Test For Infrastructure Layer CQRS with Moq and xUnit, How to write tests using In-Memory Db I am new to unit testing and I have been using the CQRS mediatR pattern. I want to add unit tests for GetAllAsync() and GetByGameNameAsync() methods using Moq and xUnit. The code runs fine as intended but I need unit testing for it.
There is no connected database, I need to be able to write tests that will check both GetAllAsync() and GetByGameNameAsync() methods to see if it is working as intended.
How can i use inmemoryDb to write tests for the two methods?
public class IGenericRepository<TContext, TEntity> : IGenericRepository<TEntity>

 where TContext: DbContext
where TEntity: class
{
private readonly TContext _gameDbContext;

private readonly DbSet<TEntity> _gameDbSet;

public IGenericRepository(TContext dbContext)
{
_gameDbContext = dbContext;
_gameDbSet = dbContext.Set<TEntity>();
}

public async Task<IReadOnlyList<TEntity>> GetAllAsync()
{
var getBack = await _gameDbSet.ToListAsync();
return getBack;
}

GameDbContext.cs
public class GamesDbContext : DbContext
{
public GameDbContext(DbContextOptions<GamesDbContext> options) :base(options)
{
}
public DbSet<GamesEntity> GamesEntity => Set<GamesEntity>():

GamesEntity.cs
public int Id {get; set;}
public string gameName {get; set;} =null!;
public string gameDescription {get; set;}=null!;

GamesRepository.cs
public class GamesRepository: GenericRepository<GamesDbContext, GamesEntity>, IGamesRepository
{
private readonly GamesDbContext _gamesDbContext;
private readomly GamesDbSet<GamesEntity> _gamesDbSet;

public GamesRepository( GamesDbContext dbContext) : base(dbContext)
{
_gamesDbContext - dbContext;
_gamesDbSet = dbContext.Set<GamesEntity>();
}

public async Task<ReadOnlyList<GamesEntity>> GetByGameNameAsync(string gameName)
{
var gameEntities = await _gamesDbContext.GamesEntity.
                     Where(v => v.Entity == gameName)
                      .ToListAsync();

return gameEntities;
}

A: With such an organization of the code, there is no way to make unit tests, since mocking DbContext is a practically impossible and, most importantly, useless task.
The repository itself does not contain complex business logic, and covering it with tests does not bring any benefit.
If you still need to write tests, then you can use In-Memory DB, although there are many opponents of this approach.


text:
Q: DNS_PROBE_FINISHED_NXDOMAIN and domain is resolving I hosted my PHP website on GoDaddy's Gen 4 VPS. after a while of users using it. The website couldn't be accessed by anyone and all the users received DNS_PROBE_FINISHED_NXDOMAIN. The Nameservers were pointed to the server IP and it was working fine. But when this message appears the domain was resolving, server was working and files could be accessed but when trying to open anything on this domain the users receive DNS_PROBE_FINISHED_NXDOMAIN. When restarting the VPS everything works fine. but this problem happens again and again after users use this website again.
Is there any solution for this or even does anyone faced this problem before or knows the root cause of it??
NOTE: The PHP code was tested before launching and the server specs were more than required.


text:
Q: Why is StandardOpenOption.CREATE_NEW not creating a file to be read from in Java? Here is my code:
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class ExplicitChannelRead {

    public static void main(String[] args) {

        int count;
        Path filePath = null;

        // First, obtain a path to a file.
        try {
            filePath = Paths.get("test1.txt");
        }
        catch(InvalidPathException e) {
            System.out.println("Path error: "+e);
            return;
        }

        // Next, obtain a channel to that file within a try-with-resources block.
        try(SeekableByteChannel fChan =
                Files.newByteChannel(filePath, StandardOpenOption.CREATE_NEW)) {

            // Allocate a buffer.
            ByteBuffer mBuf = ByteBuffer.allocate(128);

            while((count=fChan.read(mBuf)) != -1) {

                //Rewind the buffer so that it can be read.
                mBuf.rewind();

                for(int i=0; i<count; i++) System.out.print((char)mBuf.get());

            }

            System.out.println();

        } catch (IOException e) {
            e.printStackTrace();
//          System.out.println("I/O error: "+e);
        }

    }

}

On running the above code I get this exception:
java.nio.file.NoSuchFileException: test1.txt
    at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
    at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
    at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
    at java.base/sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:235)
    at java.base/java.nio.file.Files.newByteChannel(Files.java:375)
    at java.base/java.nio.file.Files.newByteChannel(Files.java:426)
    at fileNIO.ExplicitChannelRead.main(ExplicitChannelRead.java:31)

I don't understand why test1.txt file is not being created as it doesn't exist currently and I am using the StandardOpenOption.CREATE_NEW option?
When I use StandardOpenOption.WRITE option along with StandardOpenOption.CREATE_NEW then I see the file text1.txt being created and at that time I get the exception:
Exception in thread "main" java.nio.channels.NonReadableChannelException
This exception I understand its cause because I have opened the file in write mode and in the code I am performing read operation on the file.
It seems to me that a new file can't be created when the file is opened in read mode.

A: I have reproduced what you are seeing (on Linux with Java 17).
As I noted in the comments, the behavior seems to contradict what the javadocs say what should happen, but what I discovered is this:

*

*With READ or neither READ or WRITE, a NoSuchFileException is thrown.

*With WRITE (and no READ), the file is created but then NonReadableChannelException is thrown.

*With both READ and WRITE, it works.  At least ... it did for me.
I guess this sort of makes sense.  You need READ to read the file and WRITE to create it.   And the javadocs state that READ is the default if you don't specify READ, WRITE or APPEND.
But creating an empty file1 with CREATE_NEW and then immediately trying to read it is a use-case that borders on pointless.  So it not entirely surprising that they didn't (clearly) document how to achieve this.

1 - As a comment noted, CREATE_NEW is specified to fail if the file already exists.  If you want "create it if it doesn't exist", then you should use CREATE instead.


text:
Q: Render a Square Using VBO Hi i'am trying to render a square using VBO.
Here is my code
void square() {
    if (!squareUpdate) {
        GLfloat squarevertices[] = {-0.75f,  .75f,   0.0f,   0.75f,
                                     0.75f,  0.0f,   0.75f, -0.75f,
                                     0.0f,  -0.75f, -0.75f,  0.0 };

        glGenBuffers(1, &VBOid);
        glBindBuffer(GL_ARRAY_BUFFER, VBOid);
        glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 9, squarevertices,
                     GL_DYNAMIC_DRAW);

        glEnableClientState(GL_VERTEX_ARRAY);

        glVertexPointer(3, GL_FLOAT, 0, 0);
        glDrawArrays(GL_POLYGON, 0, 9);

    } else {
        glVertexPointer(3, GL_FLOAT, 0, 0);
        glDrawArrays(GL_POLYGON, 0, 9);
    }
}

but it only renders half of a square it looks like a triangle

how can i make a box using a vbo?Im sure im missing something

A: Your polygon consists of 4 vertices with 3 components (3*4 = 12). The buffer size is sizeof(GLfloat) * 12 bytes:
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 9, squarevertices, GL_DYNAMIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 12, squarevertices, GL_DYNAMIC_DRAW);

However, in the draw call you need to specify the number of vertices:
glDrawArrays(GL_POLYGON, 0, 9);
glDrawArrays(GL_POLYGON, 0, 4);


text:
Q: syscall_thread_switch iOS 8.3 race - CocoaLumberjack bug? how to debug this? I'm hitting a race-condition in my app, where all or all but 1 threads get stuck on syscall_thread_switch whenever I pause debugging. It reproduces much more often on the simulator, but also on the iPad Air. There is ALWAYS at least 2 threads stuck in CocoaLumberjack's queueLogMessage: -- see screenshots.
I've never seen this before on 8.1 and 8.2, but i'm hitting it often on 8.3. I'm not claiming this is an 8.3 bug :)
This is a level of complexity i've never had to debug before, so i'm not sure what to do. I hope I'm providing enough information, please let me know if you need more (please be specific about how to get the information if it isn't dead clear). Can you please help me debug this?! Millions of thanks.

A: I hit a similar issue with NSOperations in a NSOperationQueue in iOS 8.3 (not related to CocoaLumberjack). I had concurrent operations creating their own threads, which is no-longer needed. It behaved perfectly well in 8.2, but not 8.3.
In the start method I simply replaced:
[NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];

With:
[self main];


text:
Q: Как сделать чтобы exe не банился антивирусом при запуске Создал прогу, обычное консольное окно, у меня оно нормально запускается, но если перекинуть на другой комп, то антивирус даже не дает его запустить, причем другие не подписанные ехе с левых сайтов нормально запускаются, что нужно сделать чтобы антивирус не блочил прогу?
В общем код проги такой=)
#include <iostream>

void main(){
    system("pause");
}

сам exe https://yadi.sk/d/xlOGwNKLgVfq2
ругается на него аваст и вин 8, получает люди из инета, если запускать с флешки то все нормально, если проверить антивирусом файл на флешке то тоже все нормально
Вот и  virustotal
https://www.virustotal.com/ru/file/315ad13da888bb4aa6a88dd8bde3fba811f7384746f70bcca80ed630a309ca8c/analysis/1431032185/

A: Не знаю, какой антивирус вы имеете ввиду.
Есть, например, Windows 8 Smart Screen, который блочит любые приложения, даже подписанные сертификатом (но не блочит подписанные спец ключом), пока их не скачает какое-то количество пользователей.
Наверно и другие антивирусы тоже могут действовать на основе популярности программы у других пользователей.
У меня подписанное обычным сертификатом приложение ( я его получил бесплатно как опен-сурс разработчик). Через некоторое время этот сертификат попал в белый список майкрософт и SmartScreen перестал жаловаться на новые версии приложения. Это произошло где-то через месяц, после того как я начал подписывать, скачиваний у меня гдето 5 тысяч.

A: Если антивирус определяет вашу программу как потенциально вредоносную:
Во-первых, вам следует по возможности избавиться от всего того, что антивирусы не любят: сжатие исполняемых файлов, особенно экзотическими упаковщиками; общесистемные хуки и т. п.
Во-вторых, надо пойти на сайт производителя антивируса и найти форму для отправки сообщения о ложной тревоге.
В-третьих, можете попробовать обзавестись качественной цифровой подписью, чтобы убедить антивирус, чтобы вы доблестный автор ПО, подтвердивший свою личность.

A: Это проблема конкретного антивируса. Если у него нету возможности добавить каталог, в котором вы программируете, в список исключений — выбросьте антивирус на помойку. Если антивирус поставили вам ваши админы на работе, поговорите с ними.
Если проблема на машине у клиента, тут хуже. Вам придётся отписаться в их техническую поддержку.
В любом случае, это не программистская, а организационная проблема. Если ваш код не содержит вирусов, он не должен блокироваться антивирусом, точка.

A: Обращайтесь к производителю срабатывающего антивируса, пускай исправляют ложное срабатывание.


text:
Q: what is the probability of correctly answering 8 or more questions? An exam consists of 10 multiple choice questions, where each has 5 possible answers and only one is correct. If we answer each of the 10 questions by randomly choosing the answer, what is the probability of correctly answering 8 or more questions?
My work
Let $X=$Number of correct answer selected. Then, $X=0,...,10$.
Note $p=\frac{1}{5}$ is the probability of select the correct answer of $1$ question.
Using binomial distribution we have:
$P(X\geq 8)=\binom {10} {8}(\frac{1}{5})^8(\frac{4}{5})^2+\binom {10} {9}(\frac{1}{5})^9(\frac{4}{5})+\binom {10} {10}(\frac{1}{5})^{10}(\frac{4}{5})^0=7.79\times 10^{-5}$
Is good this? Thanks for take the time of read this!


text:
Q: tar, exclude mounted filesystems (bind), keep directories I'd like to backup a directory, keep mounted subdirectories, but exclude their contents.
Directory structure should be intact, mounted subdirectories should be empty, everything else should be backed up, including files. Don't want to specify every excluded subdirectory via command line.
i.e.
mkdir /media/somedir

mkdir /media/somedir/share_A
mount -o bind /mnt/someshare_A /media/somedir/share_A

mkdir /media/somedir/share_B
touch /media/somedir/share_B/somefile

tar backup.tar /media/somedir

expected contents of backup.tar:
share_A [empty directory]
share_B
share_B/somefile

A: My bad --one-file-system option did the trick.


text:
Q: async react-select with defaultValue So I have a state of dynamically loaded options(API call):
// myOptions will be loaded with data after API call returned
// and will re-render the component using `useEffect`
const [myOptions, setMyOptions] = useState()

I'm loading react-select like so and everything works fine, except the defaultValue:
<AsyncCreatableSelect
  defaultValue={myOptions?.[0]}
  defaultOptions={myOptions}
  onChange={selectHandler}
  isMulti
  isSearchable
/>

The myOptions?.[0] is just an example. I want it to be passed with props, but the point here is that it simply doesn't work this way. It will work however if I'll pass the object right away when the component is loaded at the first time, like so:
<AsyncCreatableSelect
  defaultValue={
    {
      _id: "myLongId",
      value: "Some Value",
      label: "someLabel",
    },
  }
  defaultOptions={myOptions}
  onChange={selectHandler}
  isMulti
  isSearchable
/>

But obviously I don't want to hardcore it, but use it dynamically with returned data from the API call and passed props.
Also, the myOptions?.[0](when fulfilled) and the object ({_id: "myLongId", value: "Some Value",label: "someLabel",}) are exactly the same, meaning they're === to true. So the only reason for it not to work is some kind of memoization at the end of react-select. This is crazy... it should be triggered on the prop change.
I'm sure I'm not the only one dealing with this, can you share your solution to this please?
Thanks.


text:
Q: how to write strings and numbers to a .txt or excel file in matlab I am trying to write text and numbers in a text file in matlab, but i am only able to write the numbers easily. I am getting different errors when i try to store strings, as matlab stores strings in matrices in a different format as compared to numbers.
I want to write the file names and corresponding text found in the images in the text file. For e.g. i have an image of 1 digit. My program will identify the 1 text from that image, and it should write in the text file the following line
image1.jpg         1
// and so on
I am only able to write the digits found by my program, i am unable to save the corresponding filenames in the txt file.
THis is the code i have written
files = dir('F:\.....path.....\*.jpg');
output_to_write = zeros(size(files,1), 1);
for file = files'
    i = imread(['F:\....path......\' file.name]);

    counter = counter + 1;

    euler_no = regionprops(j, 'EulerNumber');

    if euler_no.EulerNumber == 1
        weights1 = [one(j), two(j), 0, four(j), five(j), 0, seven(j), 0, 0, 0];
        [mx,idx] = max(weights1);
        output_to_write(counter) = idx;
    end

    save output.txt output_to_write -ascii;

If i try to make output_to_write a n X 2 matrix and put the file.name at second column for each row of this matrix i get an error. How do i get around this?
Thanks.


text:
Q: Unable to autoload constant ActiveStorage::Blob::Analyzable I looked at every possible solution regarding this error but nothing solved it.
Every time I try to upload an image, I receive this error:
Unable to autoload constant ActiveStorage::Blob::Analyzable, expected /usr/local/lib/ruby/gems/2.5.0/gems/activestorage-5.2.2/app/models/active_storage/blob/analyzable.rb to define it.
Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.5.1'

gem 'rails', '~> 5.2.0'
gem 'mysql2', '>= 0.4.4', '< 0.6.0'
gem 'puma', '~> 3.11'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby

gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'

# Use ActiveStorage variant
# gem 'mini_magick', '~> 4.8'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

# Reduces boot times through caching; required in config/boot.rb
# Causing crashes. Removing for now
# gem 'bootsnap', '>= 1.1.0', require: false

# Well maintained fork with several patches and compatability for Rails 5.x
# If we need to we can fork this and take ownership of it. Much better than building from scratch.
# gem 'casino', git: "https://github.com/identification-io/CASino.git", branch: "master"
gem 'casino', git: "https://github.com/webappsllc/CASino.git", branch: "master"
# gem 'casino', path: '/Users/justin/dev/oss/CASino'
gem 'grape', '~> 1.1.0' # Pinned

gem 'wisper', '~> 2.0'
gem 'rack-cors', require: 'rack/cors'

# Form Objects
gem "reform", ">= 2.2.0"
gem "reform-rails"
gem "dry-validation"

# Free optimization
gem 'fast_blank'

# Hashids to obscure legacy_ids
gem 'hashids'

# Send Emails via Amazon SES
gem 'aws-sdk-rails'

# Upload Files via Amason S3
gem "aws-sdk-s3", require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'guard-rspec', require: false
  gem 'dotenv-rails', require: 'dotenv/rails-now'
  gem 'spring-commands-rspec'
  gem 'parallel_tests', group: [:development, :test]
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem 'grape_on_rails_routes'
  gem "better_errors"
  gem "binding_of_caller"
  gem "letter_opener"
  gem 'letter_opener_web', '~> 1.0'
end

group :test do
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15', '< 4.0'
  gem 'selenium-webdriver'
  # Easy installation and use of chromedriver to run system tests with Chrome
  gem 'chromedriver-helper'
  gem 'factory_bot'
  gem 'rspec'
  gem 'rspec-rails'
  gem 'database_cleaner'
  gem 'faker'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
# gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

In config/application.rb I have require 'active_storage/engine' uncommented.
In config/environments/development.rb I have config.active_storage.service = :local set up.
I ran rails active_storage:install and rails db:migrate.
The name of the model is user_test
class UserTest < ApplicationRecord
  has_one_attached :image
end

I have this in app/controllers/user_tests_controller.rb
def user_test_params
  params.require(:user_test).permit(:title, :caption, :image)
end

**config/storage.yml*
test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

I am really clueless as to why it isn't working.

A: Do you have config.active_storage.service = :amazon set in your development.rb by any chance?
I was getting the above error and it ended up being because I had the above line but the AWS env vars weren't set.

A: Make sure you check that all of the environment variables present:

*

*AWS access key

*AWS secret key

*Bucket Name

checking spelling of the environment variables to make sure they match your storage.yml configuration file


text:
Q: Isolated storage is acting wierd, can save one file, but not the second I get the following on the second using(StreamWriter statement:
Value does not fall within the expected range.
            #region save allowance
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

            //Open existing file
            IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("foo.txt", FileMode.Truncate, FileAccess.Write);
            using (StreamWriter writer = new StreamWriter(fileStream))
            {
                writer.Write(App.ViewModel.Foo);
            }
            #endregion

            #region save log

            IsolatedStorageFileStream fileStream2 = myIsolatedStorage.OpenFile("log.txt", FileMode.Truncate, FileAccess.Write);
            using (StreamWriter writer = new StreamWriter(fileStream))
            {
                foreach( var i in App.ViewModel.Items )
                    writer.Write(i.ToString());
            }

            #endregion

A: You're reusing fileStream the second time instead of fileStream2. By the way, to avoid this kind of mistake, you may want to wrap your filestream inside the using block.
        #region save allowance
        IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

        //Open existing file
        using (var writer = new StreamWriter(myIsolatedStorage.OpenFile("foo.txt", FileMode.Truncate, FileAccess.Write)))
        {
            writer.Write(App.ViewModel.Foo);
        }
        #endregion

        #region save log

        using (var writer = new StreamWriter(myIsolatedStorage.OpenFile("log.txt", FileMode.Truncate, FileAccess.Write)))
        {
            foreach( var i in App.ViewModel.Items )
                writer.Write(i.ToString());
        }

        #endregion


text:
Q: Onclick buscando valor do input Tenho um código html que é inserido dentro de uma variável PHP
E dentro eu busco CEP, se eu uso
    <input alt='cep' class='text difCep' name='cep' id='cep' value='$cep'  type='text' onblur='xajax_procurarEndereco(this.value);$(\"#loading\").css(\"visibility\",\"visible\");' />

funciona de boa, mas o usuário quer um botão de pesquisa, então adaptei o código e ai está o problema, não consigo pegar o value de cep.
Testei com document.getElementById("campo") e $('#cep').val();
<label id='label_cep' for='cep'>CEP</label>
    <input alt='cep' class='text difCep' name='cep' id='cep' value='$cep'  type='text' />
    <button type='button' onclick='xajax_procurarEndereco(buscar input do cep);$("#loading").css("visibility","visible");' style="padding: 6px; height: 24px; margin-left: 10px;">Buscar</button>

A: Ambos getElementById e a query do jQuery funcionam nesse caso, eu não posso pensar em outro problema que não seja você ter digitado errado, ou então usado aspas simples fechando assim as aspas que você abriu no HTML.
Veja o exemplo: https://jsfiddle.net/ar64m2gL/