text:
Q: In ReactJS, if we don't supply a dependency array for useEffect, it can cause the function to be called every time? I saw in the ReactJS docs that the dependency array in useEffect(fn, []) is optional, and not supplying it should be the same as supplying an empty array.
However, if I have the code as on: https://codesandbox.io/s/trusting-sunset-h6ip9?file=/src/Count.js
  useEffect(() => {

    console.log("SETTING INTERVAL");

    setInterval(() => {
      console.log("NOW", Date.now() / 1000);
      setDuration(Date.now() - startTime);
    }, 1000);

  }, []);

With the [] above, everything runs as expected. However, if I remove it and run again, as can be seen on:  https://codesandbox.io/s/dreamy-platform-l93bv?file=/src/Count.js
We can see in the Developer's console or Codesandbox.io's console that  the line "SETTING INTERVAL" is continuously being printed.
Supposedly, I thought having the empty array and not having in should make no difference, but in this case we need to put it in? What is the reason?

A: Very simply put, the array you provide is telling useEffect that it should run when the values inside the array changes. Since the value is static it will only run once. If you remove the array it will run on every render. You can also put a variable inside the array to tell useEffect to update whenever the variable changes.

A: There is a major and quite obvious difference between an empty array and an 'no deps'.
When you use an empty array, you are actually using componentDidMount in class components. But if you do not leave the same empty array, you will see that your counter does not work well.
If you do not want to use an empty array, you must clean up your useEffect.
See docs about "Effects Without Cleanup"
The reason the function does not work properly is that every time your component is updated, the counter also runs very fast. But with a simple clean up command this problem can be solved.
See docs about "Effects with Cleanup"
You can see an example for your hooks bellow:
  useEffect(() => {
    console.log("SETTING INTERVAL");
    setInterval(() => {
      console.log("NOW", Date.now() / 1000);
      setDuration(Date.now() - startTime);
      return function cleanup() {
         return 0;
         // Also you can use 'clearInterval' here or anything else to stop rendering more
      };
    }, 1000);
  });

A: you need use like this:
useEffect(() => {
   const interval = setInterval(() => {
      console.log("NOW", Date.now() / 1000);
      setDuration(Date.now() - startTime);
    }, 1000);
   return ()=> clearInterval(interval)
  }, []);


text:
Q: SQL Server : compare two JSON String to find the difference I've not worked JSON that much but a client has asked for a report to see the difference between two columns in a log table (there is 30 tables all together).
The columns I'm interested are originalRecord and newRecord in the log table.
Each column holds all the JSON objects from a screen, lets say 30 text fields, drop down lists etc. The originalRecord holds the record before the change, and newRecord after the update.
An example, status change from Open to Closed, originalRecord has all 30+ fields and status "Open" and newRecord has all 30+ fields and status "Closed"
I'm trying to find a way I can compare ALL JSON Objects for a record and the difference between the two columns.
I know JSON_VALUE can compare a JSON Object such as
IIF(JSON_VALUE(OriginalRecord, '$.status')<> '', NULL, JSON_VALUE(NewRecord, '$.status'))

but I don't want to hardcode every object like above as they do change over time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mathematica permutes indices when reading Matlab files I wrote the following Matlab script:
A=reshape(1:(3*4*5),[3,4,5]);
size(A)
save('A.mat','A');

B=reshape(1:(7*8),[7,8]);
size(B)
save('B.mat','B');

C=reshape(1:(2*3*4*5),[2,3,4,5]);
size(C)
save('C.mat','C');

and it ouput
ans =
     3     4     5
ans =
     7     8
ans =
     2     3     4     5

which shows that indices go increasing.
Then I read these tensors with Mathematica:
In[20]:= mat = Import["A.mat", "LabeledData"];
In[15]:= Dimensions["A" /. mat]
Out[15]= {5, 3, 4}
In[21]:= mat = Import["B.mat", "LabeledData"];
In[17]:= Dimensions["B" /. mat]
Out[17]= {7, 8}
In[22]:= mat = Import["C.mat", "LabeledData"];
In[23]:= Dimensions["C" /. mat]
Out[23]= {5, 4, 2, 3}

which shows that first two Matlab indices go to tail in the same order and remaining indices go from the beginning in reverse order.
Is this behaviour by design or by bug? Can I read somewhere about exact rules of index transposing during import?
I see no word about it here.

