text:
Q: Can Stack Overflow change the password criteria? Why the crazy password requirements? It a Q&A site, and I have to conform to arbitrarily chosen password complexity criteria.
With a 22 random lowercase characters (entropy 119 bits), the create account page asks me to:

Just adding uppercase characters to the mix does not satisfy the requirements.  With 125 bits of entropy, It still asks me to:

Fortunately, doing either of these does satisfy the requirements. As long as there are enough unique characters.  The password a1ᓕ♵Ŀꁏꂯ (with a1 replacing Unicode characters to satisfy the numbers and letters requirement, reducing the level of entropy from 112 to 88 bits) still causes the generator to insist that the password:

Sadly, the famous correct horse battery staple password doesn't fly, either:

I add entropy in my passwords in other ways than the Password1 (entropy approximately 0) mechanism suggested by these requirements, and prefer to use the Stack Exchange OpenID provider.

A: I appreciate that there is no way that this policy is ever going to change based on what I have to say, but it is a good example of listening to your customers needs, and then ignoring them to go off and do something fun instead.

*

*Stack Exchange initially only allows login using openid.

*Lots of
people don't like that. We just want to log into a Q&A site and ask
a question. We don't want any connection between this site and our
gmail account or our facebook account or whatever. Having a single
password that if broken allows access to everything about their life
doesn't seem more secure to us. It's not even clear whether Stack Exchange
will now have access to their gmail or facebook account. Presumable not, but who knows? All we  want is to give an
email address and password and log into the site to ask a question.

*Stack Exchange says that the acquisition of new users is a very
high priority. The openid thing is deterring users, so they fix it.
Hooray, everybody is happy.

*Especially the developer who, instead of
having to so some boring password authentication, gets to play with
openid.

*But the password standard is needlessly zealous. We have an intuitive understanding of when it is important to have a really good password, and sorry but a Q&A site does not make the cut.

*But the password standard can't be lowered to something more appropriate for a Q&A site, because instead of doing the simple thing and allowing people to log on using an email address and password, Stack Exchange did the fun thing instead with openid.

Now I personally will cope with the password rules because I have seen the effectiveness of stackoverflow.com before, and I need a question answered for work. But I wonder, how many people who stumbled upon Stack Exchange gave up at that first barrier?
So if anybody from Stack Exchange is out there reading, maybe consider the following:

*

*Stack Exchange really wants new users.

*A simple password is sufficient for a Q&A site.

*The current password system is turning potential new users away at the door.

*You could fix it if you wanted to.

A: Kevin Montrose's concern is that ordinary users will be confused by an entropy meter. That does not justify blocking good passwords, which is what the current system does.
A simple way to satisfy both criteria:

*

*Calculate entropy in the background. Any password with entropy over some threshold will get accepted.

*Passwords with less entropy than that fall back to the system shown. For example, if someone gives a low-entropy password that contains only letters, it could suggest adding "upper case, numbers, or special characters". To avoid being user-hostile, passwords that meet all the constraints could be accepted (even if they have low entropy).
You claim that you're using your password criteria to enforce security for OpenID accounts. That's fair—except the current system accepts qwerty1! as a password. Seriously? If you're going to "fall on the strict side" for security, you shouldn't be accepting passwords with 6.322 bits of entropy (according to zxcvbn).
There exist libraries to quickly estimate entropy, such as the one Dropbox uses.

A: Stack Exchange username/password accounts are actually OpenIDs, not something tied to the Q&A portion of the network ( https://openid.stackexchange.com/ ).
Because these accounts aren't constrained in use (by design) we can't assume anything about the "importance" of the account, thus the rather stringent password constraints.
What the password contraints are meant to do is act as a "normal person"-readable proxy for entropy.
Directly exposing entropy measurements to a registering user would be absurdly user hostile, and a simple yes/no indicator just begs the question "why isn't my password acceptable?" (you can't just say "not enough bits!").
In short, while you and I (and a non-trivial number of the people reading this, I'd wager) can reason about Shannon entropy the typical end user cannot.  The character class stuff is a reasonable approximation that has the benefit of being explainable, and  we fall on the more strict side because security is involved.
So no, we won't be relaxing the openid.stackexchange.com password requirements.

A: Make a two-column table: two-char language codes against a very common word in that language.
Randomly pick a row from that table.
Ask Google or other search engine "Show me pages in language xxx containing word yyy"
Randomly pick one of the the fifth through zzz hits.
Randomly pick a word from that page.
Repeat.
Stick the two words together.
Write them on a post-it
Stick that on the bottom of your keyboard.
Cuss and swear because all the sites only accept ASCII characters.
My problem is that I followed the usual asinine rules exemplified in XKCD for nine characters, and SE said I need one more character.  So I invented a new one with ten characters and SE said I need one more character.
UPDATE: One more unique character, i.e., one not yet used.  So 5tack-Exch@nge! would probably work :-)
By the way, "gizmo didn't eat chicken after midnight" was accepted.  I didn't try to log in with it, though.
Next experiment: Pasted in two Chinese words separated by a semi-colon.  The request was to add one capital letter or digit.  Putting a '2' on the end still got the same request.


text:
Q: Django Complex MySQL Query From PHP with Multiple Joins to Django ORM I have this code from Kohana (it's easily understandable) and I want to convert this to Django ORM given the ff. models:
class Item(models.Model):
    glasses = models.ManyToManyField(Glass, through="ItemGlass")
    collection = models.ForeignKey(Collection)

class ItemGlass(models.Model):
    glass = models.ForeignKey(Glass)
    item = models.ForeignKey(Item)

class Collection(models.Model):
    name = models.CharField(max_length=100)

class Code(models.Model):
    code = models.CharField(max_length=30)
    description = models.TextField()

class Glass(models.Model):
    collection = models.ForeignKey(Collection)
    code = models.ForeignKey(Code)

and the php query (uses Kohana's Database Lib)
$this->select(
                array('cd.id', 'id'),
                array('cd.description','description'),
                array('COUNT(DISTINCT("items.id"))', 'count')
            )
                    ->from('items')
            ->join(array('collections', 'c'))
            ->on('c.id', '=', 'items.collection_id')
            ->join(array('glasses', 'g'))
            ->on('g.collection_id', '=', 'c.id')
            ->join(array('code', 'cd'))
            ->on('cd.id', '=', 'g.code_id')
            ->where('items.discontinued', '=', FALSE)
            ->group_by('cd.id');

NOTE: the "array" clause you see is translated as
"SELECT cd.id AS id, cd.description AS description, COUNT(DISTINCT(items.id) AS count"

The thing is how do I do it? I can't successfully use select_related to join multiple tables in this case, and I can't find a good "filter trick" for the query. Any ideas?
EDIT: I am considering doing it in plain SQL, but I would prefer to avoid it if a Django ORM query can be done :)

A: I have come up with this after an hour of "head banging":
glasses = Code.objects.filter(glass__collection__item__discontinued=False)\
        .values('id', 'description')\
        .annotate(count=Count('glass__collection__item__id', distinct=True))

A: Definitely don't use SQL, it's a simple query which should be no problem with the ORM. Use something like:
Code.objects.filter(glass__item__discontinued=False) \
    .annotate(count=models.Count('glass__item__id'))

You can add a .values(...) to the end of it if you only want to retrieve specific columns, as in your php example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: IndentationError: expected an indented block || not like the others I just programed this code and i have i problem with it.
#!/user/bin/python
x=raw_input("your name?: ")
if x==raw_input("john"):
print "Welcome john"

And here is the error.

    print "welcome john"
        ^
Indentation-error: expected an indented block

A: You must indent the block after  if:
#!/user/bin/python
x=raw_input("your name?: ")
if x==raw_input("john"):
    print "Welcome john"

Use four spaces per level of indention.


text:
Q: new File(uri.toString()) returns file not found I have a URI and I want to create a file from this URI:
fileUri = file:///mnt/sdcard/20120904_162830.png;

File fichero = new File(fileUri.toString();

This works fine but when I try to create use or fichero.exist() = false
How can I create a file from this fileUri?
Solution:
fichero = new File(fileUri.getPath());//for camera
                    if (!fichero.exists()) {
                        fichero = new File(getRealPathFromURI(fileUri));//for gallery
                    }

public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

A: Try this:
File fichero = new File(fileUri.getPath());

A: File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File output = new File(dir,"20120904_162830.png");

add this permission to manifest...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

EDIT :
String filename= output.getAbsolutePath();
filename= str.subString(str.indexOf("/"),str.length());

A: Here is solution
fileUri = "file:///mnt/sdcard/20120904_162830.png";

URI fUri = new URI(fileUri);

File fichero = new File(fileUri.getPath());

This works only if you are not giving any web address in fileUri


text:
Q: Existe alguma workflow, no git, onde se determina o acesso e o bloqueio de arquivos? Sobre o Git, teria alguma forma onde cada usuário determina quais arquivos e por quanto tempo, o outro usuário terá acesso a edição de determinados arquivos, queria alguma forma onde se evite os conflitos dos arquivos.

A: Não, pois o Git é um DVCS. Ou seja, o usuário sempre terá uma cópia do repositório, que está desconectado de qualquer server, sendo assim, não seria possível controlar políticas locais de acesso a arquivos. Pois o objetivo de um repositório DVCS é ser um repositório central, caso precise.
Se você precisa controlar esse tipo de coisa o melhor seria usar um CVCS, por exemplo: TFVC, do Team Foudation Server; Subversion (SVN), ...
Porém eu analisaria a real necessidade desse bloqueio. Seria possível resolver esse problema, via processo. Quando um desenvolvedor requisitar um PR para um repositório central, uma pessoa no papel de integrador de código, faria o aceite ou recusaria.

A: Não. A melhor forma de controlar a edição de arquivos de uma forma democrática no git é usar pull requests. Veja se esse material te ajuda por gentileza


text:
Q: display more DAGs and more days in airflow? We use airflow for some big jobs and a few smaller ones. We have a large number of small-ish jobs we would like to set up as DAGs, but how can one see more of the success/failure results as they are running? The thought of looking at the web interface just makes me feel tired. I would have to be hitting a "Next" button hundreds of times.
Here is just a bit from an app I created. But I do not want to have to extend this app. Why should I be re-inventing this wheel here?
The table below has more than a 1000 rows and can have up to 3000+ and I can look at over 90 days of data because... well, why should I not?
So how can I get this sort of display out of airflow? Or is there something 3rd-party that uses airflow and will do this?
See:

A: There is no answer. It is no other UIs available that show more DAGs.


text:
Q: Is there tab-specific memory? I would like to be able to save a small amount on information associated with a tab.  If I reload the same site on that tab, the information is still available to the Javascript, but from another tab it is not.
Is this possible?

A: Yes is possible, is called Session Storage. According to MDN:

The sessionStorage property allows you to access a session Storage object for the current origin. sessionStorage is similar to Window.localStorage; the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated with the value of the top-level browsing context, which differs from how session cookies work.


text:
Q: Docker jenkins access port I am running docker compose of jenkins image by command docker-compose up my config files
Dockerfile:
FROM java:openjdk-8-jre

EXPOSE 50000

docker-compose.yml
    version: '3'

services:
    jenkins:
        image: jenkins:2.60.3-alpine
        ports:
        - 50000:50000

My container runs docker ps result:
CONTAINER ID        IMAGE                   COMMAND                  CREATED             STATUS              PORTS                                NAMES
7dbe18cdbb53        jenkins:2.60.3-alpine   "/bin/tini -- /usr/l…"   22 minutes ago      Up 22 minutes       8080/tcp, 0.0.0.0:50000->50000/tcp   docker_jenkins_1

I checked the docker host by docker inspect 7dbe18cdbb53
Result:
],
                "NetworkID": "e3a5461960939397615620f051696f8b78fde9352d0c8b42b4ed679a1e847b9b",
                "EndpointID": "999b5d3525b2fe823c5ed0033bb27e85b3ca26356b4bd9f1525de005739fecde",
                "Gateway": "172.18.0.1",
                "IPAddress": "172.18.0.2",
                "IPPrefixLen": 16,
                "IPv6Gateway": "",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "MacAddress": "02:42:ac:12:00:02",
                "DriverOpts": null

`

When i try to access from browser like 172.18.0.2:50000 it doesnt work.

A: The jenkins image that you have is configured to listen http traffic on port 8080.
Have a look at this: https://github.com/jenkinsci/docker/blob/c2d6f2122fa03c437e139a317b7fe5b9547fe49e/Dockerfile
This is the part where the http port default value is defined

ARG http_port=8080

and this is where it is exposed

# for main web interface:
EXPOSE ${http_port}

Similarly you can find that (slave) Agent port is 50000.
In your docker ps output you can see that the jenkins container is listening on 8080 but this is not publish on the host.
So basically you are trying to connect via http to the agent port and it is not working as expected.
Do change the docker compose file to also publish the 8080 port and use that.


text:
Q: Adding own items into QGIS 3.10 news feed? Is there a possibility of adding own items into the news feed of QGIS 3.10? As a GIS administrator it would be a great tool to spread GIS/QGIS related news to internal colleagues.

A: I think you can. I'd have to get your service to return this structure.
https://feed.qgis.org/
And with this I should be able to add your news channel.
url ="https://feed.qgis.org/"
text = "QGIS"
mNewsFeedParser = QgsNewsFeedParser(QUrl(url), text)
mNewsFeedModel = QgsNewsFeedProxyModel( mNewsFeedParser );
mNewsFeedParser.fetch()

I think you can, but I'm not completely sure.
Anyway, the welcome page feed always uses only the official QGIS feed, so even if you added your own channel I don't think it's going to be the same.
I hope it helps you.

A: While the code behind the news feed is open and can be reproduced, there's no way to replace the existing feed address with a new one (or add multiple feed sources). Rather, it's hard coded into the qgis source and cannot be customised (as of 3.10)


text:
Q: Generic empty overloaded constructor and when not to use generics I'm currently building a generic state machine and I'm using the constructor of the StateMachine with a generic parameter to set the fallback state at creation, in the event that there is nothing for the machine to do.
I was wondering if it's bad practice to have two constructors, one that is used by the state machine itself when needing to create new state objects, and another that is used when initializing the state machine for the first time (setting that default fallback state).
My biggest question: Am I abusing generics, and is there a time when generics shouldn't be used?
State machine creation:
//The generic parameter is the default "fallback" state.
_nodeStateMachine = new NodeStateMachine<IdleNodeState>();

State machine constructor:
public NodeStateMachine()
{
    _currentState = new T();
}

Here is how states would be changed in the NodeStateMachine class:
public void ChangeState<U>() where U : INodeState, new()
{
    _nextState = new U();
}

The constructors in question lie directly in the states themselves:
public NullNodeState(){} // To use the class generically.

public NullNodeState(ConditionCheck check)
{
    _nullCheck = check;
}

A: I don't see how the state machine is generic, since it appears the only restriction is the states implement INodeState. In that case, I would create a static factory method specifying the initial state:
public class NodeStateMachine
{
    private INodeState _nextState;
    private NodeStateMachine(INodeState initial)
    {
        _nextState = initial;
    }

    public void ChangeState<U>() where U : INodeState, new()
    {
        _nextState = new U();
    }

    public static NodeStateMachine Create<T>() where T : INodeState, new()
    {
        return new NodeStateMachine(new T());
    }

    public static NodeStateMachine Create(INodeState initial)
    {
        return new NodeStateMachine(initial);
    }
}


text:
Q: Calculating probability of living to 100 years of age based on life expectancy I am interested in finding out how exactly to calculate the probability of an individual living to a certain age, say 100, based on a life expectancy of X, and knowing his current age, say 30.
I did some reading on the topic but most of the resources I managed to find online regarding the topic, provided only hard numbers or even some online calculators where you could input your variables and get the result (without showing the actual calculations).
What would the formula be for this calculation?

A: The life expectancy (the median or average age), which is a summary of an entire distribution (defined by more than just a single parameter), does not capture very well the probability to reach a particular age, which is a particular point in the distribution.
Some example using data (2014) from the Dutch bureau of statistics
https://opendata.cbs.nl/statline/#/CBS/nl/dataset/7052_95/table?dl=98D9

 - graph 1 shows deathrate for age $i$
   $$f_i$$
 - graph 2 shows survival rate for age $i$
   $$s_i = \prod_{j=0}^{j=i-1} (1-f_j)$$
 - graph 3 shows probability for dying at age $i$
   $$p_i = s_i f_i$$
These curves based on a single year are of course not accurate (you would need to use estimates for future years since the deathrate of, say, 50 year olds in 2014 might not be the deathrate of 50 year olds in 2064) but are sufficient for demonstration purposes
So for this right figure the mean age of death will be 79.82
But you might imagine that many different types of curves for $f_i$, $s_i$ and $p_i$ may result into this life expectancy number. Thus based on the life expectancy number (which is $\sum i p_i$), a number that combines information from all $p_i$, we can not say what the value is for a single $p_i$ (the probability to die at age $i$).


text:
Q: Caused by: java.lang.ClassNotFoundException: org.hibernate.cfg.AnnotationConfiguration cannot be found by net.sf.jasperreports_6.10.0.final I'm trying to use Hibernate with jasperreports, using jasersoft studio (6.10.0),
I'm using hibernate 5 in my project, so I'm using annotations to map classes.
When I'm creating the Hibernate Data Adapter, I chose to use "Annotations" but I got the following error:
java.lang.ClassNotFoundException:
org.hibernate.cfg.AnnotationConfiguration cannot be found by
net.sf.jasperreports_6.10.0.final

Am I missing some jar files?

A:
In Hibernate 3.6, "org.hibernate.cfg.AnnotationConfiguration" is
  deprecated, and all its functionality has been moved to
  "org.hibernate.cfg.Configuration".
So , you can safely replace your "AnnotationConfiguration" with
  "Configuration" class.

Taken from Hibernate – The type AnnotationConfiguration is deprecated
In practical terms, it means you need to use other version of jasperreports that doesn't use deprecated API or downgrade Hibernate.


text:
Q: Finding the constants of an exponential equation Find $A$ and $k$ if $f(x)=Axe^{-kx}$ has a critical point at $x=10$, and at that critical point, $f(x)=12$.
I'm entirely lost in this question. I can find the general derivative of $Axe^{-kx}$ pretty easily, but solving gets difficult fast. I'd at least like a hint first to see what direction to even move in.
(The problem)

A: $$f'(x)=Ae^{-k x} (1- k x)$$
we know that $f(x)$ has a critical point at $x=10$ thus
$$f'(10)=0\to Ae^{-10k}(1-10k)=0$$
which means $$1-10k=0\to k=\frac{1}{10}$$
Furthermore we know that $f(10)=12$ so
$$f(x)=A x e^{-k x}\to f(10)=10Ae^{-\frac{10}{10}}=12$$
and finally
$$k=\frac{1}{10};\;A=\frac{6}{5}e$$


text:
Q: Scroll form programmatically I have a form that I programmatically add panels, labels, checkboxes,and textboxes.  The form is larger than the screen size.  I am using screen capture to record the image of the text box to file for printing.  How do I programmically scroll down the form so I can capture the next image?
I have tried moving the cursor but that does not change what is displayed on the screen.  I have researched and found how to scroll in a panel but not a form.

A: In a Windows Forms application you can scroll a control into view with
 ScrollControlIntoView(pictureBox2);

You can so set a precise position with
VerticalScroll.Value = 200;


text:
Q: Rich snippets for xhtml. and how to microdata this data ? (game's data) Rich snippets it's only for html5 or it's able in xhtml? cuz my website is in xhtml.
More question, how should I show data with rich snippets to:

*

*A game's link that includes: name, image, likes, dislikes, category, description, and upload date (example: http://only4gamer.com/)

*A game's page that includes: name, game's content (swf), description, likes, dislikes, category, upload date, game keys, game tags (example: http://only4gamer.com/games/game/Superbike-X)

Thanks you very much!

A: In XHTML you can use RDFa if your primary concern is to pass validation, but in practical terms on the web nothing is really going to be broken by using Microdata in XHTML.
For your data vocabulary I would look at a combination of the Review and Product schemas.


text:
Q: Capturing a specific size image from webcam How can I capture an image from the webcam and have it be a specific size, without whitespace?
I specify the desired size:
var screenshot:BitmapData = new BitmapData(VD1.width,VD1.height,false);
That's 400x300
And then I draw to the bitmap from my Video element
screenshot.draw(VD1);
I can do Camera.getCamera.height and .width and see that my camera is 352x264px
When I view the resulting image, I see whitespace all around the edges (colored grey, so you can tell), like this:![enter image description here][1]
If you measure the actual image, you'll see that it doesn't even take up 352x264 pixels. Even with that measurement, there still exists whitespace around the right and bottom edges.
The Camera.setMode method upscales the capture to fit 400x300, but it seems like taking a direct capture from the Video object that it's attached to (with VD1.attachCamera(myCam) outputs a different result when the VD1 object is drawn to a bitmap.
I'd like all my captured images to be the same size, regardless of camera resolution. Is there a way I Can do this?

For reference, here's how I capture the image:
private function takeScreenShot():void{
    var screenshot:BitmapData = new BitmapData(VD1.width,VD1.height,false);
    screenshot.draw(VD1);
    var encoder:PNGEncoder = new PNGEncoder();
    var pngByteArray:ByteArray = encoder.encode(screenshot);

    var responder:Responder = new Responder(function(res:Object):void{
        trace("createThumbnail success");
    },
    function(res:Object):void{
        trace("createThumbnail call failed");
    });

    mync.call("saveThumbnail", responder,pngByteArray);

}

Here's how I set up my camera
VD1 = new Video();
VD1.width = 400;
VD1.height = 300;

myMic = Microphone.getMicrophone();
myMic.rate = 22;
myMic.setSilenceLevel(0);
myMic.setUseEchoSuppression(true);
myMic.soundTransform = new SoundTransform(0,0);

myCam = Camera.getCamera();
trace(myCam.height+","+ myCam.width);
myCam.setMode(400,300,15);
myCam.setQuality(0,100);
myCam.setLoopback(true);

A: You probably cannot change the dimensions that the image is captured at, but you can resize the image. Here is a link to another StackOverflow question with info on resizing.


text:
Q: Javascript: Aba mestre Preciso de uma certa função em um projeto, preciso que algumas funções só executem em uma aba do meu site, por exemplo... O usuário está na aba HOME mas as abas SOBRE, CONTATO estão abertas e nesse site reproduz um áudio dependo do que retorno de uma consulta em um PHP. Então não quero todas as abas fazendo essa mesma pesquisa (que efetuo de +/- de 3 em 3 segundos), e não quero reproduzir o áudio em todas as abas (não terão nesse site somente essas páginas), então criei uma função utilizando o sessionStorage e o localStorage, segue:
    var app = {};

app.getTime = function()
{
    // retornar em segundos
    return new Date().getTime().toString().substring(0,10);
};

if( !sessionStorage['window']) sessionStorage['window'] = Math.floor(Math.random()*(9999999999999999-1111111111111111+1)+1111111111111111);

(app.fn = function()
{

    // Se não tiver setado o localStorage['time'] a menos de 3 sec
    // esta será a janela mestre.
    if( !localStorage['window'] || parseInt(localStorage['time'])<(app.getTime()-3))
    {

        localStorage['window'] = sessionStorage['window'];
    }

    app.mestre = (sessionStorage['window'] == localStorage['window']);

    if( app.mestre)
    {

        localStorage['time'] = app.getTime();
    }

    clearInterval(app.time);

    app.time = setInterval(function(){ app.fn(); }, 1000);

})();

///////////////

// EXEMPLO... Só a janela mestre fará a contagem...

var cont = 1;

setInterval(function(){

    if( app.mestre) document.body.innerHTML += cont++ + '  ';

}, 1000);

JSFiddle (Abra pelo menos duas vezes clicando no link - Duplicar a Aba não funciona)
O que acontece é que quando duplico a Aba como disse o sessionStorage das abas são iguais, ou seja, dá errado...
Como resolver e o que posso fazer para melhorar o código ?

A: Se a mudança de aba é feita via ajax, guarde o nome da aba atual em uma variável global no ato da mudança.
aba = "Home";

ou
aba = "Contato";

Então, dentro do setInterval:
setInterval(function(){

    if(aba != "Home"){

        return; //se não for a aba home, sai da função antes de executar o cálculo.

    }

    if( app.mestre) document.body.innerHTML += cont++ + '  ';

}, 1000);

Agora, se cada aba do site é uma página independente, gerada pelo PHP, você tem duas alternativas:
1 - Ou colocar o script somente na aba home;
2 - Verificar se estamos na Home procurando por um elemento.
Pegue a id de algum elemento que só exista na home do seu site, neste caso a homeId. Se esse elemento não existir, faça a função retornar nulo antes de realizar o código. Coloque no começo da função app.fn:
var homeId = document.getElementById('homeId');
if (homeId == null){

    return;

}


text:
Q: WCF server consequences when client aborts connection I am wondering what the consequences are for a WCF server when the client aborts the connection.  I know, for instance, that the server will continue processing the request.  But what happens after that?  When the server tries to send the response to the client what will happen?

*

*Will the server try once and give up or try multiple times?  Is this configurable?

*How long will the server try to send the response to the client?  Will the server know immediately that something is wrong or will it sit there waiting for an acknowledgment from the client that it will never receive?  Is this configurable?

*When the server finally gives up will an exception be thrown on the server?

*Are there any other side-effects that would be good to be aware of?

In my case I am using an HTTP binding.  Is it different for other bindings?  Also, when I say the client aborts the connection I am talking about something like calling client.Abort();.  Does it change anything if the client connection is 'abnormally' aborted, e.g. I unplugged the network cable from the client machine?

A: Assuming you are talking without callback functionality here:
There will not be any exception on server if the client is disconnected from server. If the server service is running on perclient mode then the service object will not be destroyed immediately. In percall mode, you can implement IDisposable to clear any resources immediately after the call is over as the object is going to be destroyed.
There are no retry methods on the server to keep trying to send the data to the client as the channel between the client and server will be broken.
In callback mode, you will have the client channel and you can check if the client is connected or if you tried to use the channel it will through an exception. You can then remove the channel from the list as you can call again on faulted channel.
If the service is running in percall mode, then do not call client.abort() as that will create another instance of the service. So it is not useful in this mode.


text:
Q: Confusion regarding WCF at Azure I have few WCF services, deployed at IIS, which are consumed by some android devices. I'm have to move all my databases and services to Azure. I googled to find out how to deploy WCF at Azure, and found a concept of WebRole and Azure Cloud Service project. See THIS SO POST
But at the same time, I just tried creating a new webapp in Azure and simply published my WCF services project there, and it worked fine. (I tested with client).
My Question is,

*

*What is the difference between the methods mentioned in the post I linked, and the way I deployed? I'm concerned, because I'm expecting high amount of requests.

*Is it okay to deploy my already created/ready services the way I did?

*What is preferred?

A: Both (WebApp and Web role) will work for your scenario.
The main difference between this two way is that Web role allows you to connect to it through remote desktop.
You can keep using WebApp and configure Auto Scaling (based on CPU usage or at a specific time).


text:
Q: React::ServerRendering::PrerenderError in... Rails 5, React I am using Rails 5 with react-rails gem. I want to use server-side rendering, but I see this error:

React::ServerRendering::PrerenderError in Home#index
Encountered error "# ExecJS::ProgramError: TypeError: Cannot read property 'serverRender' of undefined" when prerendering Main with {}

This is my /assets/javascripts/application.js:
//= require rails-ujs
//= require jquery
//= require react
//= require react_ujs
//= require_tree .

This is javascripts/components.jsx:
class Main extends React.Component{
    render(){
        return (

Hello

        );
    }
}

and this is the view:
<%= react_component('Main', {}, {prerender: true}) %>

Without prerender option, everything works.

A: I've had a similar issue and here's how I solved it
run command rails generate react:install
This will create the components folder and some required files under your javascripts/ dir.
Now, place your components.jsx in /assets/javascripts/componets directory
refresh the page.
I'm running rails 4.2.10 and haven't tested rails 5 but I'm guessing this should do the trick.
Let me know how you get on


text:
Q: How to run multiple lambda functions when deploying as a Docker image? How does the dockerfile look like for aws lambda with docker image via aws-sam when declaring multiple functions/apps in templates.yaml?
Here is the sample dockerfile to run "a single app"
FROM public.ecr.aws/lambda/python:3.8

COPY app.py requirements.txt ./

RUN python3.8 -m pip install -r requirements.txt -t .

# Command can be overwritten by providing a different command in the template directly.
CMD ["app.lambda_handler"]

A: The Dockerfile itself looks the same. No changes needed there.
The presence of the CMD line in the Docker file looks like it needs to change, but that is misleading. The CMD value can be specified on a per-function basis in the template.yaml file.
The template.yaml file must be updated with information about the new function. You will need to add an ImageConfig property to each function. The ImageConfig property must specify the name of the function in the same way the CMD value otherwise would have done so.
You will also need to update each function's DockerTag value to be unique, though this may be a bug.
Here's the NodeJs "Hello World" example template.yaml's Resources section, updated to support multiple functions with a single Docker image:
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      ImageConfig:
        Command: [ "app.lambdaHandler" ]
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get
    Metadata:
      DockerTag: nodejs14.x-v1-1
      DockerContext: ./hello-world
      Dockerfile: Dockerfile
  HelloWorldFunction2:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      ImageConfig:
        Command: [ "app.lambdaHandler2" ]
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello2
            Method: get
    Metadata:
      DockerTag: nodejs14.x-v1-2
      DockerContext: ./hello-world
      Dockerfile: Dockerfile

This assumes the app.js file has been modified to provide both exports.lambdaHandler and exports.lambdaHandler2. I assume the corresponding python file should be modified similarly.
After updating template.yaml in this way, sam local start-api works as expected, routing /hello to lambdaHandler and /hello2 to lambdaHandler2.
This technically creates two separate Docker images (one for each distinct DockerTag value). However, the two images will be identical save for the tag, and based on the same Dockerfile, and the second image will therefore make use of Docker's cache of the first image.


text:
Q: How to check the convergence of $\sum_{n=1}^{\infty} \frac{n^{n/2}}{n!}$ How do I know the nature of the

$$\begin{align}
\sum_{n=1}^{\infty} \frac{n^{n/2}}{n!}
\end{align}$$

I have tried the ratio test and got nowhere.

A: \begin{align}
\frac{(n+1)^{\frac{n+1}2}}{(n+1)!}\cdot \frac{n!}{n^\frac{n}2} &= \frac{\sqrt{n+1}}{n+1}\sqrt{\left( \frac{n+1}{n}\right)^n}=\frac{\sqrt{n+1}}{n+1}\sqrt{\left( 1+\frac{1}{n}\right)^n}
\end{align}
I am going to leave the evaluation of the limit as $n\to \infty$ as an exercise.


text:
Q: How would I save the rating with a Shared Preference? I am trying to implement a rating bar within an AlertDialog. I have the rating bar working but I can't seem to make the SharedPreference work to remember what star rating was inputted beforehand. Where/How should I put the SharedPreference to make it work?
Here is the code for the rating AlertDialog:
 private float rateValue;

  rating.setOnClickListener(clk ->{
           AlertDialog.Builder mBuild = new AlertDialog.Builder(SoccerItemDetailHostActivity.this);
           mBuild.setTitle("Please rate the app");
           View mView = getLayoutInflater().inflate(R.layout.soccerratingbar,null);

           final RatingBar ratebar = (RatingBar)mView.findViewById(R.id.ratingBar);
           ratebar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
               @Override
               public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                   rateValue = rating;
                   Toast.makeText(SoccerItemDetailHostActivity.this, ""+rating, Toast.LENGTH_SHORT).show();
               }
           });

           Button btnSubmit=(Button)mView.findViewById(R.id.btnSubRating);
           btnSubmit.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   Toast.makeText(SoccerItemDetailHostActivity.this, ""+rateValue, Toast.LENGTH_SHORT).show();
               }
           });
           mBuild.setView(mView);
           AlertDialog dialog=mBuild.create();
           dialog.show();

       });

A:
I have the rating bar working but I can't seem to make the SharedPreference work to remember what star rating was inputted beforehand.

Well, what have you tried? Your code doesn't show any attempt at using SharedPreferences so it's impossible to say what you're doing wrong.

Where/How should I put the SharedPreference to make it work?

You could probably add an onDismissListener to the dialog that saves the current rating.

A: To save the rating you need to save it in your SharedPreferences. In the code below I show you how to achieve that:
RatingBar ratingBar = findViewById(R.id.ratingbar);
        if(getRating(getApplicationContext()) != 0){
            ratingBar.setRating(getRating(getApplicationContext()));
        }
        ratingBar.setOnRatingBarChangeListener((ratingBar1, rating, fromUser) -> {
                setRatingBar(getApplicationContext(),rating);

        });

And here the mentioned SharedPreferences functions:
public static SharedPreferences prefs(Context context){
        return PreferenceManager.getDefaultSharedPreferences(context);
    }
    public static void setRatingBar(Context context, float Float) {
        prefs(context).edit().putFloat("RatingBar", Float).apply();
    }
    public static float getRating(Context context) {
        return prefs(context).getFloat("RatingBar", 0);
    }


text:
Q: Enable wifi antenna in boot-repair environment L.S.,
I'm trying to fix things with Boot-repair(bootable disk) but it needs internet to work properly.
The thing is, my wifi antenna auto-enables when i boot windows and linux, but this is not the case when i boot into Boot-repair. And i can't enable it with it's hotkey, (fn+) f12.
It just stays disabled, and i can't find any or option button to enable it in Boot-repair.
Maybe there is a command to enable it?
Can someone help me?
Or is it perfectly reasonable to use Boot-repair without internet connection?
That would seem strange to me as Boot-reapir itself strictly says it needs it.
Anyway, thanks for the help.

A: If your 'boot repair' is linux based, it's very well possible that the wireless card isn't recognized due to the absence of correct firmware.
Please provide us with more information on the repair disk: it is a read only disk, or could you be able to install extra drivers while running the repair disk? If so: try to find out which type your wireless card is, with the lspci or lsusb commands. There's a good chance that the information from these commands will help you find the correct drivers, should they be missing.


text:
Q: PlayFramework 2.x - Forms / Associating error message to one element of a tuple I've got this form mapping:
val myElement = Form(
    mapping(
      "title" -> nonEmptyText,
      "schedule" ->
        tuple("startSchedule" -> jodaDate("dd/MM/yyyy HH:mm"),
          "endSchedule" -> jodaDate("dd/MM/yyyy HH:mm"))
          .verifying(MyValidator().checkForEndScheduleConsistency("error.schedule")),
    )(MyElement.apply)(MyElement.unapply)
  )

MyElement class:
case class MyElement(title: String, schedule: (Datetime, Datetime))

MyValidator class:
def checkForEndScheduleConsistency(errorMsg: String) =
    Constraint[(DateTime, DateTime)]("constraint.schedule", errorMsg) {
      schedule =>
        MyDomainValidator().checkForEndScheduleConsistency(schedule._1, schedule._2, Messages(errorMsg)) match {
          case Success(s) => Valid
          case Failure(f) => Invalid(ValidationError("custom error string from `f`"))
        }
    }

Requirement: An error message must be associated to the field schedule.endSchedule(tuple's element) if the schedule is inconsistent according to MyValidator object.
However, in order to have both required elements (startSchedule and endSchedule) available for checkForEndScheduleConsistency method, I can't apply a verifying method directly on the nested tuple's element named endSchedule. Instead, I have to apply one on the whole tuple in order to include startSchedule variable, as shown in the code snippet.
The drawback is that the error is not mapped to endSchedule but to schedule (that doesn't represent anything in my HTML form), and so nothing is displayed to screen when an inconsistent schedule appears.
Therefore, I have to use this "workaround" to achieve my requirement using Form's withError method:
def create = Action {
    implicit request =>
      myForm.bindFromRequest.fold(
        myFormWithErrors => {
          myFormWithErrors.error("schedule") match { //check for the presence of potential schedule error
          case Some(e) => {
            BadRequest(views.html.create_element("Create an element", myFormWithErrors.withError("schedule.endSchedule", Messages("error.schedule"))))
          }
          case _ => BadRequest(views.html.create_element("Create an element", myFormWithErrors))
        }
        },
        myForm => {
          treatSubmittedMyForm(myForm)
        }
      )
  }

=> Very ugly and anti-DRY.
Is there a way to apply verifying on the tuple and despite of that, apply the error message to a nested tuple's element? In my case, on endSchedule.

A: Probably the best solution is to replace the default helpers provided by Play when rendering the field by one of your own making, as per documentation:
@(elements: helper.FieldElements)

    @elements.label

        @elements.input
        @elements.errors.mkString(", ")
        @elements.infos.mkString(", ")

That way you can manually replace the error reference to the right element. Not extremely nice but you should be able to create a reusable tag from it.

A: The best solution is to precise the global (to schedule) "error" key into the more specific generated input directly, here the schedule.endSchedule input:
@inputText(hobbyForm("schedule.endSchedule"), 'id -> "schedule.endSchedule", '_error -> hobbyForm.error("schedule")

Notice the part: '_error -> hobbyForm.error("schedule")


text:
Q: Cannot implicitly convert type 'string' to 'int' for comparing 2 variables Im having an issue whereby the variables to check if the random number and user input variables are the same. This is required to check if they have the same value as I need it for the game mastermind I am creating as a college project. Thanks.
 public void DrawStart()
    {
        Console.Clear();
        Random rnd = new Random();
        int numberOne = rnd.Next(1, 7); //This is generating a random number and is saving it within the variable numberOne
        int numberTwo = rnd.Next(1, 7); //This is generating a random number and is saving it within the variable numberTwo
        int numberThree = rnd.Next(1, 7); //This is generating a random number and is saving it within the variable numberThree
        int numberFour = rnd.Next(1, 7); //This is generating a random number and is saving it within the variable numberFour
        Console.WriteLine("This is your first guess.");
        Console.WriteLine("Good luck");
        string gnumberOne = Console.ReadKey().KeyChar.ToString();
        string gnumberTwo = Console.ReadKey().KeyChar.ToString();
        string gnumberThree = Console.ReadKey().KeyChar.ToString();
        string gnumberFour = Console.ReadKey().KeyChar.ToString();
        Console.WriteLine("");
        Console.WriteLine("These are the random numbers");
        Console.Write(numberOne);
        Console.Write(numberTwo);
        Console.Write(numberThree);
        Console.Write(numberFour);
        if (numberOne = gnumberOne)
        {
            Console.WriteLine("X");
        }
        else
        {
            Console.WriteLine("O");
        }
        Console.ReadKey();
    }-

A: Firstly, you need to use == in your if statement to compare two values. = assigns values, it doesn't do comparison.
Your line if (numberOne == gnumberOne) is comparing an int to a string. You need to compare like to like.
Try:
if (numberOne.ToString() == gnumberOne)

or
if (numberOne == int.Parse(gnumberOne))

A: You need to parse the string
if (numberOne == int.Parse(gnumberOne))
{
    Console.WriteLine("X");
}

And you should be using == to compare not =
You might want to take a look at TryParse to safely parse your numbers without the application crashing if someone would enter something else than a number.


text:
Q: Vue3 Vite Hot Reload (HMR) no working in the browser I'm developing a vue3 project with vite.
The HMR doesn't working fine in my dev enviroment.
When a vue file edited, vite handle the change and send a message thru websocket correctly
{"type":"update",
"updates":[{"type":"js-update","timestamp":1669740364450,"path":"/src/views/user/LoginView.vue","explicitImportRequired":false,"acceptedPath":"/src/views/user/LoginView.vue"}]}

but in the browser (I tried different ones) nothing happened.
Any solution?
my package.json
{
  "name": "frontendq",
  "private": true,
  "version": "0.9.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@quasar/extras": "^1.15.5",
    "axios": "^1.1.3",
    "moment": "^2.29.4",
    "quasar": "^2.10.2",
    "vue": "^3.2.45",
    "vue-i18n": "9",
    "vue-recaptcha": "^2.0.3",
    "vue-router": "^4.1.6",
    "vue3-cookies": "^1.0.6",
    "vuex": "^4.1.0"
  },
  "devDependencies": {
    "@quasar/vite-plugin": "^1.2.3",
    "@vitejs/plugin-vue": "^3.2.0",
    "sass": "1.32.12",
    "vite": "^3.2.4"
  },
  "packageManager": "yarn@3.2.4"
}

A: I've been dealing with this issue in a project with Vue 3, TypeScript and Vite 4. I added the next to my vite.config.ts to fix the hot reload:
server: {
  watch: {
    usePolling: true,
  }
},

My entire vite.config.ts:
import {defineConfig} from "vite";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  server: {
    watch: {
      usePolling: true,
    }
  },
});


text:
Q: Duplicated output with Watchdog library I'm working with watchdog library, and want to send e-mails when a file is saved on a folder.
My problem is that when I save any pdf file on the folder, the module registers 4 modified events, and send four e-mails. Can anyone suggest how can I fix it ?
Here is my code. I used print just to exemplify.
'''
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class Handler(FileSystemEventHandler):
    def on_modified(self, event):
        print('Modified')

folder_to_track = 'path'

observer = Observer()
event_handler = Handler()
observer.schedule(event_handler, folder_to_track, recursive=True)
observer.start()

try:
    print('Monitoring')
    while True:
        time.sleep(1)

except KeyboardInterrupt:
    observer.stop()
    print('Done')
observer.join()

'''
Output:
Modified
Modified
Modified
Modified


text:
Q: Read text file entry in visual web part (C#) I have a text file with URL & active entry
URL                  Active
Http://              0
http://              1

I want to convert the file to a SharePoint list in visual web part

A: By this way, you can achieve your solution, Please Update the logic as for your context.
using (SPSite oSPsite = new SPSite("http://website url/"))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
      {
        oSPWeb.AllowUnsafeUpdates = true;

        // Fetch the List
        SPList list = oSPWeb.Lists["MyList"];

        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\timesheetfile.txt");

        SPListItem itemToAdd = null;

        //Display the file contents by using a foreach loop and update logic as You want.
        foreach (string line in lines)
        {
        string[] arr = line.Split(",");

         //Add a new item in the List
        itemToAdd = list.Items.Add();
        itemToAdd["URL"] = Convert.Tostring(arr[0]);
        itemToAdd["Active"] = Convert.Tostring(arr[1]);
        itemToAdd.Update();

        }


text:
Q: Unable to merge ResourceDictionary from a referenced project I have two assemblies that each provide a common set of styles and resources that I want to include in my application. I'm using merged dictionaries in my App.xaml in order to load them, and at runtime they were just fine. Unfortunately, these resources won't load at design time, filling my Errors window with messages about unresolvable resources and giving me a UI that doesn't represent what will actually appear.
This is my App.xaml as it stands right now:
<Application x:Class="ClientDebug.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             >
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Dai.Common;component/Xaml/Common.xaml" />
                <ResourceDictionary Source="/Dai.DevExpress;component/Xaml/Styles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

For both of these merged dictionaries, I get the following errors in my Errors window:
Error   11  An error occurred while finding the resource dictionary "/Dai.Common;component/Xaml/Common.xaml".   C:\DevProjects\Core Application\ClientDebug\App.xaml    12  17  ClientDebug
Error   12  An error occurred while finding the resource dictionary "/Dai.DevExpress;component/Xaml/Styles.xaml".   C:\DevProjects\Core Application\ClientDebug\App.xaml    13  17  ClientDebug

Which are obviously short on helpful information. Again, they load at runtime just as you'd expect, but none of the resources are available at design time.

A: I have this every time I start a new WPF project or work with an old one ever since a few days ago. I started a question to ask for help on it, only for it to disappear on me on a test Solution! Seems Visual Studio's not very stable, who knew?
The core of the problem is that the Xaml designer isn't allowing you to make references to other Projects in your Solution from your Application Project only. The workaround is to move everything into a Library and have the Application do little more than hand off control to it in code. Inelegant and the loss of App.Xaml is very tough, but it's much better than waiting for Visual Studio to magically figure it all out.

A: I precede the dictionaries that are from other namespaces with "pack://application:,,," like so:
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/Wsi.Util;component/DataGrid/NameValueDataGridDictionary.xaml" />
            <ResourceDictionary Source="LayoutStylesDictionary.xaml" />
            <ResourceDictionary Source="pack://application:,,,/Wsi.Util;component/controls/ToolBarResources.xaml" />
            <ResourceDictionary Source="pack://application:,,,/Wsi.Common;component/view/themes/FilterStylesResourceDictionary.xaml" />
        </ResourceDictionary.MergedDictionaries>

HTH,
Janene

A: I tried a similar merging in a project of mine and I seem to have it working perfectly. (or so, forgive me if its some settings of mine that I may have set long ago..) The only question I can ask is if the xamls are referring to anything within the parent project? I am assuming you have a reference to the parent project also (just cross-checking). Maybe the xaml file needs another xaml file too (controls, colors, fonts etc).
(The merging that I tried was from MahApps.)
  <Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colours.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseDark.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </Application.Resources>

A: I fixed this issue by signing the referenced project.
Problem was: My project was signed with a key file but the referenced project not.
To solve:

*

*Load the project into the solution

*Opened the project properties

*Navigate to 'Signing'

*Click 'Sign the assembly'

*Select '<New...>' from the combo box

*Enter a name, eg. 'keyfile' ('Protect my keyfile with a password' is optional)

*Rebuild solution


text:
Q: Boot a native OS on a hard disk as a virtual machine I'm searching for a solution to boot a native OS on a hard disk as a virtual machine.
It's like what VMware Fusion did on a Mac which boots Windows in Boot Camp as a virtual machine.
In detail, I have Windows installed on /dev/sda2 and Ubuntu 11.10 on /dev/sda5.
Is there anyway to use a virtual machine software to boot the Windows on /dev/sda2 as a virtual machine while I'm using Ubuntu?

A: As answered, this also can be done in VirtualBox, this is the way that works for me
Always, make sure that you are running as Administrator(Windows) or Sudo(Linux), any changes that you do will write to the REAL disk, so be carefull
In Windows
C:\Program Files\Oracle\VirtualBox>VBoxManage.exe internalcommands createrawvmdk -filename "E:\virtualbox\linuxhd.vmdk" -rawdisk "\\.\PhysicalDrive1"
RAW host disk access VMDK file E:\virtualbox\linuxhd.vmdk created successfully.

In Linux
$ VBoxManage internalcommands createrawvmdk -filename "~/linuxhd.vmdk" -rawdisk "/dev/sda"

It will create a file with something around 1kb that is a link to the physical  hard drive.
Then create a Virtual Machine as ever you do.
If you want to map only a partition
At Windows
\\.\Physicaldrive1 -partitions 1

(Disk start with 0, partitions
    with 1)
At Linux (Much more intuitive)
/dev/sda1
/dev/sda2
etc.

Eventually you can get resolution issues
Eventually you can get resolution issues even after install vboxadditions, in my experience the problem is your /etc/X11/xorg.conf it is configured to your specific real hardware specs(I have a offboard GPU for example), least in my case I solve it simply removing this file (xorg auto configure at boot, only will not work if you set some specific setting), so run:
sudo cp /etc/X11/xorg.conf /etc/X11/xorg.conf.original && sudo rm /etc/X11/xorg.conf

Reference

*

*http://www.virtualbox.org/manual/ch09.html#rawdisk

*https://forums.virtualbox.org/viewtopic.php?f=6&t=36694

*https://romaimperator.com/?p=29

A: Yes, I did this long ago following this guide:
https://lists.ubuntu.com/archives/ubuntu-us-nm/2008-February/000521.html
of course, always backup and be careful!
Essentially:

*

*Used a USB 3.5 HD enclosure and connect the XP drive to it.
If the drive was shutdown uncleanly you may need to manually

mount it with the following command.
   sudo mount ntfs-3g /dev/whereyourdriveis /mount/somemountpoint -o

force
   Once the drive is mounted under linux contiunue to step 2.

*Launch VMWare.

*Go to File -> New -> New Virtual Machine.

*Select "Custom"

*Select Next

*Select your operating system (i.e. Win XP)

*Select Next

*Give it a name like "WindowsXP"

*Select Next

*Specify processor One or Two

*Select Next

*Choose public or private (on a single-user machine this doesn't
matter)

*Select Next

*Select the memory to devote to the virtual machine. 512 MB is a
pretty useful number.

*Select your network connection

*Select Next.

*Leave SCSI set to BusLogic

*Select Next

*Select Use Physical Disk

*Select Next

*Select Use Entire Drive

*Select Next

*Specify the place to save the VM

*At this point you're done Select Power On to boot the Physical drive
in VMWare!

More Info: I should add, I have successfully done this, but I also had success using this method years even years before. So there are at least two known and tested ways for accomplishing this that I can tell you.

A: You can do this via VirtualBox raw disk access.
(http://www.virtualbox.org/manual/ch09.html)
It basically creates a "virtual" disk file that points to the actual partition and loads it as a disk drive in the VM. I've installed Linux guest in VB on Windows host in such a way, and the installation can boot from the VM or by itself.


text:
Q: How can I solve the inability to achieve fragment jump through onclick? The program did not report any errors, but when I clicked the button to jump to the fragment, the program crashed directly and still did not report any errors.
This is MainActicity code:
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);
        imageView.setImageResource(R.drawable.ic_launcher_background);
    }

    public void selectFragment(View view) {
        Fragment fragment;
        switch (view.getId()){
            case R.id.button:
                fragment = new testFragment();
                break;
            case R.id.button3:
                fragment = new secTestFragment();
            default:
                throw new IllegalStateException("Unexpected value: " + view.getId());
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment2, fragment).commit();
    }
}

This is my main activity layout.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="267dp"
        android:layout_marginBottom="160dp"
        android:contentDescription="TODO"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        tools:srcCompat="@tools:sample/avatars" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="42dp"
        android:layout_marginEnd="137dp"
        android:layout_marginBottom="220dp"
        android:onClick="selectFragment"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="@+id/fragment2"
        app:layout_constraintVertical_bias="0.663" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="186dp"
        android:layout_marginTop="28dp"
        android:layout_marginEnd="137dp"
        android:text="textButton"
        android:onClick="selectFragment"
        app:layout_constraintBottom_toBottomOf="@+id/fragment2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <fragment
        android:id="@+id/fragment2"
        android:name="com.example.fragmenttest.testFragment"
        android:layout_width="408dp"
        android:layout_height="411dp"
        android:layout_marginTop="240dp"
        android:layout_marginEnd="3dp"
        android:layout_marginBottom="80dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

This is the first fragment page layout.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".testFragment">

    <ImageView
        android:id="@+id/testImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:src="@tools:sample/avatars"
        android:src="@drawable/burwood"/>
</FrameLayout>

This is the second fragment page layout.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".secTestFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/fragmentTextView"
        android:layout_width="match_parent"
        android:layout_height="106dp"
        android:gravity="center"
        android:text="@string/hello_blank_fragment"
        android:textSize="36sp"
        android:textStyle="bold" />

</FrameLayout>

I hope can get some suggestion. Thank you!

A: You will want to debug your application and you can set a breakpoint before it crashes. Then step over the crash and you should se the crash in the debug console or in the logcat output. If for some reason they are not there, you can run adb logcat in the terminal and watch the output as you run your application and it will log the crash there.
Logcat tool in Android Studio

You can find more information on command-line logcat https://developer.android.com/studio/command-line/logcat


text:
Q: How to delete all lines before the first and after the last occurrence of a string? cat grab.txt
My Dashboard
Fnfjfjf. random test
00:50

1:01:56
My Notes
No data found.

Change Language                                                                                + English

Submit

Estimation of Working Capital Lecture 1

Estimation of Working Capital Lecture 2

Estimation of Working Capital Lecture 3

Money Market Lecture 254

Money Market Lecture 255

Money Market Lecture 256

International Trade Lecture 257

International Trade Lecture 258

International Trade Lecture 259
Terms And Conditions
84749473837373
Random text fifjfofifofjfkfkf

I need to filter this text after doing the following

*

*Delete all lines before the first occurrence of word - Lecture

*Delete all lines after the last occurrence of word - Lecture

*Remove all empty lines

Expected output
Estimation of Working Capital Lecture 1
Estimation of Working Capital Lecture 2
Estimation of Working Capital Lecture 3
Money Market Lecture 254
Money Market Lecture 255
Money Market Lecture 256
International Trade Lecture 257
International Trade Lecture 258
International Trade Lecture 259

What have I tried so far?
cat grab.txt | sed -r '/^\s*$/d; /Lecture/,$!d'

After searching for a bit and some trial-error, I am able to remove empty lines and remove all lines before the first occurrence but unable to remove all lines after the last occurrence.
Note - Even tho my existing command is using sed, its fine if the answer is in awk, perl or grep

A: Could you please try following. Written and tested with shown samples with GNU awk.
awk '
/Lecture/{
  found=1
}
found && NF{
  val=(val?val ORS:"")$0
}
END{
  if(val){
    match(val,/.*Lecture [0-9]+/)
    print substr(val,RSTART,RLENGTH)
  }
}'  Input_file

Explanation: Adding detailed explanation for above.
awk '                                        ##Starting awk program from here.
/Lecture/{                                   ##Checking if a line has Lecture keyword then do following.
  found=1                                    ##Setting found to 1 here.
}
found && NF{                                 ##Checking if found is SET and line is NOT NULL then do following.
  val=(val?val ORS:"")$0                     ##Creating va and keep adding its value in it.
}
END{                                         ##Starting END block of this code here.
  if(val){                                   ##Checking condition if val is set then do following.
    match(val,/.*Lecture [0-9]+/)            ##Matching regex till Lecture digits in its value.
    print substr(val,RSTART,RLENGTH)         ##Printing sub string of matched values here to print only matched values.
  }
}' Input_file                                ##Mentioning Input_file name here.

A: Simply using grep 'Lecture' file with the input you have shown in file will work:
$ grep 'Lecture' file
Estimation of Working Capital Lecture 1
Estimation of Working Capital Lecture 2
Estimation of Working Capital Lecture 3
Money Market Lecture 254
Money Market Lecture 255
Money Market Lecture 256
International Trade Lecture 257
International Trade Lecture 258
International Trade Lecture 259

(note: this simply grabs all the lines containing Lecture. See @RavinderSingh13 answer for protecting against non-Lecture lines in between)

A: You could replace matches of the following regular expression (with the multiline flag set) with empty strings using your tool of choice. The regex engine need only support negative lookaheads.
\A(?:^(?!.*\bLecture\b).*\r?\n)*|^\r?\n|^.*\r?\n(?![\s\S]*\bLecture\b)

Start your engine!
The regex engine performs the following operations.
\A                  : match beginning of string (not line)
(?:                 : begin a non-capture group
  ^                 : match beginning of line
  (?!.*\bLecture\b) : assert the line does not contain 'Lecture'
  .*\r?\n           : match the line
)                   : end non-capture group
*                   : execute the non-capture group 0+ times
|                   : or
^\r?\n              : match an empty line
|                   : or
^.*\r?\n            : match a line
(?!                 : begin a negative lookahead
  [\s\S]*           : match 0+ characters, including line terminators
  \bLecture\b       : match 'Lecture'
)                   : end negative lookahead

A: Print everything starting from the first occurrence of the pattern,
reverse the file,
print everything starting from the first occurrence of the pattern,
then reverse the result:
awk "/Lecture/,0" file.txt | tac | awk "/Lecture/,0" | tac


text:
Q: Integrating paypal with c++ MFC app We are planning to integrate Paypal with one of our cpp application written using MFC. The question is shall we use Rest apis to accomplish this? or there is any other easier way to do achieve this? I have recently used  Paypal REST Services via Postman and they look pretty easy. What I want to achieve is how can I use rest apis for paypal without launching the browser ? How can I achieve Login credentials from the user ? Can anyone point me to right direction ?
Appreciate your help in advance.
Thanks
AJ

A: I'd suggest using PayPal REST API https://developer.paypal.com/docs/api/ as they putting more effort into it. There is also SOAP API, but I would not use it. It seems like dated.
You can use ultra modern Casablanca C++ REST SDK which is an open source framework from Microsoft available at: https://github.com/Microsoft/cpprestsdk to implement your end-point.

A: You can do that using Wizdome which is c++ / MFC oriented. A product named Datattoo recovery developed under c++ and MFC allows paying for the amount of data successfully recovered, and the integration with PayPal is done that way.
Here is a more detailed description about the process:


text:
Q: Setting an Embers.js property from within Handlebars.js I have a site that is using Node.js with Jade on the backend, and on the client-side I am using Handelbars.js with Embers.js.  I am passing a property into my .jade template for my flickr apiKey, so that I can keep all these keys in one server side json file.  I then want to set my Embers flickrPhotoSearchRequestModel's property in the html, so that it can use it to access the api.
I am trying to do
script(type='text/x-handlebars')
  {{Piccee.flickrPhotoSearchRequestModel.set('api_key', 1)}}

But, that does not seem to work.
FlickrController.js
Piccee.FlickrPhotoSearchRequestModel = Em.Object.extend({
api_key: "",
searchTerm: "",
page: 1,
url: function() {
    var url = "http://api.flickr.com/services/rest/?method=flickr.photos.search";
    url += '&api_key=' + this.get("api_key");
    url += '&tags=' + this.get("searchTerm");
    url += '&text=' + this.get("searchTerm");
    url += '&page=' + this.get('page');
    url += '&sort=interestingness-desc&extras=url_sq%2C+url_t%2C+url_s%2C+url_q%2C+url_m%2C+url_n%2C+url_z%2C+url_c%2C+url_l%2C+url_o&format=json&nojsoncallback=1';
    return url;
}.property('api_key', 'searchTerm', 'page'),
});

Piccee.flickrPhotoSearchRequestModel = Piccee.FlickrPhotoSearchRequestModel.create({
api_key: "123",
searchTerm: "",
page: 1

});
In .js, that above set method would work just fine, it just won't work in the Handelebar's template.

A: Ember does not execute what is in the brackets, so trying something like a set will not work.  Instead you should create a View and take in your data as parameters (ie "api_key").  Now I would normally recommend doing this via bindings so stuff could update/propagate but your data is generated in the HTML and only needs to be executed on once... So you might try something like this:
<script type='text/x-handlebars'>
    {{#view SomeView api_key=1}}
        <a {{bindAttr href="piccee.url"}}>Some Pics</a>
    {{/view}}
</script>

Then:
SomeView = Em.View.extend({
    api_key: null,
    piccee: null,

    init: function(){
        this._super();
        this.set('piccee', Piccee.FlickrPhotoSearchRequestModel.create({
            api_key: this.get('api_key');
        }));
    }
});

If you are having trouble with this, let me know and I will create a fiddler.
All that being said, you could also register your own handlebars helper (though Ember.Handlebars.registerHelper) which can take in parameters and draw a view.  It essentially makes a widget; I would only go down this path once you had the view working and you knew you wanted to use it over and over again.
EDIT: So, now we want bind that value instead of setting it initially.  You can reference parentViews in your paths which makes things like this kind of nice.
{{#view SomeHeaderView api_key=1}}
    ...
    stuff & things
    ...

    {{#each myList}}
        {{#view SomeView}}
            ... link here ...
        {{/view}}
    {{/each}}
{{/view}}

And inside that url (change the api_key to be parentView.api_key):
...
url: function() {
    var url = "http://api.flickr.com/services/rest/?method=flickr.photos.search";
    url += '&api_key=' + this.get("parentView.api_key");
    url += '&tags=' + this.get("searchTerm");
    url += '&text=' + this.get("searchTerm");
    url += '&page=' + this.get('page');
    url += '&sort=interestingness-desc&extras=url_sq%2C+url_t%2C+url_s%2C+url_q%2C+url_m%2C+url_n%2C+url_z%2C+url_c%2C+url_l%2C+url_o&format=json&nojsoncallback=1';
    return url;
    }.property('parentView.api_key', 'searchTerm', 'page'),
...

I usually end up with a view because I find I want more then simple operations and it is legit.  I am still not 100% sure I follow, but I think this is the direction you are going.


text:
Q: Laravel 5.5, error when the database row is null on paginate: Call to a member function paginate() on null I have written some code to show a crud table with some internet radio stations, I want to show the first created internet radio stations to show as the first item or the number one in the table.
The code works when there's at least one internet radio station in the database, but doesn't work on null.
I have written the following code in the controller:
$internetradiostations = Internetradiostations::first()->paginate(5);
    return view('internetradiostationsviewer',
        compact('internetradiostations'))
        ->with('i', (request()->input('page', 1) -1 ) *5); `

When executing i get the following error when there's no internet radio station in the database:
Call to a member function paginate() on null
Strangely the code still works on null and doen't give errors when using
Internetradiostations::latest()->paginate(5);
instead of:
Internetradiostations::first()->paginate(5);

A: You don't need to paginate data with a single element. Just keep-
$internetradiostations = Internetradiostations::first();

If you want to paginate then remove first()-
$internetradiostations = Internetradiostations::paginate(5);


text:
Q: npm install -g @vue/cli but INSTALL ERROR This is my environment..

*

*MacOs Big Sur version 11.2.3

*npm version 7.15.1

*node version version 16.3.0

Below is my error..
npm WARN deprecated @hapi/topo@3.1.6: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/bourne@1.3.2: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated @hapi/address@2.1.4: Moved to 'npm install @sideway/address'
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated @hapi/hoek@8.5.1: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/joi@15.1.1: Switch to 'npm install joi'

changed 943 packages, and audited 944 packages in 16s

59 packages are looking for funding
  run `npm fund` for details

13 vulnerabilities (3 moderate, 10 high)

Some issues need review, and may require choosing
a different dependency.

Run `npm audit` for details.

I try again and again.. but it's not work.
Please help me!!

A: We miss a few infos here; you say that you get an install error, but these are just warnings about deprecated dependencies. Moreover, these dependencies doens't look much related to @vue/cli itself…
Are these globally installed dependencies? You might wanna use npm-check and use it globally to see if these are old global dependencies that you should get uptodate (or get rid of):
$ npm-check -ug

A: I have resolved in this method:

*

*npm uninstall –g @ionic/cli

*install nodejs

*Reinstall again: npm install –g @ionic/cli

A: For Mac users
First, Uninstall angular/cli: sudo npm uninstall -g @angular/cli
Then, go to https://www.brew.sh/ and copy the link below Install Homebrew and paste it to the terminal and hit enter.
Then, type: brew install angular-cli and hit enter.
Finally, check the version: ng --version


text:
Q: What's the common way to check if a field is null or undefined (but not zero or empty string) in Javascript? I know I can't do if (!obj.x) because if obj.x is 0 or "", it will be "truthy".
Option 1: I could do if (obj.x === null || obj.x === undefined).
Option 2: But could I just do if (obj.x == null)?
Just to be clear, I want a condition that is true when obj.x is null or undefined, but false for any other value.
According to the comments, both options are equivalent but option 2 is more clear. I agree.
EDIT:
Someone pointed out that there are similar questions (see links above), but in this case I was thinking of fields, rather than variables. The difference is that fields can be undefined and there is no runtime error when using them. I updated my question accordingly.
EDIT 2:
This question was closed because there are similar questions. I think there is a slight difference here, because in my question I'm checking a field/property of an object, not a variable, so the typeof operator is not needed.


text:
Q: How to execute a function on Console closing in C# I have a simple C# Console Application and I want to execute a function when the user is closing the Console Application. So I need an event probably, which fires a function on pressing Ctrl + C, clicking the close button or writing something into the console to shut down. I tried every single code snippet on Stackoverflow and other pages but none of them worked on all cases. One solution worked for everything during debugging the Application in Visual Studio, however on running the compiled exe File in a Console Prompt, it didn't work on Ctrl + C and clicking the close button. Can anyone help me?
Here's my code in the Main class:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;

namespace BankClient
{
    class Program
    {
        private static DB _db;
        private static string _notUpdatedUsersCsvFilePath;

        static void Main(string[] args)
        {
            BankServer server = new BankServer();
            _db = new DB();
            _notUpdatedUsersCsvFilePath = "not_updated_users.csv";

            if (File.Exists(_notUpdatedUsersCsvFilePath))
            {
                string[] lines = File.ReadAllLines(_notUpdatedUsersCsvFilePath);

                if (lines.Length > 0)
                {
                    Console.WriteLine($"Es sind noch unbearbeitete Einträge von Kunden vorhanden, welche nicht in der Datenbank aktualisiert werden konnten:");
                    foreach (string l in lines)
                    {
                        Console.WriteLine($"{l.Split(';').First().Trim()} {l.Split(';').Last().Trim()}");
                    }
                    Console.WriteLine();
                }
            }

            Console.WriteLine("Fetching DB...");
            if (_db.fetchDB()) Console.WriteLine("Fetched DB successfully.");
            else
            {
                Console.WriteLine("An error occured whilst fetching DB!");
                Console.ReadLine();
                return;
            }

            Console.WriteLine();
            foreach (Kunde k in _db.Kunden)
            {
                Console.WriteLine($"- {k.Vorname} {k.Nachname} ({k.Id}) -> Kontostand: {k.Kontostand}");
            }

            Console.WriteLine();

            Kunde kunde = _db.Kunden.Find(k => k.Id == 1);

            if (kunde == null)
            {
                Console.ReadLine();
                return;
            }

            kunde.Kontostand += 100;
            kunde.ChangeMade = true;

            Console.WriteLine($"{kunde.Vorname} {kunde.Nachname} ({kunde.Id}) -> Kontostand: {kunde.Kontostand}");

            Console.ReadLine();

            onClosing();
        }

        private static bool onClosing()
        {
            bool error = false;

            Console.WriteLine("Stopping application...");
            Console.WriteLine("Updating DB...");

            Dictionary<bool, string> tmpDB = _db.saveDB();

            if (tmpDB.ContainsKey(true))
            {
                Console.WriteLine("Updated DB successfully.");
            }
            else
            {
                error = true;
                Console.WriteLine(tmpDB[false]);

                foreach (Kunde k in _db.Kunden)
                {
                    if (k.ErrorMessage != null)
                    {
                        File.AppendAllText(_notUpdatedUsersCsvFilePath, $"[{DateTime.Now}];" + $"{{id: {k.Id}, vorname: \"{k.Vorname}\", nachname: \"{k.Nachname}\", kontostand: {k.Kontostand.ToString().Replace(',', '.')}, filiale: {k.Filiale}, status: {k.Status}, errorMessage: \"{k.ErrorMessage}\"}}" + Environment.NewLine);
                    }
                }
            }

            if (!error)
            {
                Thread.Sleep(5000);
                Environment.Exit(-1);
                return true;
            }

            Thread.Sleep(10000);
            return false;
        }
    }
}

Best regards,
Steven


text:
Q: Getting no matching results for query mysql php I am trying to find matching results to my query in my database and put it in the table form I made, however I get no matching results back. I ran my query in phpmyadmin and got the desired output. I used var_dump on my $result variable and get the following: resource(4) of type (mysql result). here is my code:
<?php
function renderSearchForm($search, $search_by, $search_by, $error){
?>
<!DOCTYPE HTML5>

    <title>Search Query</title>

<?php
//display errors
    if($error != ''){
        echo '
' . $error . '
';
    }
?>

<form action="" method="post">

Search For:

Name: * <input type="text" name="search" value="<?php echo $search; ?>" />

Search by:

<input type="radio" name="search_by"
<?php if (isset($search_by) && $search_by=="firstname") echo "checked";?>
value="firstname"/>Firstname*
<input type="radio" name="search_by"
<?php if (isset($search_by) && $search_by=="surname") echo "checked";?>
value="surname"/>Surname*

<input type="submit" name="submit" value="Submit">

* required

</form>

<?php
}

//connect to db
include('connect_db.php');

//check if submitted
if (isset($_POST['submit'])) {
    $search = mysql_real_escape_string(htmlspecialchars($_POST['search']));
    $search_by = mysql_real_escape_string(htmlspecialchars($_POST['search_by']));

    //check if search is empty
    if (empty($_POST["search"])) {
         $error = "Error: Name is required";

         //error, display form
         renderSearchForm($search, $search_by, $search_by, $error);
         }

         elseif
         // check if name only contains letters and whitespace
          (!preg_match("/^[a-zA-Z ]*$/",$search)) {
           $error = "Error: Only letters and white space allowed";

         //error, display form
         renderSearchForm($search, $search_by, $search_by, $error);
         }

         //check if radio button selected
         elseif (empty($_POST["search_by"])) {
         $error = "Error: Search_by is required";

         //error, display form
         renderSearchForm($search, $search_by, $search_by, $error);
         }else{
            //save data
            $query =  "SELECT * FROM members WHERE '$search_by' LIKE '%$search%'";
            $result = mysql_query($query)
            or die(mysql_error());
            var_dump($result);

            //display data from db
            echo "
";
            echo "
 ID	 Firstname	 Surname	 Telephone	 Cell	 Address
";

            //loop through results of db and display in table
            while ($row = mysql_fetch_array($result)) {
                //echo contents in table
                echo "
";
                echo "" . $row['id'] . "	";
                echo "" . $row['firstname'] . "	";
                echo "" . $row['surname'] . "	";
                echo "" . $row['telephone'] . "	";
                echo "" . $row['cellphone'] . "	";
                echo "" . $row['address'] . "	";
                echo "Edit	";
                echo "Delete	";
                echo "
";
             }

             echo "
";

             //This counts the number or results
             $anymatches=mysql_num_rows($result);
             if ($anymatches == 0)  {
             echo "Sorry, but we can not find an entry to match your query

";
             }
             //And we remind them what they searched for
             echo "Searched For: " .$search. " In: " .$search_by;
             }

}else{
    //if form not submitted, display form
    renderSearchForm('','','','');
}
?>

A: You need to remove the single quotes between $search_by. Try this:
"SELECT * FROM members WHERE $search_by LIKE '%$search%'"


text:
Q: Windows search can't find .lvm-files? (files created by Native Instruments' LabView) I have gotten several files for several kinds of measurements. They were generated by some ADC (specific type does not matter) and the necessary software Labview, which are both made by Native Instruments. The files are of the type .lvm. Opening them with Excel is no problem, I processed them as I deemed necessary. So I had no problem there so far.
But I can't find them via Windows search. This makes cleaning them up/sorting them and other stuff rather tedious. :/ Does anyone know how I can enable Windows to find them?

A: Not all file types are enabled by default. However it is simple to change this.

*

*Click on the Start button, type Indexing and select "Indexing Options"

*Click on "Advanced" (this may trigger UAC)

*Click on the "File Types" tab, search for the file type you want and make sure the tickbox next to it is selected

*Click on "Ok" and then "Close".

If you're not prepared to wait for Windows to find all those files (which, depending on how many you have, may take a while), then you can force a re-index by not performing step 4 and clicking on "Rebuild" instead.
Be warned though that this could also take a long time as you are essentially deleting the entire database and rebuilding it from scratch. Personally, I'd just leave the computer idle for a couple of hours and let Windows find those files as it would normally.


text:
Q: Adding Edit Row Action to TableView that uses Fetch Controller? I have a table that uses a coredata fetch to populate its self, the fetch controller stores the delete row action.
However I want to add an edit feature to the row as well, I dont seem to be able to add this along side the delete feature I currently have and need to use editActionsForRowAt to get it to appear.
When i use editActionsForRowAt it overrides by existing Fetch Controllers row actions and causes the delete to no longer work.
Any idea how I can add just an edit next to the existing delete without over writing or messing with the fetch results controller?
Here is the code for the fetch controller that is the source for the table and its delete case and delete func, I want to ideally add an edit button to this, without having to overwrite it all with editActionsForRowAt
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        switch (type) {
        case .insert:
            if let indexPath = newIndexPath {
                workoutDesignerTable.insertRows(at: [indexPath], with: .fade)
            }
            break;
        case .delete:
            if let indexPath = indexPath {
                workoutDesignerTable.deleteRows(at: [indexPath], with: .fade)
            }
            break;
        case .update:
            if let indexPath = indexPath, let cell = workoutDesignerTable.cellForRow(at: indexPath) as? RoutineTableViewCell {
                configure(cell, at: indexPath)
            }
            break;
        default:
            print("...")
        }
    }

    // MARK: - DELETING TABLE ROW

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let UserExercise = fetchedResultsController.managedObjectContext
            UserExercise.delete(self.fetchedResultsController.object(at: indexPath))
            do {
                try UserExercise.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

For more information please find the below screenshot of current Table Row Edit Actions.

A: From the documentation tableView(_:editActionsForRowAt:)

Use this method when you want to provide custom actions for one of your table rows. When the user swipes horizontally in a row, the table view moves the row content aside to reveal your actions. Tapping one of the action buttons executes the handler block stored with the action object.
If you do not implement this method, the table view displays the standard accessory buttons when the user swipes the row.

So you need to also pass the delete action button with your other buttons.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let btnEdit = UITableViewRowAction(style: .default, title: "Edit") { action, indexPath in
         //Put the code of edit action
    }
    let btnDelete = UITableViewRowAction(style: .destructive, title: "Delete") { action, indexPath in
         //Put the code of delete action
    }
    return [btnEdit, btnDelete]
}

Note: If you are implementing tableView(_:editActionsForRowAt:) then there is no need to implement tableView(_:commit:forRowAt:) method.


text:
Q: How to resolve this : Execution of batch script terminates after a specific command but runs fine when commandd is executed manually I have a requirement to run commands in the following order to automate the testing process:
cd "jakarta-jmeter-2.5.1\bin"
jmeter -n -t  "Cmd-Try-Shared-AQ.jmx" -l log.jtl -Jthreads=10
cd "../lib/ext"
java -jar JMeterPluginsCMD.jar --generate-csv test.csv --input-jtl log.jtl --plugin-type AggregateReport

After executing the JMeter command batch file terminates and does not process next command that is changing the current directory. I tried to troubleshoot by placing PAUSE to see if it reaches the next line but of no help, it simply terminates after executing the second command. If execute the same 4 commands manually one after the other they all execute fine.
Please help.

A: Use "call jmeter -n -t ..." since it is another cmd file and Command Prompt requires calls.

A: Andrey is right -- if jmeter is a batch file you must use "call".  The reason is that if you call a batch file from another, the first one will exit after executing the 2nd one, unless it is called with "call".
Here's an example:
Foo1.bat
foo2.bat
echo foo1

Foo2.bat
echo foo2

It seems like if you run Foo1.bat, it will spit out both "foo1" and "foo2" but it does not:
C:\temp>foo1

C:\temp>foo2.bat

C:\temp>echo foo2
foo2

To change the behavior, Foo1.bat should look like this:
foo1.bat
    call foo2.bat
    echo foo1


text:
Q: Android Location Services not working Here goes: I've spent all night scouring the internet, especially StackOverflow, trying to figure out why I can't get basic Location Services working in Android. I have tried in a variety of emulated environments, from Android 1.6 up to Android 4, all with GPS services emulated, as well as on an actual Android 2.2.2 Device. Location is always returned as null, I've tried at least seven different downloadable sample projects, using them verbatim, and getting the same results.
Obviously, I'm missing something key. If anyone could point out what I'm doing wrong, it would be greatly appreciated.
com.mytestproject.android:
package com.mytestproject.android;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.mytestproject.android.R;
public class MyTestProject extends Activity {
private TextView mytext;
private LocationManager locmgr = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mytext = (TextView) findViewById(R.b.mytext);

    //grab the location manager service
    locmgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    mytext.setText("waiting for location");
}

//Start a location listener
LocationListener onLocationChange=new LocationListener() {
    public void onLocationChanged(Location loc) {
        //sets and displays the lat/long when a location is provided
        String latlong = "Lat: " + loc.getLatitude() + " Long: " + loc.getLongitude();
        mytext.setText(latlong);
    }

    public void onProviderDisabled(String provider) {
    // required for interface, not used
    }

    public void onProviderEnabled(String provider) {
    // required for interface, not used
    }

    public void onStatusChanged(String provider, int status,
    Bundle extras) {
    // required for interface, not used
    }
};

//pauses listener while app is inactive
@Override
public void onPause() {
    super.onPause();
    locmgr.removeUpdates(onLocationChange);
}

//reactivates listener when app is resumed
@Override
public void onResume() {
    super.onResume();
    locmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,10000.0f,onLocationChange);
}
}