A: My personal opinion is that this is a bug.
Our MATLink package handles this well.
In[1]:= << MATLink`

In[2]:= OpenMATLAB[]

In[3]:= MEvaluate[
 "a=reshape(1:(3*4*5), [3,4,5]);
 size(a)"]

Out[3]= ">>
ans =

     3     4     5

"

In[5]:= Dimensions@MGet["a"]

Out[5]= {3, 4, 5}

Update:
I looked at the implementation of the MAT5 file importer. It is written in pure Mathematica.  The relevant section is this:

It gives the impression that this is done quite deliberately.  Therefore I no longer think that it is a bug, but I do not know why it is done this way.
If you want to transfer data to/from MATLAB, and have both Mathematica and MATLAB installed on the same computer, I still recommend using MATLink.

A: as a workaround use hdf5
A=reshape(1:(3*4*5),[3,4,5]);
h5create('xyz.hdf5','/A',[3,4,5])
h5write('xyz.hdf5','/A',A)

mathematica
a=Import["xyz.hdf5", "Data"][[1]]

this is fully reverse indexed..
Dimensions[a]

{5,4,3}

reverse the index order to be matlab-like:
a = Transpose[a, Reverse@Range@ArrayDepth@a]];
Dimensions[a]

{3,4,5}


text:
Q: Capture whole android screen from service without root I need to capture whole android screen from service code and save bitmap to sd card.
I dont have root, so cant use framebuffer. And I cant depend on debug server.
There is ASL http://code.google.com/p/android-screenshot-library/, but is there a way to do that without installing some native service, only from my code?

A: Fortunately, this is not possible, for obvious privacy and security reasons.

A: you could get your app to have a transparent view so.when a screenshot is about to be taken the app opens the view then screenshots the view


text:
Q: Run-time error '1004': Method 'Range' of object '_Global' failed Visual Basics Hi I am struggling to get my code to run and would really appreciate some help as it is my first time working with Visual Basics.
Error:
Run-time error '1004': Method 'Range' of object '_Global' failed
Part of code highlighted as error:
Dim i As Long, lastrow As Long
lastrow = Cells.Find(What:="*", _
After:=Range("Ai"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row

Yellow arrow next to this line: MatchCase:=False).Row
Solution:
Changed
After:=Range("Ai"), _

to
After:=Range("A" & Rows.Count), _

A: Try changing
After:=Range("Ai"), _

with
After:=Range("A" & i), _

Anyhow, a simple way of obtaining the last row of A:A column would be:
LastRow = Range("A" & rows.count).End(xlup).row


text:
Q: facing error "FileSystemWallet is not a constructor" while executing enrollAdmin.js Facing error "TypeError: FileSystemWallet is not a constructor"
on line const wallet = new FileSystemWallet(walletPath);
Details are as below "
NPM version : 6.14.4
Node Version: v10.21.0
below is the code trying to execute, Please help on this and Thanks in advance.
'use strict';
const FabricCAServices = require('fabric-ca-client');
const { FileSystemWallet, X509WalletMixin } = require('fabric-network');
const fs = require('fs');
const path = require('path');

const ccpPath = path.resolve(__dirname, 'connection-banka.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);

main();

async function main() {
try {
    const caInfo = ccp.certificateAuthorities['ca.banka.example.com'];
    const caTLSCACerts = caInfo.tlsCACerts.pem;
    const ca = new FabricCAServices(caInfo.url, { trustedRoots:caTLSCACerts, verify: false }, caInfo.caName);
    const walletPath = path.join(process.cwd(), 'wallet-BankA');
    console.log(`Wallet path: ${walletPath}`);
    const wallet = new FileSystemWallet(walletPath);
    console.log(`Wallet : ${wallet}`);

    const adminExists = await wallet.exists('admin');
    if (adminExists) {
        console.log('An identity for the admin user "admin" already exists in the wallet');
        return;
    }

    const enrollment = await ca.enroll({ enrollmentID: 'admin',enrollmentSecret: 'adminpw' });
    const identity = X509WalletMixin.createIdentity('bankaMSP',enrollment.certificate, enrollment.key.toBytes());
    await wallet.import('admin', identity);
    console.log('Successfully enrolled admin user "admin" and imported it into the wallet');
    }
    catch (error) {
        console.error(`Failed to enroll admin user "admin": ${error}`);
        process.exit(1);
        }
}

A: I ran into this issue recently too and I think it's because the master branch of the fabric-sdk-node package doesn't have that class any longer. They've moved from FileSystemWallet in v1.4 to FileSystemWalletStore in v2.2 / the current master branch.
Try:
...
const { Wallets, X509WalletMixin } = require('fabric-network');
...
async function main() {
   ...
   const wallet = await Wallets.newFileSystemWallet(walletPath);
   ...
}

I'm still trying to work out how to open an existing wallet without overwriting an existing so I'll update this post if/when I figure it out.


text:
Q: Drill motor improvement to avoid component wear when shut off Story
Get my hands on two Metabo (made in Germany) cordless DC battery powered hand drills previously thrown away because of..... the batteries, how sad. The overall construction is simple however pretty stiff and clever designed with quality components.... a keeper! "The Post Apocalyptic Inventor" aka TPAI made a video about making obsolete tools useful again. The solution is simple, use an external battery or PSU to power the tool by installing a connector. I did it a little different, used a different and more regular connector and install the connector on a different location. The result is actually equal to the TPAI version.

Problem
At the first try, I notice that after starting the motor (huge inrush current anyway) it stops immediately (with some reverse turn shake feedback). Through the ventholes of the motor I noticed some huge sparks when the motor stops. This abrupt "kick out" behaviour is not very healthy for the switches, bearings, the gears and the brushes, possibly effecting the lifetime of the device. I have notice similar behaviour at other brands, only at high speeds and release the (speed controlled) trigger quickly. These ones has no electronic speed control, it is just on or off in selected direction.
When disconnect the power source (remove it), this problem does not occur and the motor slows down by friction and power loss.
After figuring out how it works (very clever designed in matter of simplicity of construction) I understand why.

The motor is shorted (in feedback/generator state) when releasing the power trigger, because of the clever configuration of the two 2-state power on slash direction switches in parallel. However this results in a huge feedback current and build up coil voltage inside the motor. That is the reason why the brushes spark intens and the motor stops immediately after high speed rotations. To avoid feedback to the batteries this is good but can have some negative impact on other components because of the sparks and internal feedback force.

Question

*

*I have tried to design a new addon solution (mod) in the existing
configuration. Cut the negative lead and added two diodes and a
resistor. I am not a professional so I wonder if this is a plausible
solution to slow down the decrease of speed and limit the feedback
current/voltage inside the circuit. What do you think, it this okay?

*If this solution is plausible, why manufacturers do not apply this
even at quality tools? To avoid the best quality? Wear is a selling
point?

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. A pair of diodes can snub the motor when running in either direction.
The diodes will conduct only during transition of SW1 or SW2.

simulate this circuit
Figure 2. Simulation circuit.

Figure 3. Simulation results. Top: voltage at Node 1. Bottom: current traces.

*

*SW4 (representing the NO contact) opens at 0.1 s. Voltage rapidly swings negative.

*SW5 (representing the NC contact) closes at 0.2 s.

*D3 keeps the current running through the motor.

*The current through the NC contact decays from a low initial value to zero.

A: One possible solution would be to replace the diodes in your idea with NTC thermistor current surge devices. You can get them rated at 25 amps with an initial resistance of 2 ohms and resistance of 0.02 ohms at rated current. It would cause a delay before maximum current would be available. When the switch is turned off, the motor would see the 2 ohms of the cold thermistor, so it would experience a relatively slow braking at about 6 amps initially for a 12V battery.

A: A inexpensive and relative simple solution for dynamic braking would be to place a low value in the braking circuit maybe in the 2 ohm range. This will increase the reliability as there is no semiconductors involved. When you release the switch the output voltage of the motor will rise very rapidly. initially the resistor will conduct a lot of current, as the pulse rapidly decays the current will reduce to zero. You can empirically determine what resistor you will need. As it is a pulse load, not steady state You can use a smaller resistor.

A: I like the idea with the two diodes and the break resistor. In this circuit I try to avoid the losses across the diodes using MOSFETs. This can only work, if at no time both switches are activated, but I assume this is impossible in this machine.

simulate this circuit – Schematic created using CircuitLab

*

*Activating one direction switch will enable the MOSFET on the opposite side. The low pass filters R4/C1 and R5/C2 should protect the gates from short voltage spikes, where ever they might come from.

*Releasing e.g. SW1 will activate the break resistor. There will be a short negative back EMF, that is clamped by the body diode of MOSFET M1 and the diode D2 can quickly tun off the negative path via M2.

*I added the diodes to be sure that the negative path is no longer conducting if the opposite switch is activated while the motor is still rotating. Probably not needed.

*C3 and C4 together with R1 form a snubber network to protect the contacts, this is more a question of EMI style.

I did not test this circuit, so there may be aspects I'm currently not aware of.
This sure would make the machine more expensive, I can understand why this is not implemented regulary.


text:
Q: Как удалить двойной параграф в PHP Как удалить двойной параграф в PHP?
Этот метод не работает:
preg_replace('/(\n){3,}/', '\n\n', $text);

A: Для всех систем:
preg_replace('/(' . PHP_EOL . '){3,}/', PHP_EOL . PHP_EOL, $text);

Для Unix систем:
preg_replace("/\n{3,}/", "\n\n", $text);

Для не Unix систем:
preg_replace("/(\r\n){3,}/", "\r\n\r\n", $text);

И строковые литералы, содержащие эскейп-последовательности, нужно заключать в двойные кавычки.


text:
Q: Silverlight Isolated Storage and Host Name Redirects I have a site that serves up a pretty substantial Silverlight RIA and it makes use of IsolatedStorage.  The SL app is served up from https://www.site.com/Application (MVC View that hosts the SL object tags, etc).  It is also served up from https://site.com/Application.  The problem inherent in this is that this will create two separate IsolatedStorage application because the two host names are seen as different.
My first thought was to just serve the XAP file from an absolute link instead of a relative one:
<param name="source" value="http://site.com/ClientBin/app.xap" />

But this seemed to cause weird problems when the page was served from www.site.com and the xap was served from site.com.
My next thought was to leave it a relative link, but always do a permanent redirect (301) from www.site.com/application -> site.com/application to ensure that it is always served from the same location.  Any thoughts or suggestions?  Has anyone seen this?

A: You get "wierd problems" because the host page is served from a different site than the XAP hence access to the HTMLPage and attempts to call Javascript will fail.
The use of 301 doesn't change these conditions so you still have problems.
You will need to decide which site you want the application to run from and perform a redirect on for the entire page.
Personally if I were to build a substantial RIA application I would only allow it run from one site "site.com".  I would create a "www.site.com" which redirects to the "site.com" that never actually serves any content just redirects.


text:
Q: How to determine which hardware component is broken? I have a PC which I can no longer turn on. That is, I press the power button and nothing happens, not even the CPU fan starts spinning.
I have tried removing all but the most essential components (so only leaving the PSU, motherboard, CPU and RAM), and this did not make a difference. I'm suspecting it is the PSU, however as long as a power cable is connected the LED on the motherboard does emit light.
I have tried connecting a different motherboard/CPU, and this did not make a difference. Is it safe to connect the PSU to my regular PC to see if it works? We have had two power outages recently, so I'm worried that the PSU might be sufficiently broken to cause a short when used with other (currently working) hardware. Is that even possible?
Also, my friend suggested it might just be the power button that's broken - I tested this theory by connecting the two motherboard pins using a metal object (screwdriver), and nothing happened. I am assuming that's a correct way to test that?
Thanks in advance for any advice.

A: From what it sounds like to me, and the given troubleshooting path you have taken, the power supply is probably not working properly.  While it is true that the LED light on the motherboard lights up, that doesn't mean that the PSU is fully operational.
Suggested Step:

*

*Test a known GOOD PSU in the suspect machine, to see if it works or not.  This will tell you if the issue is the PSU or perhaps the motherboard causing the issue.

Having an unprotected computer, not on a power surge protector, can wreak havoc on your PSU and system, so in the future, make sure that you protect your devices with a good surge protector.


text:
Q: Create Countdown Timer I want to create a countdown Timer in React Js in which i will user Start(To start the countdown), Stop(To stop the countdown) and reset (to reset the timer) as in the picture exemple.
As i beginner developper in React JS and in javascript globally, i started by testing the button.After that i created a function "secondPass" to calculate the remaining time and after that displaying it.The "countDown" variable is for stopping the "setinterval" after that with "clearInterval(countDown)".
The problem is that i get an error msg in the "codesandbox" plateform as in the picture.If someone can explain my error and if not to much asked help me to write a very simple code to achieve my project.
:
Here the React code:
import React from "react";

export default class Timer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      timer: 90
    };
  }

  var seconds = 1200, // Number Of Seconds

  countDown = setInterval(function() {
    secondPass();
  }, 1000);

  function secondPass() {

  var minutes = Math.floor(seconds / 60),  // To Determine The Minutes

  var remSeconds = seconds % 60;   // To Determine The Seconds

}

  resetTime() {
    this.setState({ timer: 0 });
  }
  render() {
    const { timer } = this.state;
    return (

{timer}

        <button onClick={() => this.resetTime()}>Reset</button>

    );
  }
}

A: It's because secondPass is a member function defined in the body of the Timer class. In JS, you do not need the function before it, declare it just like render: change function secondPass to secondPass

A: remove the function keyword for secondPass function. you don't need function keyword for function if you are declaring it inside a class.
make it like,
export default class Timer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      timer: 90
    };
  }

  var seconds = 1200, // Number Of Seconds

  countDown = setInterval(function() {
    secondPass();
  }, 1000);

  secondPass() {

    var minutes = Math.floor(seconds / 60),  // To Determine The Minutes

    var remSeconds = seconds % 60;   // To Determine The Seconds

  }

  resetTime() {
    this.setState({ timer: 0 });
  }
  render() {
    const { timer } = this.state;
    return (

{timer}

        <button onClick={() => this.resetTime()}>Reset</button>

    );
  }
}

A: You don't need to use function keyword when declaring functions in a class for secondPass function. It's the new ES6 syntax.


text:
Q: How to tell when an LM334 is limiting the current? I have an LM334 based constant current source configured to supply a max of 1 mA.
The load has a variable impedance. My goal is to make an alarm of sorts when that impedance exceeds a threshold, and the way I want to do that is to detect when the 334 is in current limiting mode.
When it's passing less than 1 mA of current, I would expect it to be acting like a very low-value resistor, meaning that the voltage drop across it should be low. When the 1 mA of current is reached, it should begin to increase its resistance, thus increasing the voltage drop across it.
I'd like to measure the voltage drop and light an LED (really an optoisolator) when it exceeds a threshold.
At least, that's my thinking at the present. If anyone else has an idea of how to light an LED when an LM334 is actually limiting the current through it, that would work too.

simulate this circuit – Schematic created using CircuitLab
In the schematic, I1 represents the LM334. I don't see a way in circuitlab to represent an actual LM334, so the simulation likely won't operate correctly. R1 represents the ground impedance - the goal is to detect when it's value exceeds 10k. At the moment, I'm thinking I'd like to find a way to light an LED when Vin-Vout > 1V. From there, it's just a matter of tuning either the set resistor of the LM334 or the voltage threshold to trim to the setpoint.
Note as well that the actual circuit ground is on the top side of R1 - Vout is the ground potential for the purpose of this circuit. The actual earth is on the far side of R1.

A: At 25C, the LM334 has a minimal drop-out voltage of about 0.9V between V+ and V-. If the V+ to V- drop is larger than that, the LM334 is in current regulation. Othewise, the load is getting the maximum voltage that the source can provide, and is not running at full current.
The simplest way to detect that would be by biasing a PNP transistor with a scaled-down version of the drop out voltage. When the drop out is at 1V below V+, the base would get, say, 0.7V, and the transistor would start conducting.

simulate this circuit – Schematic created using CircuitLab
This isn't superbly accurate, but might work well enough. The current through the 25kOhm R1/R2 divider is 40uA/V, and that's an error source. The divider produces about 0.72V at 0.9V drop-out. You can increase the resistance of the divider if you can use a larger load resistor R3 or a higher-gain transistor. The ILIM output is logic-compatible as long as V+ is not too high. Otherwise, you'll need a series resistor between ILIM and your MCU input.
You can also simply use a high- or low-side current monitor/comparator. E.g. if you can waste about a volt of headroom and your load can be floating, you can use LTC1540 with a 1.18k sense resistor, you'll get logic output straight out of it.

A: Any (real) current source will have a voltage limit beyond which it will not deliver a constant current. In the case of the LM334, it is rated with a voltage drop of 2.5V. Below 2.5V, the impedance may increase. The typical performance is shown in the datasheet in this graph:

So for low currents, it might be delivering more-or-less constant current at 0.7V and for higher currents, more than 1V. This will vary over temperature and from unit to unit, that's what they mean by 'typical'.
So if you monitor the voltage across the LM334 (perhaps with a comparator) you can have a good idea of whether it is working or not. If the voltage is more than 2.5V (for appropriate current settings) you know it is working. If it's less than that it may or may not be working (there is no minimum voltage below which is it is guaranteed to not work).
Edit: So if the LM334 is connected low side and sinking 1mA, and you want to know when the forward voltage drops below 1V you can use a comparator with a 1V reference. The reference could be derived from a regulated supply voltage such as 5V with a voltage divider. The comparator could be something like half an LM393.


text:
Q: Require.js backbone.js circular dependency tree hierachy We have a tree hierarchy of stores. Each store can only have one parent, but can have multiple children. Our api returns its results nested like so.
What we would like to do is have a collection of store models, with children being another collection of store models.
[{'name': 'store_a',
  'children': [{'name': 'store_b',
                'children': [{'name': 'store_c',
                              'children': []
                             }],
                },
                {'name': 'store_d',
                 'children': [],
                }]
}]

we have a store model:
define([
  'jquery',
  'jquery',
  'jCookie',
  'underscore',
  'backbone',
  'require'
], function($, jQuery, cookie, _, Backbone) {

    var StoreModel = Backbone.Model.extend({
        initialize: function(){
            if(this.get('children') instanceof Array){
                console.log(this);
                var child = new require('collections/stores')(new StoreModel(this.get('children')));
                this.set('children', child);
            }
        }
    });

  return StoreModel;

});

This store model should get the fetch JSON (when we call the collection.fetch()), if the model.children is an Array then it should create a Collection from this and hence recursively go down the tree turning all Arrays of children, into collections. Once it returns from initialising the model it should set the current models 'children' attribute to the collection.
The collection is
define([
  'jquery',
  'underscore',
  'backbone',
  'models/store'
], function($, _, Backbone, storeModel){

  var StoresCollection = Backbone.Collection.extend({
    model: storeModel,
    url: '/api/stores'

  });

  return StoresCollection;
});

Pretty barebones ('scuse the pun)
and the view is
define([
  'jquery',
  'underscore',
  'backbone',
  'collections/stores',
  'text!templates/stores/tree.html'
], function($, _, Backbone, StoreCollection, storeListTemplate){

  var StoresListView = Backbone.View.extend({
    el: $("#page"),
    events: {
    },

    initialize: function(){
        this.login();
        _.bindAll(this, 'render', 'recurse');
        this.collection = new StoreCollection();
        this.collection.bind('reset', this.render);
        this.collection.fetch();
        console.log('initialize');
        console.log(this.collection);
    },

    render: function(){
        console.log("in render");
        console.log(this.collection);
    }
  });
  return StoresListView;
});

What happens at this point is that I get a
Uncaught TypeError: Object [object DOMWindow] has no method '_reset'
in backbone.js at line 447.
I've also tried returning an object from the collection instead of a 'class', but this means that I keep adding to the same object and thus the recursive function that requires a new collections instance for each recurse doesn't work.
Should the above work? should I be able to do this?
Cheers
Mark


text:
Q: Low memory Java application server We have developed a lightweight Jersey/JSON/JMS Java application which acts as a connector between the customers legacy MS Access system and our application server. This connector is installed on the customers server.
We have used Glassfish 3.1.2 as application server so far, but the memory consumption is enormous (400 - 900 MB only hosting this particular application, even in Web Profile!).
We are looking for a lightweight application server which is easy to use (supporting JDBC/ODBC, Jersey, JMS and Custom JNDI Resources), uses less than 300 MB of memory and has a Web GUI for configuration and deployment.
Which application servers whould fit our needs? Is there a way to reduce the memory consumption of Glassfish to under 400 MB?

A: You could use Jetty. Jetty provides an HTTP server, HTTP client, and javax.servlet container.
It's commonly used for in-container unit testing of servlet code, because it's a fast-starting, cut-down Java EE server container, but it is nevertheless a real application server.

A: I finally found the solution.
Since our application doesn't require much memory, a 32 Bit Glassfish instance satisfies our needs. It uses with the Admin GUI and our application running around 250 MB of memory, which is OK. Jetty may use less memory, but has no Admin GUI and furthermore, its easier for us to manage one type of application server than two.


text:
Q: How to code in C# for accessing Form 1 checkedBox by Form2 and do some action in Form2 There are two graph in Form2 and user input the tick on check box 1 in Form1 and press load button.After that program show to enable chart1 or chart2.As an example if user select check box 1 and 2 then show two graph.If user select check box 1 then only show chart1.Please help me by given coding example for this.I attached my interface with this.
This is a checkbox and load button
There is a 2 graph

A: You can declare a public variable as Boolean and change the value as per the check box value.

A: The cleanest solution I think would be to create a constructor that takes an two bools as parameters and show the graphs based on those values.

A: As @Tamas Szabo and @Danish_k12 wrote you, you need to add a public property in your second form. On Load button click initialize new form2. Then check which checkbox is checked and set the public property you add to the second form accordingly. Then in Load event of the second form, depending on the value of the public property you added show first or second graph.
Here is how you can achieve this:
Form1 - with Form2 as private field
namespace WindowsFormsApplication3
{
    using System;
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        private Form2 form2;

        public Form1()
        {
            this.InitializeComponent();
            this.button_Load.Click += Button_Load_Click;
        }

        private void Button_Load_Click(object sender, EventArgs e)
        {
            if(this.form2 != null)
                this.form2.Dispose();

            this.form2 = new Form2();
            if(this.checkBox1.Checked == true)
            {
                this.form2.IndexOfGraphToShow = 1;
            }

            if(this.checkBox2.Checked == true)
            {
                this.form2.IndexOfGraphToShow = 2;
            }

            if(this.form2.IndexOfGraphToShow == 1 || this.form2.IndexOfGraphToShow == 2)
            {
                this.form2.Show();
                return;
            }

            MessageBox.Show("Select which graph to show", "Choose graph", MessageBoxButtons.OK, MessageBoxIcon.Error);
            form2.Dispose();
        }
    }
}

Form2:
namespace WindowsFormsApplication3
{
    using System;
    using System.Windows.Forms;

    public partial class Form2 : Form
    {
        public Form2()
        {
            this.InitializeComponent();
            this.Load += Form2_Load;
        }

        public int IndexOfGraphToShow { get; set; }

        private void Form2_Load(object sender, EventArgs e)
        {
            if(this.IndexOfGraphToShow == 1)
            {
                //  TODO: Show first graph
            }
            else if(this.IndexOfGraphToShow == 2)
            {
                //  TODO: Show second graph
            }
        }
    }
}

One more thing. Using check boxes in your case is good option only if you can show both graphics at once, as both check boxes could be checked. If you plan to show only one graph consider using option set.
To show each time button was clicked a new form you may store the shown form in a private field. Check if the field is not null on button click. If so dispose the old form and create a new one.
You may consider also using of ShowDialog instead of Show when you show the second form like this:
this.form2.ShowDialog();

This will create a dialog window and user will not be able to reach the button of the first form as long as second form is open.


text:
Q: Builder pattern in Objective-C I'm used to construct object using the builder pattern like the following:
MyObject myObject = new MyObject.Builder()
    .setProperty1(property1)
    .setProperty2(property2)
    .setProperty3(property3)
    .create();

I'm new to Objective-C specifically iOS, and I am wondering not exactly it, but if this design pattern is actually used (since you need nested classes, static methods, etc). If there is an equivalent design pattern, I'd like to learn it, or if it is used exactly as it is, I'd like an example.

A: I can suggest you to read the following article : https://annema.me/2014/04/04/the-builder-pattern-in-objective-c/


text:
Q: async lazy loading with tasks I am using data binding against a property that may be slow. However, I don't want to freeze the UI. Instead, I want to use the new task library.
Ideally, my property would look like this:
public string MyProperty
{
   get
   {
      if (_cache != null)
         return _cache;
      var result = await SomeSlowFunction();
      return result;
   }
}

However, this does now work because properties are never async.
Is there a solution?

A: I assume you have implemented INotifyPropertyChanged. Then maybe something like this can do the job:
private string _myProperty;
public string MyProperty
{
   get
   {
      if (_myProperty != null)
         return _myProperty;
      MyProperty = Application.Current.Dispatcher.BeginInvoke((Action)(() => SomeSlowFunction()));
      return string.Empty;
   }
   set
   {
      if (_myProperty == value) return;
      _myProperty = value;
      RaiseNotifyPropertyChanged("MyProperty");
   }
}

A: What I do is check for realResult and if it is null return "working" then call BackGroundWorker.  On the callback from BackGround assign realResult and call NotifyPropertyChanged.  async on property is of little value. I like the structure of BackGroundWorker and the ability to cancel and report progress.
    private System.ComponentModel.BackgroundWorker backgroundWorker1;
    private string textBackGround;

    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    public MainWindow()
    {
        backgroundWorker1 = new BackgroundWorker();
        backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);

        InitializeComponent();
    }

    public string TextBackGround
    {
        get
        {
            if (!string.IsNullOrEmpty(textBackGround)) return textBackGround;
            backgroundWorker1.RunWorkerAsync();
            return "working";
        }
    }

    // This event handler is where the actual,
    // potentially time-consuming work is done.
    private void backgroundWorker1_DoWork(object sender,
        DoWorkEventArgs e)
    {
        // Get the BackgroundWorker that raised this event.
        BackgroundWorker worker = sender as BackgroundWorker;

        // Assign the result of the computation
        // to the Result property of the DoWorkEventArgs
        // object. This is will be available to the
        // RunWorkerCompleted eventhandler.
        e.Result = ComputeFibonacci(worker, e);
    }

    // This event handler deals with the results of the
    // background operation.
    private void backgroundWorker1_RunWorkerCompleted(
        object sender, RunWorkerCompletedEventArgs e)
    {
        // First, handle the case where an exception was thrown.
        if (e.Error != null)
        {
            MessageBox.Show(e.Error.Message);
        }
        else if (e.Cancelled)
        {
            // Next, handle the case where the user canceled
            // the operation.
            // Note that due to a race condition in
            // the DoWork event handler, the Cancelled
            // flag may not have been set, even though
            // CancelAsync was called.
            textBackGround = "Cancelled";
            NotifyPropertyChanged("TextBackGround");
        }
        else
        {
            // Finally, handle the case where the operation
            // succeeded.
            textBackGround = e.Result.ToString();
            NotifyPropertyChanged("TextBackGround");
        }
    }

    // This is the method that does the actual work. For this
    // example, it computes a Fibonacci number and
    // reports progress as it does its work.
    string ComputeFibonacci(BackgroundWorker worker, DoWorkEventArgs e)
    {

        // Abort the operation if the user has canceled.
        // Note that a call to CancelAsync may have set
        // CancellationPending to true just after the
        // last invocation of this method exits, so this
        // code will not have the opportunity to set the
        // DoWorkEventArgs.Cancel flag to true. This means
        // that RunWorkerCompletedEventArgs.Cancelled will
        // not be set to true in your RunWorkerCompleted
        // event handler. This is a race condition.

        if (worker.CancellationPending)
        {
            e.Cancel = true;
            return "cancelled";
        }
        Thread.Sleep(1000);
        if (worker.CancellationPending)
        {
            e.Cancel = true;
            return "cancelled";
        }
        return "complete";
    }
}

A: Blam has the right idea: you do need some kind of "in progress" return value because the UI data binding needs a value immediately. However, you don't need BackgroundWorker.
If you use null for an "in progress" value, then you can do something like this:
// If _cache is not null, then we already have a calculated property value.
private string _cache;

// If _cacheTask is not null, then the property is being calculated.
private Task<string> _cacheTask;

public string MyProperty
{
  get
  {
    if (_cache != null)
      return _cache;
    if (_cacheTask != null)
      return null; // (in progress)
    StartSomeSlowFunction();
    // Note: _cacheTask is not null at this point.
    return null; // (in progress)
  }

  set
  {
    if (value == _cache)
      return;
    _cache = value;
    var propertyChanged = PropertyChanged;
    if (propertyChanged != null)
      propertyChanged(new PropertyChangedEventArgs("MyProperty"));
  }
}

private async Task StartSomeSlowFunction()
{
  // Immediately start SomeSlowFunction and set _cacheTask.
  _cacheTask = SomeSlowFunction();

  // Asynchronously wait for SomeSlowFunction to complete,
  //  and set the property with the result.
  MyProperty = await _cacheTask;

  // Let the task be GCed; this also allows the property to be
  //  recalculated if it is set to null first.
  _cacheTask = null;
}

private async Task<string> SomeSlowFunction();


text:
Q: STS maven project error with chromedriver I keep getting a red "!" on my maven project in STS Eclipse IDE. I import my fresh downloaded ChromeDriver from http://chromedriver.chromium.org/ and download ChromeDriver 72.0.3626.69 version which is the same version of my Chrome Browser on this PC. I even made sure to make a drivers folder to paste it in on my project. I add to my classpath and apply and get the red "!".
I also notice after downloading in my downlods folder in my file explorer on Windows 10 I notice chromedriver is hidden in file explorer when I try to add external jars when adding to class path. Not sure if this has anything to do with it.


text:
Q: How to traverse rows in a table as a Tree I have a table with two columns: child and parent. This table represents a tree kind structure having multiple trees. Given any child, i need to find its root. In other words, I need to get the parent of that child, and then the parent of the parent and so on until it reaches the root of that child.
child    parent
1        2
2        3
9        10
3        4
4        5
5        255

Here, we have two trees. One starts from 255(root) and ends at 1(leaf).
255 -> 5 -> 4 -> 3 -> 2 -> 1. And the second one starts at 10 and ends at 9. For ex: if 3 is given then it needs to find the root which on this case would be 255.
I am really new to the SQL world. My idea would be to recursively traverse the parent column for the child until if there is no entry in the child column for some parent on the way and return that parent. Is there a way to do that in SQL, especially in postgres.?

A: For such cases, you can use recursive queries. The only problem is that recursive queries are not very efficient in Postgres, so you can use this approach for small volumes of data only.
Heres sample:
create table tree (id integer, parent integer);
insert into tree values(1, null);
insert into tree values(2, 1);
insert into tree values(3, 1);
insert into tree values(4, 3);
insert into tree values(5, 2);

insert into tree values(10, null);
insert into tree values(20, 10);
insert into tree values(30, 10);
insert into tree values(40, 30);
insert into tree values(50, 20);

with recursive parentsearch as (
 select id, parent as parent_id from tree where id = :leaf_id
 union
 select t.id, t.parent as parent_id from tree t join parentsearch ps on t.id=ps.parent_id
)
select * from parentsearch where parent_id is null;


text:
Q: Simple way to have dynamically set readonly text boxes in gridview rows? My GridView is getting its data from a select statement that is bound to it.
I'd like to make all of the columns/rows read-only/unselectable until a user clicks the Edit button.
My Edit button is bound to GridView1_RowEditing
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            TextBox txtBoxResTitle = (TextBox)GridView1.Rows[GridView1.EditIndex].FindControl("txtBoxResTitle");
            txtBoxResTitle.ReadOnly = false;
            txtBoxResTitle.Enabled = true;
            BindData();
        }

In the above snippet I am using EditIndex of GridView class to get the index of the row that was just set by the NewEditIndex. In the above code I also tried setting e.NewEditIndex to get the row to find the TextBox but the code following still doesn't seem to apply.
Essentially when I click edit I want the text boxes in the selected row for editing to become editable and when I either click Update or Cancel I plan on having the row becoming un-editable.
The above code doesn't function in either scenario (whether I use GridView1.EditIndex or e.NewEditIndex)
Below is my page code for the gridview.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
        <asp:GridView runat="server" AutoGenerateColumns="false" ID="GridView1" AllowPaging="true"

          ... styling snipped ...

            OnRowEditing="GridView1_RowEditing"
            OnRowUpdating="GridView1_RowUpdating"
            OnPageIndexChanging="GridView1_PageIndexChanging"
            OnRowCancelingEdit="GridView1_RowCancelingEdit"
            OnRowDeleting="GridView1_RowDeleting">

            ... styling snipped ...

            <Columns>
                <asp:TemplateField HeaderText="pk1" Visible="false">
<ItemTemplate>
<asp:Label ID="lblResPk1" runat="server" visible="false" Text='<%#Eval ("pk1")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
                <asp:TemplateField HeaderText="Resource Title">
                    <ItemTemplate>
                        <asp:TextBox ID="txtBoxResTitle" readonly="true" Enabled="false" runat="server" Text='<%#Eval ("resource_title")%>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Resource Type">
                    <ItemTemplate>
                        <asp:TextBox ID="txtBoxResType" runat="server" Text='<%#Eval ("resource_type")%>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Cost">
                    <ItemTemplate>
                        <asp:TextBox ID="txtBoxResCost" runat="server" Text='<%#Eval ("resource_cost")%>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Availability">
                    <ItemTemplate>
                        <asp:TextBox ID="txtBoxResAvail" runat="server" Text='<%#Eval ("available")%>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Edit" ShowHeader="false">
<EditItemTemplate>
<asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update" CommandName="Update"></asp:LinkButton>
<asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel" CommandName="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="true" ShowHeader="true" />
<asp:CommandField HeaderText="Select" ShowSelectButton="true" ShowHeader="true" />
            </Columns>

        </asp:GridView>
            <asp:Label ID="lblDeleteException" runat="server" Text="Label" Font-Bold="True" ForeColor="#FF3300" Visible="False"></asp:Label>
            </ContentTemplate>
    </asp:UpdatePanel>

Please advise.
The bottom jquery code
$(function() {
$('#GridView1').find('[input type="text"]').each(function() {
     $(this).attr('disabled', 'disabled');
}) <-------extra ) needed
  });

Was throwing an error about ) expected, I believe it needed one above where notated.
I added the code right inside the end tag of my update panel like such:
</asp:UpdatePanel>
    <script>
        $(function () {
            $('#GridView1').find('[input type="text"]').each(function () {
                $(this).attr('disabled', 'disabled');
            })
        });
    </script>
    </asp:Content>

But still the fields are editable. My Site.Master file contains the script reference to load the jquery file as I use jquery elsewhere in my project.

A: Find each textbox for a row in this event and make readonly.
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    foreach (Control ctrl in e.Row.Controls)
    {
        MakeTextboxesReadonly(ctrl);
    }

}

private static void MakeTextboxesReadonly(Control parent)
{
    foreach (Control ctrl in parent.Controls)
    {
        if (ctrl is TextBox)
        {
            (ctrl as TextBox).Enabled = false;
        }
    }
}


text:
Q: Exact image for downloading Ubuntu 12.04 I have an HP laptop with Ubuntu 12.04 issued by my college. But since I am more of a Windows guy, I installed Windows 8 to it. However, when the laptop was issued, I was told that I should not change the OS. Now that the academic year is ending, I have to give the laptop back to the college, and for that, I need to change the OS back to Ubuntu. Can anyone tell me where can I download the exact OS??
I don't know what is this, here is the link to an image of the exact release version

A: There it is.
http://releases.ubuntu.com/12.04/ubuntu-12.04.4-desktop-amd64.iso

*

*Download the iso.

*Make a bootable CD/USB

*Install

It's an updated version of the same OS you had installed. But that should be no problem. It would have looked like that if you had used it daily and updated it as necessary.


text:
Q: Android Studio Adding image asset not working I'm trying to add an image in Android studio by right clicking on the drawable folder->new->Image Asset, I add an Action Bar and Tab Bar icon with a custom image and I click finish and it looks like its doing something but nothing appears in the drawable folder.  I'm also unable to reference the new image name in any xml.  What's funny is if I go to re-add this image, it says the image already exists and it will be overwritten.  Am I doing something wrong?

A: I create a new project with Android Studio and generate image asset in the new project. It begins to work. I don't know what's wrong with the previous project. Hope it also helps for you.

A: As @Varun said, Before click on Finish, check save path by click on "Next" button.

A: TLTR: fix any other icon type you touched before.
In my case it was because of wrong path to foreground image path (the source image was deleted):

So even after changing the icon type the error does not disappear (buttons are disabled):

So fix other icon types.

A: In Background Layer set Asset Type to "Color"


text:
Q: Keep search results when changing routes and coming back in Angular I have an app with 3 routes:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { SearchComponent } from './pages/search/search.component';
import { CreateUserComponent } from './pages/create-user/create-user.component';
import { UserProfileComponent } from './pages/user/user-profile.component';

const routes: Routes = [
  {
    path: '',
    redirectTo: 'search',
    pathMatch: 'full'
  },
  {
    path: 'search',
    component: SearchComponent,
    data: {
      breadcrumb: 'Search'
    }
  },
  {
    path: 'create-user',
    component: CreateUserComponent,
    data: {
      breadcrumb: 'Create User'
    }
  },
  {
    path: 'user/:auth0Id',
    component: UserProfileComponent,
    data: {
      breadcrumb: 'Profile'
    }
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class UserManagementRoutingModule { }

In the SearchComponent template, I have a button that make a GET request when clicked:
search.component.html
 <button nz-button nzType="primary" type="button"
  (click)="searchAll()">{{ 'SEARCH.SEARCH-FORM.SEARCH-ALL-BTN' | translate }}</button>

search.component.ts
    searchAll(): void {
    this.tableLoadingText = 'SEARCH.RESULT.LOADING-SEARCH';
    this.isTableLoading = true;
    this.currentSearchType = 'searchAll';

    this.scimB2bService.getAllUsers(this.pageSize, this.pageIndex).subscribe((res: IB2bScimUserList) => {
      this.userList = res.Resources;
      this.totalUser = res.totalResults;
      this.mapUsers(this.userList);
      this.triggerFeedback('success', 'SEARCH.STATUS.SUCCESS.SEARCH-ALL', null);
    }, error => {
      this.isTableLoading = false;
      this.triggerFeedback('error', 'SEARCH.STATUS.ERROR.SEARCH-ALL', error);
    });
  }

What's the easiest way to go to 'user/:auth0Id' route and comme back to 'search' route without loosing the search results (I mean not having to do the GET request again)?
Thanks!

A: If you want data to be shared between components, just put it in a shared service.
@Injectable({providedIn: 'root'})
export class SearchService {
  searchResults = []; // idk if your results are actually an array
}

In your search component
constructor(private searchService: SearchService){}

searchAll(): void{
  ...
  this.scimB2bService.getAllUsers(this.pageSize, this.pageIndex).subscribe((res: IB2bScimUserList) => {
    this.searchService.searchResults = res.Resources; // idk what you actually want stored
    ...
  });
}

In any other component
constructor(private searchService: SearchService){}

get searchResults() { return this.searchService.searchResults };

<p *ngFor="let res of searchResults">{{ res }}</p>

It would make more sense to put the search functions and http requests in this service as well.
Since the service is provided in 'root', the enclosed data will persist as long as the application does.

A: I used this approach: stackoverflow.com/a/44854611/14530862 combined with this other one: stackoverflow.com/a/57027024/14530862
My code:
import { ActivatedRouteSnapshot, RouteReuseStrategy, DetachedRouteHandle } from '@angular/router';

export class CustomReuseStrategy implements RouteReuseStrategy {
   private storedRouteHandles = new Map<string, DetachedRouteHandle>();

  // Decides if the route should be stored
  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return route.data.reuseRoute === true;
  }

  // Store the information for the route we're destructing
  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
     this.storedRouteHandles.set(route.routeConfig.path, handle);
  }

 // Return true if we have a stored route object for the next route
  shouldAttach(route: ActivatedRouteSnapshot): boolean {
     return this.storedRouteHandles.has(route.routeConfig.path);
  }

  // If we returned true in shouldAttach(), now return the actual route data for restoration
  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
     return this.storedRouteHandles.get(route.routeConfig.path);
  }

  // Reuse the route if we're going to and from the same route
  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
     return future.routeConfig === curr.routeConfig;
  }
 }


text:
Q: Java Clip won't stop and keep playing .wav file when i hit the button I try to make a program to play and stop wav, the code can play wav when i hit the play button but can't stop it when i hit a stop button, and when i hit the play button again it play the sound again but merging the sound before, here's the code :
public constructor(){
btnPlaySound.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    btnPlaySoundCLick();
                } catch (LineUnavailableException | IOException
                        | UnsupportedAudioFileException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });}

 private void btnPlaySoundCLick() throws LineUnavailableException, IOException, UnsupportedAudioFileException{

    File soundFile = new File(path);
    AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);

    DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
    Clip clip = (Clip) AudioSystem.getLine(info);
    clip.open(sound);

    clip.addLineListener(new LineListener() {
      public void update(LineEvent event) {
        if (event.getType() == LineEvent.Type.STOP) {
          event.getLine().close();
          clip.stop();
        }
      }
    });

    // play the sound clip
    if(btnPlaySound.getText().equals("Listen")){
        btnPlaySound.setText("Stop");
        clip.start();
    } else if(btnPlaySound.getText().equals("Stop")) {
        btnPlaySound.setText("Listen");
        clip.stop();

    }
}

A: Here is my little implementation of what you are trying to do -  it is important to note that the clip is made global so that you have access to it, and the action has been moved to the button:
public class c extends JFrame {

  String f="e-22.wav";
  JButton btnPlaySound=new JButton("Listen");
  Clip clip = null;

public c(){

  btnPlaySound.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
              JButton b=(JButton)arg0.getSource();
              // play the sound clip
              if(b.getText().equals("Listen")){
                b.setText("Stop");
                btnPlaySoundCLick();
              } else if(btnPlaySound.getText().equals("Stop")) {
                  b.setText("Listen");
                  clip.stop();
              }
            } catch (LineUnavailableException | IOException
                    | UnsupportedAudioFileException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

  setSize(500, 500);
  add(btnPlaySound);
  setVisible(true);

}

 private void btnPlaySoundCLick() throws LineUnavailableException, IOException, UnsupportedAudioFileException{

  File soundFile = new File(f);
  AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);

  DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
  clip = (Clip) AudioSystem.getLine(info);
  clip.open(sound);

  clip.addLineListener(new LineListener() {
  public void update(LineEvent event) {
    if (event.getType() == LineEvent.Type.STOP) {
    System.out.println("stop");
      event.getLine().close();
    }
  }
  });

  clip.start();

  }

  public static void main(String[] args) {
    c cc=new c();
  }

}


text:
Q: Show details(sysinfo) rdp C# I'm using AxInterop.MSTSCLib.dll for connect Virtual Server;
try
{
    rdp.Server = txtServer.Text;
    rdp.UserName = txtUserName.Text;

    IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
    secured.ClearTextPassword = txtPassword.Text;
    rdp.Connect();
}
catch (Exception Ex)
{
    MessageBox.Show("Error Connecting", "Error connecting to remote desktop " + txtServer.Text + " Error:  " + Ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Well, now I want to display the hardware specifications in the app, Is it possible?(Like: CPU cores, RAM)


text:
Q: Enable and Disable in angularjs I try to make disable second field until I do not enter 'Lokesh' in first field for that I have tried below code I am in learning stage of angularjs so please correct me where I am doing mistake.
eg.code
<!DOCTYPE html>

Enter 'Lokesh' to display last name

                    <input data-ng-model="firstName"

                   type="text"

                   ng-disabled="{if(firstName="lokesh")}"

                   Last Name: <input type="text" ng-model="lastName">

                   />

A: The problem is with the attribute ng-disabled="{if(firstName=" lokesh ")}"
There is no need of using if, you can directly compare the strings.
Update the code as
ng-disabled="firstName=='lokesh'"

Demo

  <input data-ng-model="firstName" class="span12 editEmail" type="text" placeholder="Type lokesh here" />Last Name:
  <input type="text" ng-model="lastName" ng-disabled="firstName!=='lokesh'" />

{{firstName}}


text:
Q: Trouble in parsing date using dateutil I am using python-dateutil for parsing a date from a string:
import dateutil.parser
print dateutil.parser.parse('some null string', fuzzy=True).date()
2012-10-18
print dateutil.parser.parse('some 31 Oct 2012 string', fuzzy=True).date()
2012-10-31

What I am expecting is for dateutil.parser.parse('some null string', fuzzy=True).date() to throw an exception, but it's returning the current date. Can someone show me how I can avoid getting the current date, if no date is found in the provided string?
Thanks in advance.

A: See the dateutil docs, specifically the parse function (emphasizes mine):

Additionally, the following keyword arguments are available:
default
  If given, this must be a datetime instance. Any fields missing in the parsed date will be copied from this instance. The default value is the current date, at 00:00:00am.
... (snip) ...
fuzzy
  If fuzzy is set to True, unknown tokens in the string will be ignored.

Given that you've set fuzzy to True, no exception will be thrown as it will simply ignore all unknown tokens. And, as the default argument is not passed, the current date will be returned.
So the solution will be to either keep fuzzy set to False, so that invalid format strings will throw an exception; or check if the returned datetime is equal to the current date at 00:00:00am as an indication of a failed conversion.


text:
Q: Building a cheap and stable microwave network analyser or oscillator (2-5GHz) I am interested in measuring the changing dielectric constant of a liquid as it undergoes a process.  My background research of scientific articles shows that the 2-5GHz range provides the best contrast between the before and after dielectric constants of this liquid. In those papers they use a vector network analyser which is not suitable for me due to cost and the large size. Hence I want to develop a system to measure the dielectric constant at a fixed microwave frequency somewhere in the 2-5GHz range.
From what I understand I need a signal generator and a matched receiver. The output of the analyser will be connected to a coaxial cable with an open ended probe suspended in the liquid. What are recommended or suggested designs for such a device? It needs to be stable and reasonably cheap to make. Are there ICs designed for this? I note Analog Devices has a range of direct digital synthesis chips that look suitable but the prices become insane at the gigahertz range.
EDIT: Just to clarify, the design does not need to sweep. It can be a fixed frequency, it just has to be within 2-5GHz.

A: This is a very big question to try to answer here, but I'll try to get you started.
Since you are only doing a one-port (reflection) measurement, you are quite correct that you don't need a full vector network analyzer. You could do this with either a vector voltmeter or an even simpler VSWR meter and a swept-frequency source (as your question suggests you intend).
The source should not require a DDS. A basic VCO should do, although of course the lower you can keep the harmonic distortion, the more accurate your measurements will be. VCOs covering more than an octave (as you need) are somewhat more difficult to find than narrowband ones covering frequency bands with important commercial uses. But you barely need more than an octave and you should be able to find one. Normally you would operate the VCO in a phase-locked loop, locked to a suitable reference frequency (say 10 MHz), to tune the the desired frequency in your 2 - 5 GHz band. This is the essence of an rf synthesizer.
On the receiver side, what you really need is a directional coupler to pick off the reflected signal coming back from your sample, and an rf detector to measure the reflection amplitude. A pair of matched couplers and detectors would let you measure the ratio between the transmitted signal and reflection for more accurate measurements.
Finally, the probe. I am not familiar with best practice for designing probes for liquid dielectric constant measurements, but I can give you some ideas about it. Details probably depend on physical factors like the viscosity of your sample, whether its a corrosive material, how easily residue from one sample could contaminate the next sample, the volume of the available samples, etc.
If you think the dielectric constant is basically constant over the 2-5 GHz range, then I'd suggest to build a resonant chamber and flood it with the sample, for example a roughly 1/2-wavelength segment of air-filled coaxial line, where you replace the air with your sample. If the dielectric constant changes, so will the resonant frequency of the chamber. Sweep the source frequency and find the reflection minimum or maximum to determine the sample dielectric constant. This type measurement could be done with just a VSWR meter as the sensor.
If the dielectric "constant" is changing in the 2-5 GHz range (due to material resonances, this is reasonably likely), then you will need a vector-voltmeter type detector. Again, though, I'd consider making a near-resonant chamber to hold the sample. With some math, the rf reflection from the chamber (amplitude and phase) will tell you the sample dielectric constant at each frequency.


text:
Q: Delete user from database if email not confirmed I am currently working on a registration based website, and I have the server sending an activation email to the user upon registration. This is all done in PHP so, as you can imagine, I am using the mail() function.
This is all fine and dandy, once the user gets the email and clicks the activation link, the 'active' field that is in the 'Users' table is set to true. Here's the problem though, in the case that a user does not confirm their email address, what am I to do?
I have thought of holding details like the date and time the user registers but I don't know how to proceed with this data. How do I have the server automatically delete the user from the  database after a set amount of time?
That's what I think I should be asking, but in all honesty I don't know the usual protocol...
Conclusion: Since Cron is for Unix based servers I've had to pass on it, but I found it very interesting that I could just use the Windows Task Scheduler that is built into Windows. This at least means I can test it on my PC before any server hosting. Thank you all

A: You should definitely store the date and time that the activation link was sent.
There isn't really a way to tell the server to automatically delete stale user data, but it's easy enough to code up yourself. Assuming you have access to cron on your server, you can set up a cronjob to run (for example) every night at 2am and execute a PHP script that searches the database for users who were sent a link more than X days ago but never confirmed it

A: i think the solution would be Storing the timestamp while sending the mail.
now run a cron every 15minutes which would check that which values are having timestamp more than 24hrs or any timelimit you want and then delete it from db

A: Just call in your index.php file the following code. (Why index.php ? - because it is requested every time and can "act" as a cronjob.)
(Just Pseudo Code - might need some tweaks!)
mysql_query("DELETE FROM user WHERE active = 'false' AND registerTime < (NOW-60*60*24*7)")
This will delete all Users which have not been activated within 7 Days.
It's just a concept idea i think you can build on.

A: You should look into cronjobs that you run daily. Simply put in a field in your database with the time your user registered.


text:
Q: Solution for hyphen word I am wondering about this case:
Is it possible to do something like that?
if word, for example co-worker is hyphen, jquery can take detect and take word and replace with class inside?
Example:
co-worker
I think something about preg.replace function, but not sure how to detect word.
Can anybody give me a tip for this?

A: You could use a regex to detect any hyphenated word:

function highlightHyphenated(element) {
  // Regular expression matching any group composed by:
  //   - `[A-Za-zÀ-ÖØ-öø-ÿ]+` one or more letters (including accented ones), followed by
  //   - `-` a hyphen, followed by
  //   - `[A-Za-zÀ-ÖØ-öø-ÿ]+` one or more letters (including accented ones)
  const re = /([A-Za-zÀ-ÖØ-öø-ÿ]+-[A-Za-zÀ-ÖØ-öø-ÿ]+)/gim;
  if (re.test(element.innerText)) {
    element.innerHTML = element.innerHTML.replace(re, '$1');
  }
}

document.querySelectorAll('p').forEach(el => highlightHyphenated(el));
.hyphenated {
  display: inline-block;
  background-color: yellow;
  font-weight: bold;
}

Lorem ipsum dolor sit-amet, consectetur adipiscing elit. Etiam orci tortor, aliquet quis mollis in, posuere id ipsum. Vestibulum quis nibh augue. Sed id congue ex. Suspendisse eget elit fringilla, commodo mi vitae, luctus odio. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque cursus quam vitae leo eleifend, a laoreet neque varius. Morbi quis posuere risus, at scelerisque dui. Morbi sit amet lorem purus. Pellentesque auctor ut libero sed tempor. Integer vitae erat id leo porttitor blandit. Duis cursus lacus quis mauris facilisis, dapibus auctor nisl feugiat. Donec consectetur dolor eu suscipit aliquam. Fusce magna ante, luctus a arcu at, volutpat blandit tortor. Vivamus bibendum sem id mauris dapibus, et ultricies elit fermentum. Aliquam eu efficitur ipsum. Pellentesque eu velit ipsum.

Sed-fermentum lorem a ipsum sodales, vel vestibulum odio hendrerit. Aenean auctor ipsum in urna finibus, eu vulputate massa rutrum. Curabitur id eros pulvinar, dapibus justo nec, euismod sem. Ut ornare turpis velit, non aliquet est rhoncus eu. Etiam ex dolor, congue eleifend nisl eget, tempus dictum nulla. Integer ultricies enim eu mattis sagittis. Aliquam malesuada condimentum semper. Aliquam erat volutpat. Integer in dapibus sapien, tempor venenatis nisi. Curabitur eget sapien vitae nisi pulvinar volutpat aliquet ut augue. Cras pretium congue est, at pulvinar velit egestas vitae. Pellentesque non dui et urna posuere mattis.

Fusce consectetur vel purus a rutrum. Nulla vitae-metus nec eros facilisis porta. Ut quis sem ac nibh finibus porta egestas ac neque. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque sagittis nisl ante, vel placerat dui fermentum eu. Quisque placerat placerat neque. Nullam vel euismod nisl. Nullam aliquet enim vitae odio ultricies tincidunt. Nullam sagittis arcu at eleifend commodo. In hac habitasse platea dictumst. Nunc nibh lacus, pharetra nec sapien quis, congue pharetra felis. Vivamus porta, ex et convallis sagittis, ex dui porttitor augue, et tempus neque risus quis diam. Morbi eget leo lectus.

Sed at justo euismod, luctus lorem ut, dignissim libero. Curabitur vel auctor neque, vel ultrices nulla. Duis in aliquet-ligula. Aliquam sed est nisl. Aliquam enim orci, congue eget erat sed, imperdiet pharetra est. Fusce efficitur a tortor-nec fringilla. Sed sed tempus tellus, efficitur ornare lorem. Proin risus sem, mollis et lectus nec, rhoncus accumsan magna. Mauris hendrerit ligula eu est pretium, id bibendum ante tincidunt. Nam cursus vehicula diam, in eleifend magna blandit at. Vestibulum sit amet bibendum elit.

Donec magna est, placerat in vehicula eget, convallis non metus. Proin posuere ultricies neque a scelerisque. Quisque eu ex quis magna varius-vulputate. Sed venenatis dapibus iaculis. Cras lacinia ex et ante mollis, et condimentum ante porta. Sed tempus diam at fringilla condimentum. Aenean est ex, sollicitudin at blandit ac, dapibus eu mauris. Sed a tincidunt arcu. Maecenas sagittis cursus eros, ut commodo neque maximus id. Aenean accumsan purus eu tortor eleifend, vel volutpat turpis tempus. Vestibulum et metus non eros rhoncus placerat. Donec congue enim libero. Cras placerat, urna eu tincidunt aliquam, nisl odio viverra felis, id volutpat ipsum libero a leo.

If you do not care about accented letters, you can replace [A-Za-zÀ-ÖØ-öø-ÿ]+ with [A-Za-z]+


text:
Q: Parsing the web page response as Json, in Java I have a java code:
URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));

String inputLine;
while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);

Which is opening the connection and printing the contents of it. The contents are indeed Json. The output is something like:
{
  "merchantId": "guest",
  "txnId": "guest-1349269250-001",
}

I wish to parse this in json simple jar. I changed the code loop like this:
JSONObject obj = new JSONObject();
while ((inputLine = in.readLine()) != null)
        obj.put("Result",inputLine);

But that doesn't seem to be working. The output I'm getting is:
{"Result":"}"}

A: You should use the JSONParser#Parse() method or the JSONValue#parse() method :
URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
Reader in = new InputStreamReader(oracle.openStream());

Object json = JSONValue.parse(in);

A: Are you sure you're following the documentation on how to parse a JSON string?
By the looks of it you have to obtain the entire string and call a JSONParse#parse() on it, but your code is filling up a HashMap (JSONObject's parent class) with each of the lines of the JSON. In fact it stores just the last line because you're calling put() with the same "Result" key on every iteration.

A: You should read whole contents to String variable first and parse it to json. Be careful of ""(double quote). Java uses \" for double quote. Like.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonSimpleExample3 {

    public static void main(String args[]) {

        JSONParser parser = new JSONParser();
        //String str = "{\"merchantId\": \"guest\",\"txnId\": \"guest-1349269250-001\",}";

        //intilize an InputStream
        InputStream is = new ByteArrayInputStream("file content".getBytes());

        //read it with BufferedReader and create string
        BufferedReader br = new BufferedReader(new InputStreamReader(is));// Instead of is, you should use oracle.openStream()
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        // parse string
        try {
            JSONObject jsonObject = (JSONObject) parser.parse(sb.toString());

            String merchantId = (String) jsonObject.get("merchantId");
            System.out.println(merchantId);
            String txnId = (String) jsonObject.get("txnId");
            System.out.println(txnId);

        } catch (ParseException e) {

            e.printStackTrace();
        }
    }
}

A: try this link its really helpful if you are going to be logging in or staff like that
Java Json simple
import java.io.IOException;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;

public class ParseJson1 {

public static void main(String[] args) {
    String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
    /*
     * {"title":"Free Music Archive - Genres","message":"","errors":[],"total" : "161","total_pages":81,"page":1,"limit":"2",
     * "dataset":
     * [{"genre_id": "1","genre_parent_id":"38","genre_title":"Avant-Garde" ,"genre_handle": "Avant-Garde","genre_color":"#006666"},
     * {"genre_id":"2","genre_parent_id" :null,"genre_title":"International","genre_handle":"International","genre_color":"#CC3300"}]}
     */
    try {
        String genreJson = IOUtils.toString(new URL(url));
        JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
        // get the title
        System.out.println(genreJsonObject.get("title"));
        // get the data
        JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
        // get the first genre
        JSONObject firstGenre = (JSONObject) genreArray.get(0);
        System.out.println(firstGenre.get("genre_title"));
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
}

}


text:
Q: How to disable jquery code in partial view I use this code for edit :
I want to disable dropdownlist, when radioobutton is selected, it not working in Edit Partial view but it work in insert partial. Insert partial code is exactly Same as Edit Partial View .
what's the problem ?
Partial View :
    @model Amene.Areas.Admin.Models.CategoryViewModel
@using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", Url = "/Admin/Category/Edit", OnSuccess = "InsertCategory" }))
            {

        <input class="form-control col-md-6 col-lg-6" name="CategoryName" value="@Model.CategoryModel.CategoryName" />

        <input value="0" type="radio" id="main" name="MainCat" @(Model.CategoryModel.ParentID == 0 ? Html.Raw("checked='checked'") : Html.Raw(""))>دسته اصلی
        <input value="1" type="radio" id="sub" name="MainCat" @(Model.CategoryModel.ParentID != 0 ? Html.Raw("checked='checked'") : Html.Raw(""))>زیر دسته

        <select name="ParentID" id="dropdowncat">
            @foreach (var item in Model.List)
                {
                <option value="@item.CatID" @(Model.CategoryModel.ParentID == item.CatID ? Html.Raw("selected='selected'") : Html.Raw(""))>@item.CategoryName</option>
            }
        </select>

    @Html.HiddenFor(model => model.CategoryModel.CatID)
    <input type="submit" value="ثبت" />
}

Contoller :
public PartialViewResult Edit(int id)
    {
        var model = new CategoryViewModel();
        var cat = _CategoryService.CategoryByID(id);
        model.CategoryModel = Mapper.Map<CategoryModel>(cat);
        var categorymodel = _CategoryService.GetAllCategory();
        model.List = Mapper.Map<IEnumerable<CategoryModel>>(categorymodel);
        return PartialView(model);
    }

Scripts :
$("#main").click(function () {
        $("#dropdowncat").attr("disabled", true);
    });

    $("#sub").click(function () {
        $("#dropdowncat").attr("disabled", false);
    });

and in View :

A: for code to work on dynamic content it has to be tied to the document.  change your click events to
$(document).on('click', '#main', function(){...


text:
Q: Interpretation variants of binary operators I'm writing a grammar for a language that contains some binary operators that can also be used as unary operator (argument to the right side of the operator) and for a better error recovery I'd like them to be usable as nular operators as well).
My simplified grammar looks like this:
start:
    code EOF
;
code:
    (binaryExpression SEMICOLON?)*
;

binaryExpression:
    binaryExpression BINARY_OPERATOR binaryExpression //TODO: check before primaryExpression
    | primaryExpression
;

    primaryExpression:
            unaryExpression
            | nularExpression
    ;

    unaryExpression:
        operator primaryExpression
        | BINARY_OPERATOR primaryExpression
    ;

    nularExpression:
        operator
        | BINARY_OPERATOR
        | NUMBER
        | STRING
    ;

        operator:
            ID
        ;

BINARY_OPERATOR is just a set of defined keywords that are fed into the parser.
My problem is that Antlr prefers to use BINARY_OPERATORs as unary expressions (or nualr ones if there is no other choice) instead of trying to use them in a binary expression as I need it to be done.
For example consider the following intput: for varDec from one to twelve do something where from, to and do are binary operators the output of the parser is the following:

As you can see it interprets all binary operators as unary ones.
What I'm trying to achieve is the following: Try to match each BINARY_OPERATOR in a binary expression and only if that is not possible try to match them as a unary expression and if that isn't possible as well then it might be considered a  nular expression (which can only be the case if the BINARY_OPERATORis the only content of an expression).
Has anyone an idea about how to achieve the desired behaviour?

A: You allow operators to act like operands ("nularExpression") and operands to act like operators ("operator: ID"). Between those two curious decisions, your grammar is 100% ambiguous, and there is never any need for a binary operator to be parsed. I don't know much about Antlr, but it surprises me that it doesn't warn you that your grammar is completely ambiguous.
Antlr has mechanisms to handle and recover from errors. You would be much better off using them than writing a deliberately ambiguous grammar which makes erroneous constructs part of the accepted grammar. (As I said, I'm not an Antlr expert, but there are Antlr experts who pass by here pretty regularly; if you ask a specific question about error recovery, I'm sure you'll get a good answer. You might also want to search this site for questions and answers about Antlr error recovery.)

A: Fairly standard approach is to use a single recursive rule to establish the acceptable expression syntax. ANTLR is default left associative, so op expr meets the stated unary op requirement of "argument to the right side of the operator". See, pg 70 of TDAR for a further discussion of associativity.
Ex1: -y+x  -> binaryOp{unaryOp{-, literal}, +, literal}
Ex2: -y+-x -> binaryOp{unaryOp{-, literal}, +, unaryOp{-, literal}}
expr
    : LPAREN expr RPAREN
    | expr op expr         #binaryOp
  //| op expr              #unaryOp   // standard formulation
    | op literal           #unaryOp   // limited formulation
    | op                   #errorOp
    | literal
    ;

op  : .... ;

literal
    : KEYWORD
    | ID
    | NUMBER
    | STRING
    ;

A: I think what I'm going to write down now is what @GRosenberg meant with his answer. However as it took me a while to fully understand it I will provide a concrete solution for my problem in case someone else is stumbling across this question and is searching or an answer:
The trick was to remove the option to use a BINARY_OPERATOR inside the unaryExpression rule because this always got preferred. Instead what I really wanted was to specify that if there was no left side argument it should be okay to use a BINARY_OPERATOR in a unary way. And that's the way I had to specify it:
binaryExpression:
    binaryExpression BINARY_OPERATOR binaryExpression
    | BINARY_OPERATOR primaryExpression
    | primaryExpression
;

That way this syntax only becomes possible if there is nothing to the left side of a BINARY_OPERATOR and in every other case the binary syntax has to be used.


text:
Q: Extract specific multiple string from lines via regex I have been trying to extract certain values from multiple lines inside a .txt file with PowerShell. I have a huge file with all the backup and trying to extract all those lines.
Txt file:
Backup-ID:           hostname01
Policy:              VM_weekly
Primary Copy:        23
Expires:             1/5/2024 3:19:13 AM
Type:                4

Copy Number:        2
Fragment Size (KB): 6188832
Expires:            1/5/2024 3:19:13 AM
MediaID:            XXX122
TestID:             1222
Block:              33

Copy Number:        3
Fragment Size (KB): 6188832
Expires:            1/5/2024 3:19:13 AM
MediaID:            XXX134
TestID:             223
Block:              22
Duplicate:          N

Backup-ID:           hostname02
Policy:              VM_weekly2
Primary Copy:        24
Expires:             1/5/2024 3:19:13 AM
Type:                2

Copy Number:        2
Fragment Size (KB): 6188832
Expires:            1/5/2024 3:19:13 AM
MediaID:            XXX244
Comp:               BBB
Block:              45
Duplicate:          N

Copy Number:        3
Fragment Size (KB): 6188832
Expires:            1/5/2024 3:19:13 AM
MediaID:            XXX199
Comp:               AA
Block:              334

Copy Number:        4
Fragment Size (KB): 6188832
Expires:            1/5/2024 3:19:13 AM
MediaID:            XXX177

I have code so far :
Get-Content C:\test.txt | Select-String -Pattern 'Backup-ID: ' ,'Policy: ' ,'Primary Copy: ' ,'Expires:  ' ,'Copy Number: ' , 'Fragment Size ' ,'Expires: ' , 'MediaID:'

This is what I want :
hostname01,VM_weekly,23,6188832,1/5/2024 3:19:13 AM,XXX122,3,6188832,1/5/2024 3:19:13 AM,XXX134
hostname02,VM_weekly2,24,1/5/2024 3:19:13 AM,2,6188832,1/5/2024 3:19:13 AM,XXX244,3,6188832,1/5/2024 3:19:13 AM,XXX199,4,6188832,1/5/2024 3:19:13 AM,XXX177

A: Here's my old-school approach:
$line = ''
Get-Content C:\test.txt |
    Select-String -Pattern 'Backup-ID: ' ,'Policy: ' ,'Primary Copy: ' ,'Expires:  ' ,'Copy Number: ' , 'Fragment Size ' ,'Expires: ' , 'MediaID:' |
        ForEach-Object {
            $aux = $_  -split ':',2            # only 2 substrings
            if ($aux[0] -eq 'Backup-ID') {
                if ( $line -ne '' ) { $line }  # Write-Output (current line)
                $line = $aux[1].Trim()
            } else {
                $line += ',' + $aux[1].Trim()
            }
        }
        $line                                   # Write-Output (last line)

Output:
D:\PShell\SO\54921319.ps1

hostname01,VM_weekly,23,1/5/2024 3:19:13 AM,2,6188832,1/5/2024 3:19:13 AM,XXX122,3,6188832,1/5/2024 3:19:13 AM,XXX134
hostname02,VM_weekly2,24,1/5/2024 3:19:13 AM,2,6188832,1/5/2024 3:19:13 AM,XXX244,3,6188832,1/5/2024 3:19:13 AM,XXX199,4,6188832,1/5/2024 3:19:13 AM,XXX177

Edit: … I need to export CSV file ….
$xArr = D:\PShell\SO\54921319.ps1
$xCsv = $xArr |  ConvertFrom-Csv -Header $(1..30|%{"a$_"})
$xcsv | Export-Csv -NoTypeInformation -Path c:\temp\result.csv

Of course, you can compute

*

*actual upper limit for -Header $(1..30|%{"a$_"}) instead of estimated 30 e.g. as ($xArr | % {$_.Split(',').Count}|Measure-Object -Maximum).Maximum,

*or even compute some human-readable headers (having in mind recurring names of some properties for each Copy Number inside given Backup-ID)

A: Using a better Pattern
 $Pattern = '^Backup-ID|^Policy|^Primary Copy|^Expires|^Copy Number|^Fragment Size|^Expires|^MediaID'

and RegEx to split the output at Backup-ID
(Get-Content .\test.txt|Select-String -Pattern $Pattern|Out-String) -split "(?=Backup-ID)"|ForEach-Object {
    (($_ -split "`r?`n" | %{($_ -split ":\s+",2)[1]}) -join ',').Trim(',')
}

hostname01,VM_weekly,23,1/5/2024 3:19:13 AM,2,6188832,1/5/2024 3:19:13 AM,XXX122,3,6188832,1/5/2024 3:19:13 AM,XXX134
hostname02,VM_weekly2,24,1/5/2024 3:19:13 AM,2,6188832,1/5/2024 3:19:13 AM,XXX244,3,6188832,1/5/2024 3:19:13 AM,XXX199,4,6188832,1/5/2024 3:19:13 AM,XXX177

A: This maybe?
& {
    $current = $null
    switch -regex -file 'C:\text.txt' {
        '^(Backup-ID|Policy|Primary Copy|Expires|Copy Number|Fragment Size \(KB\)|Expires|MediaID):\s+(.*)' {
            if ($matches[1] -eq "Backup-ID") {
                if ($current) { $current.ToString() }
                $current = [Text.StringBuilder]::new()
                [void]$current.Append($matches[2])
            }
            else {
                [void]$current.Append(",").Append($matches[2])
            }
        }
    }
    $current.ToString()
}


text:
Q: NHibernate not deleting child object I can't get NHibernate to delete this child object, it completes without throwing any exceptions and without deleting anything:
    public void DeleteW9(int vendorId, int vendorW9Id)
    {
        var vendor = vendorRepository.Get(vendorId);
        var W9 = vendor.W9.Where(x => x.Id == vendorW9Id).First();
        vendor.W9.Remove(W9);
        vendorRepository.SaveOrUpdate(vendor);
    }

Here's my Vendor mapping:
        mapping.HasMany(x => x.W9)
               .KeyColumn("VendorFk")
               .Cascade.AllDeleteOrphan()
               .AsBag();

My VendorW9 table contains a reference to the Vendor's ID in the form of the VendorFk. I have no restraints setup, do I need to setup a primary key relationship? NHibernate functions fine for everything but deleting orphans.

A: Try adding vendorRepository.Commit():
public void DeleteW9(int vendorId, int vendorW9Id)
{
    var vendor = vendorRepository.Get(vendorId);
    var W9 = vendor.W9.Where(x => x.Id == vendorW9Id).First();
    vendor.W9.Remove(W9);
    vendorRepository.SaveOrUpdate(vendor);
    vendorRepository.Commit();
}


text:
Q: Good/clean practice for building the auth part of an application I'm starting on a greenfield project and haven't done or architected the sign-up/sign-in and auth part of the backend in a very long time, so my knowledge on the nowadays' good practices is very limited. I've basically only done basic local sign-up/sign-in functionality.
The app is related to social networking, so thousands of users might be expected in proximity of a few years. Therefore I want to start off with as clean of architecture as possible, obviously. But also trying to "look into the future" and anticipate costs.
Now, for the project I need to have sign-up/log-in options with:

*

*mobile phone nr.

*email

*Apple account

*Facebook account

I'm looking into managed services like Auth0, AWS Cognito (particularly interested in this one), etc.
But I'm uncertain whether I understand how the process and user account management should be set up. Provided I use a relational DB, do I still need to create the user account models in my application and then:

*

*when a user signs up thru email - my app handles all the auth, including sign-in and access/refresh token generation and handling.

*when a user signs up thru any other 3rd party means - I use the managed auth service and link the user record in the service to a user record in my DB. Then use the managed service for token generation and handling.

Or, do I delegate the whole user management (including the user account models & data) to the managed auth service? And thus, the only functionality related to auth and user account management in my application will be calls to the managed auth service...?

A: I think that you always have to create your own identity (user model with an ID), to unify user management across several identity providers.
Then you map your users to different identity providers: local (email and password), OAuth, Auth0, anything else.
If a user wants to also login via another identity provider, or loses access to one of them, they don't also lose access to your site.


text:
Q: store event in native calendar of iPhone using EventKit.framework I am trying to save event in iPhone calendar using EventKit.framework. Its save perfectly, but I want to set alert to "NONE", but by default it takes '30 minutes before' as alert. How can I solve this problem? Here is my code to save event in iPhone calendar
if ([appDelegate.objEvent.event_alert intValue]==0) {
        alarm1 = [EKAlarm alarmWithRelativeOffset:0];
    }
    else if ([appDelegate.objEvent.event_alert intValue]==1) {
        alarm1 = [EKAlarm alarmWithRelativeOffset:-5];
    }
    else if ([appDelegate.objEvent.event_alert intValue]==2) {
        alarm1 = [EKAlarm alarmWithRelativeOffset:-300];
    }
    else if ([appDelegate.objEvent.event_alert intValue]==3) {
        alarm1 = [EKAlarm alarmWithRelativeOffset:-900];
    }
    else if ([appDelegate.objEvent.event_alert intValue]==4) {
        alarm1 = [EKAlarm alarmWithRelativeOffset:-1800];
    }
    else if ([appDelegate.objEvent.event_alert intValue]==5) {
        alarm1 = [EKAlarm alarmWithRelativeOffset:-3600];
    }
    else if ([appDelegate.objEvent.event_alert intValue]==6) {
        alarm1 = [EKAlarm alarmWithRelativeOffset:-7200];
    }
    else if ([appDelegate.objEvent.event_alert intValue]==7) {
        alarm1 = [EKAlarm alarmWithRelativeOffset:-86400];
    }
    else if ([appDelegate.objEvent.event_alert intValue]==8) {//B4 2 days
        alarm1 = [EKAlarm alarmWithRelativeOffset:-172800];
    }

    NSMutableArray *myAlarmsArray = [[NSMutableArray alloc] init];

//    [myAlarmsArray addObject:alarm1];

//    event.alarms = myAlarmsArray;
//    [myAlarmsArray release];

    if ([appDelegate.objEvent.event_alert intValue]!=0)
    {
        [myAlarmsArray addObject:alarm1];
        event.alarms = myAlarmsArray;
    }
    else
    {
//        [myAlarmsArray addObject:nil];
//        event.alarms = nil;
    }

A: Per the documentation, If you want an alert to fire at, as you say NONE, which i assume you mean to fire at the exact time that the event is, you would use the following code
[EKAlarm alarmWithAbsoluteDate:date];

Link to the documentation for this


text:
Q: Почему появляются прочерки в таблице SQL Таблица от oracle, вот запрос SQL:
select department_id, count(job_id) as count_person,
sum(salary) as salary_per_department
from HR.EMPLOYEES group by department_id

Вот что вернул, откуда прочерк, если в таблице их нет?


text:
Q: Make arbitrary line dashed I have followed this question to achieve an arbitrary line:
Chart.js — drawing an arbitrary vertical line
Fiddle
I use this line of code to change to dashed:
this.chart.ctx.setLineDash([3]);

but this changes the line on the chart too, I only want to change the arbitrary line stroke. How can I adapt this?
Thanks.

A: Just wrap the block where you set the ctx properties and draw with the following lines to save and restore the context,
this.chart.ctx.save();
...
this.chart.ctx.restore();

Fiddle - http://jsfiddle.net/ps3186ex/

var data = {
  labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
  datasets: [{
    data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
  }]
};

var ctx = document.getElementById("LineWithLine").getContext("2d");

Chart.types.Line.extend({
  name: "LineWithLine",
  draw: function() {
    Chart.types.Line.prototype.draw.apply(this, arguments);

    var point = this.datasets[0].points[this.options.lineAtIndex]
    var scale = this.scale

    // draw line
    this.chart.ctx.save();
    this.chart.ctx.setLineDash([3]);
    this.chart.ctx.beginPath();
    this.chart.ctx.moveTo(point.x, scale.startPoint + 24);
    this.chart.ctx.strokeStyle = '#ff0000';
    this.chart.ctx.lineTo(point.x, scale.endPoint);
    this.chart.ctx.stroke();
    this.chart.ctx.restore();

    // write TODAY
    this.chart.ctx.textAlign = 'center';
    this.chart.ctx.fillText("TODAY", point.x, scale.startPoint + 12);
  }
});

new Chart(ctx).LineWithLine(data, {
  datasetFill: false,
  lineAtIndex: 2
});
<script src='https://rawgit.com/nnnick/Chart.js/v1.0.2/Chart.min.js'></script>
<canvas id="LineWithLine" width="600" height="400"></canvas>


text:
Q: Python: How to iterate over rows and apply function to create new columns variable    best m_value  g_value  e_value
       m    8      3       3       7
       g    5      5       5       9
       e    7      6       4       4
       m    3      7       8       2
       m    6      2       1       1
       e    7      6       4       2

This is a tiny mini version of my actual dataframe and I would like to make calculations per row. For each row I would like to subtract best from the column that starts with the variable value (so for example for the first row I would like to subtract best from m_value, as m is indicated in the variable column). Therefore, I have the following function, that subtracts best from the column that starts with the string in variable:
df_test['dif'] = df_test.apply(lambda row: (df_test.loc[row,'best']) - (df_test[df_test.columns[pd.Series(df_test.columns).str.startswith(df_test.loc[row,'variable'])]]), axis=0)

However I get the following error:
(u'None of [0    m\n1    g\n2    e\n3    m\n4    m\n5    e\n6    g\n7    e\nName: variable, dtype: object] are in the [index]', u'occurred at index variable')

How could I correctly apply the function?
example data:
df_test = pd.DataFrame()
df_test['variable']= ['m', 'g', 'e', 'm', 'm', 'e','g', 'e']
df_test['best'] = [8,5,7,3,6,7,8,9]
df_test['m_value']= [3,5,6,7,2,6,6,9]
df_test['g_value']= [3,5,4,8,1,4,7,2]
df_test['e_value']= [7,9,4,2,1,2,3,4]

A: You need not resort to row-wise pd.DataFrame.apply where calculations can be vectorised. Instead, you can use optimised methods available in Pandas. In this case, via pd.DataFrame.lookup:
df_test['dif'] = df_test['best'] - \
                 df_test.lookup(df_test.index, df_test.variable+'_value')

print(df_test)

  variable  best  m_value  g_value  e_value  lookup
0        m     8        3        3        7       5
1        g     5        5        5        9       0
2        e     7        6        4        4       3
3        m     3        7        8        2      -4
4        m     6        2        1        1       4
5        e     7        6        4        2       5
6        g     8        6        7        3       1
7        e     9        9        2        4       5

A: You can do this:
df_test['dif'] = df_test.apply(lambda x: x['best'] - x[x['variable']+'_value'], axis=1)

>>> df
  variable  best  m_value  g_value  e_value  dif
0        m     8        3        3        7    5
1        g     5        5        5        9    0
2        e     7        6        4        4    3
3        m     3        7        8        2   -4
4        m     6        2        1        1    4
5        e     7        6        4        2    5


text:
Q: How to build blog application using microservice architecture? I already have a blog application which is built on Spring-Boot as a monolith.
There are 2 entities.

*

*user

*post

And the mapping is one to many.
A single user can create multiple blog posts.
How can i recreate the same functionality as separate microservice applications.
So far on researching through internet, what i see people saying is create database per service etc.
Suppose if i create 2 services say

*

*UserService(which has separate DB and CRUD operations associated with it)

*PostService(which has separate DB and CRUD operations associated with it)

How can i make communications in between them.
In the monolith app the POST entity has createdBy mapped to User.
But how this works in Microservices architecture?
Can any one please help me how can i design such architecture?

A: First list out the reasons why you want to break it in micro-services. To make it more scalable (in following scenarios for example).

*

*Post comments becomes slow, and during this period registration of
new Users to remain unaffected.

*Very few users upload/download files, and you want general users who simply view comments and post comments to be unaffected, while upload/download files may remain
slow.

Answers of the above question and analyzing,priotizing other NFR's shall help to determine how and what to break.
Additionally,
Post service only needs to validate whether the user is a valid logged in user.(Correct?)
User Service does not really need to communicate with post service at all.
Further you might want to decouple other minor features as well. Which in turn talk to each other which can be authenticated via other means like(Certificates, etc.) as they will be internal and updating some stats(user ranking), aggregates data etc.
The system might also have a lot of smaller hidden features, which might or might not have to do anything with Post Service at all, which can be separated in terms of different micro-services(like video/file/picture/any binary content upload/download) also and prioritized based on computation power needed, hit frequency and business priority.
After breaking it in to micro-services, you need to run some stress tests (based on current load) to know which services needs replication and which not and needs a automatic load balancing. Writing stress load first before breaking can also help to understand which features need to be move out of the monolith first.