main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/mytext"
android:textSize="15pt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.johnandbrian.android"
    android:versionCode="1"
    android:versionName="1.0" >

<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES"></uses-permission>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".MyTestProject"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</manifest>

A: add this to onCreate() function,
locmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,10000.0f,onLocationChange);

A: If onLocationChanged() isn't even being called, even with sample projects, then I don't think "location is always null" is an accurate description of the problem. onLocationChanged() is only called when the location changes. So it sounds like you are (a) not injecting mock locations or otherwise driving the location engine when using the emulator, and (b) not moving around enough on the real device. I suggest loading a sample project onto the real device, going outside, and moving around some (several 10s of meters). Put some breadcrumbs in the onLocationChanged() method (in the sample project) to verify that it's being called.


text:
Q: Приходят пустые заявки в Telegram Вот мой код, не пойму в чем кроется причина. Приходят с различной переодичностью полностью пустые, хотя я захожу на сайт заполняю данные и все доходит как нужно.
 <?php
    $name = $_POST['user_name'];
    $telegram = $_POST['user_telegram'];
    $description = $_POST['user_description'];
    $id_user = $_POST['id_user'];
    $token = "";
    $chat_id = "";
    $worker_chat_id = "";

    $arr = array(
      'id: ' => $id_user,
      'Name: ' => $name,
      'Telegram: ' => $telegram,
      'Description' => $description
    );

    foreach($arr as $key => $value) {
      $txt .= "".$key." ".$value."%0A";
    };

    $arr_worker = array(
      ""=>'Пришла новая заявка',
      'id: ' => $id_user,
    );

    foreach($arr_worker as $key => $value) {
      $txt_worker .= "".$key." ".$value."%0A";
    };

    $sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}","r");

    $sendToTelegram_2 = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$worker_chat_id}&parse_mode=html&text={$txt_worker}","r");

    if ($sendToTelegram and $sendToTelegram_2) {
      header('Location: /success');
    } else {
      echo "Error";
    }
    ?>