text:
Q: Tkinter Listbox : Botton delete the selected Items from the Listbox and JSON files so I have a ListBox on my Tkinter menu, the items on the Listbox are my user.json list-Dict (Code below)
The question is: How can i create a button that delete the Listbox selected items from my JSON list.
I already know the code to delete the Item from the Listbox which is: lb.delete(ANCHOR), but i searched a lot how to delete the selected listbox dicts from my JSON list/dicts which I did not find any result.Thank you for the Help.
My LISTBOX:
#LISTBOX

lb = Listbox(tab2, width=40, height=16)
lb.grid(row=0, column=1)
lb.insert(END, "CLIENTS")

for person in data["person"]:
    ans1 = (f"Name: {person['name']}")
    ans2 = (f" City: {person['City']}")
    ans3 = (f" Gender: {person['Gender']}")
    ans = "\n" + ans1 + "\n" + ans2 + "\n" + ans3 + "\n"
    lb.insert(END, ans)

MY FUNCTION AND BUTTON
def delt():
    lb.delete(ANCHOR)

Button(tab2, text="DEL", command=delt).grid(row=4, column=1)

MY JSON FILE
{
  "person": [
    {
      "Name": "Peter",
      "City": "Montreal",
      "Gender": "Male"
    },
    {
      "Name": "Alex",
      "City": "Laval",
      "Gender": "Male"
    },
    {
      "Name": "Annie",
      "City": "Quebec",
      "Gender": "Female"
    }
  ]
}

A: Since in the json file, the person key is a list of dictionaries, therefore our main task is to convert the row selected in the listbox to a dictionary and then remove that dictionary from the person key and write the changes to the json file.
user.json file
{
  "person": [
    {
      "Name": "Peter",
      "City": "Montreal",
      "Gender": "Male"
    },
    {
      "Name": "Alex",
      "City": "Laval",
      "Gender": "Male"
    },
    {
      "Name": "Annie",
      "City": "Quebec",
      "Gender": "Female"
    }
  ]
}

Code:
import tkinter as tk
import json

window = tk.Tk()

# selectmode='single' says that you can select only one row at a time in the listbox
lb = tk.Listbox(window, width=40, height=16, selectmode='single')
lb.grid(row=0, column=1)
lb.insert('end', "CLIENTS")

# open and load your user.json file
with open('user.json', 'r') as json_file:
    data = json.load(json_file)

for person in data['person']:
    ans1 = person['Name']
    ans2 = person['City']
    ans3 = person['Gender']
    ans = "\n" + "Name: " + ans1 + " \n" + "City: " + ans2 + " \n" + "Gender: " + ans3 + "\n"
    lb.insert('end', ans)

msg_label = tk.Label(window)
msg_label.grid(row=5, column=1)

def delt():
    with open('user.json', 'r') as json_file:
        data = json.load(json_file)

    # get the values that is under selection in list box
    # it returns one long string in the format you inserted the data in the list box (see above-> ans)
    row_values = lb.get(tk.ACTIVE)

    # split the results into a list of words and replace ':' in 'Name:', 'City:' and 'Gender: ' with ''
    row_values = [row_value.replace(':', '') for row_value in row_values.split()]

    # in each list box row,
    # every even index can be thought as keys of a dictionary
    keys = row_values[0::2]
    # every odd index can be thought as values of a dictionary
    values = row_values[1::2]

    # using the keys and values lists, convert the row data into a dict
    # that matches the format of data in your .json file
    row_selection = dict()
    for key, value in zip(keys, values):
        row_selection[key] = value

    # remove the entry from your user.json file
    # if that entry is found in the file
    if row_selection in data['person']:
        data['person'].remove(row_selection)

        # write changes to file
        with open('user.json', 'w') as json_file:
            data = json.dump(data, json_file)

        # delete the entry from listbox
        lb.delete(tk.ANCHOR)

        msg_label.config(text='Row removed from file')
    else:
        msg_label.config(text='Row not found in the file')

delete_btn = tk.Button(window, text="DEL", command=delt)
delete_btn.grid(row=4, column=1)

I have tried to explain every line with a comment. Hope you understand my explanation. Try printing every variable in the delt() function to have clarity.


text:
Q: Do I need to use stationary time series data when building linear model with AR error terms? I have a linear model $y=\beta*x+\epsilon$. However, the error term is modeled as an AR term, where $\epsilon(t)=p*\epsilon(t-1)+w(t)$, $w(t)$ is white noise. Y and X are both time series economic variables.
ADF test shows that both x and y are non-stationary. Johansen test cannot reject the null there are cointegration in between the two variables.
What is the assumption behind?
Is stationarity required on x and y to start with such model?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stringbuilder cannot append white space? import java.util.StringTokenizer;

public class ReverseWords {
    public static void main(String[] args) {
        StringBuilder output = new StringBuilder();
        String str = "This is String , split by StringTokenizer, created by mkyong";
        StringTokenizer st = new StringTokenizer(str);
                char space =' ';
        System.out.println("---- Split by space ------");
        while (st.hasMoreElements()) {
            //System.out.println(st.nextElement());
                     output.insert(0,st.nextElement());
                     output.append(" ");
        }

        System.out.println(output.toString());
        /*System.out.println("---- Split by comma ',' ------");
        StringTokenizer st2 = new StringTokenizer(str, ",");

        while (st2.hasMoreElements()) {
            System.out.println(st2.nextElement());
        }*/
    }
}

I'm trying to just reverse the words of a string and here is what I get:
mkyongbycreatedStringTokenizer,bysplit,StringisThis

A: You are inserting the parts at the front, but all the space at the end.
You could do something like this to address this:
String s = st.nextElement();
output.insert(0, s);
output.insert(s.length(), " ");

Note that this is quite inefficient, as all the accumulated content is shifted back all the time.
Do you need to use a string tokenizer? Otherwise, you could just write
String[] parts = str.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = parts.length - 1; i >= 0; i--) {
  sb.append(parts[i]);
  sb.append(' ');
}

A: Another solution: Change this:
output.insert(0,st.nextElement());
output.append(" ");

to this:
output.insert(0,st.nextElement() + " ");

This makes the space character part of the string you're inserting at the front; the original code appended the space at the end, causing it to become separated from the string that nextElement() returned.


text:
Q: How to add additional labels in my plot in matplotlib? I want something like on the image

here is my code:
import matplotlib.pyplot as plt
import pandas as pd

plt.style.use('seaborn-notebook')

data = {
    'Unmarried woman': [36, 23, 28, 20, 16],
    'Married woman': [26, 38, 49, 14, 38]
}

unmarried_labels = ['30–55', '14–50', '16-59', '16-24', '13-26']
married_labels = ['25–50', '29–59', '34–89', '11–18', '33–55']

df = pd.DataFrame(data, columns=['Unmarried woman', 'Married woman'],
                  index=['Africa', 'Asia', 'Latin America', 'Northern America',
                         'Europe'])

df.plot.barh()

plt.title(
    'Abortion rate per 1000 women aged 15–44 y. by marital status (2010–2014)',
    fontweight='bold', fontsize=11)

plt.show()

A: As of Matplotlib 3.4.0 this can be accomplished with bar_labels and zipping containers with the labels:
# Save axes returned from DataFrame plot
ax = df.plot.barh()
# Iterate over containers and all_labels together
for container, labels in zip(ax.containers, all_labels):
    ax.bar_label(container, labels=labels, label_type='center')

*

*Labels will align with indexes of the DataFrame:

*

*The first list in all_labels will align with column 0 (Unmarried woman) and continue across the columns

*Index 0 in each sub-list (labels) will align with index 0 in the DataFrame which is Africa and continue down the rows.

All Together:
import matplotlib.pyplot as plt
import pandas as pd

plt.style.use('seaborn-notebook')

unmarried_labels = ['30–55', '14–50', '16-59', '16-24', '13-26']
married_labels = ['25–50', '29–59', '34–89', '11–18', '33–55']
all_labels = [unmarried_labels, married_labels]

df = pd.DataFrame({'Unmarried woman': [36, 23, 28, 20, 16],
                   'Married woman': [26, 38, 49, 14, 38]},
                  columns=['Unmarried woman', 'Married woman'],
                  index=['Africa', 'Asia', 'Latin America', 'Northern America',
                         'Europe'])

# Save axes returned from DataFrame plot
ax = df.plot.barh()
# Iterate over containers and all_labels together
for container, labels in zip(ax.containers, all_labels):
    ax.bar_label(container, labels=labels, label_type='center')

plt.title(
    'Abortion rate per 1000 women aged 15–44 y. by marital status (2010–2014)',
    fontweight='bold',
    fontsize=11
)

plt.tight_layout()
plt.show()


text:
Q: Symfony2 Forms - Selected Value in Dropdown using Propel ModelType I'm trying to set the selected value of a 'model' (ModelType from the Symfony Propel Bridge) form type and I'm failing miserably.
There is Product table with the following structure:
id, name, category_id

Example data would be:
id => 1, name => 'Test', category_id => 3

Another table holds the Category data, so category_id is a foreign key.
id => 1, name => 'Category 1'
id => 2, name => 'Category 2'
id => 3, name => 'Category 3'

The form type I'm working with is:
$builder->add('category_id', 'model', array(
    'class' => 'Foo\BarBundle\Model\Category',
    'required' => true,
    'multiple' => false,
    'expanded' => false,
    'label' => 'Pick a product category!',
    'query' => CategoryQuery::create()->orderByName(),
));

Now when I load up the form, I get a nice select drop-down containing the ordered Categories as you would expect.
What I'd like the drop-down to do is display the correct "selected" Category for a Product that already exists (use case: in a Product Edit form).  So, Product ID 1 would have a selected option of "Category 3".
I tried setting a "data" option (which was ignored) so I'm perplexed as to why something so fundamental seems so difficult.
Any help would be greatly appreciated.
UPDATE: Problem solved, see below:
$builder->add('category', 'model', array(
    'class' => 'Foo\BarBundle\Model\Category',
    'required' => true,
    'multiple' => false,
    'expanded' => false,
    'label' => 'Pick a product category!',
    'query' => CategoryQuery::create()->orderByName(),
));

Changed 'category_id' to 'category' and everything was right with the world once more.


text:
Q: Wordpress Admin Bar Not Showing in Front End I have a [shayari website]1 . The issue with this website is when i am posting some shayari and status i am unable to see the admin bar in front end
I Am using Publisher Theme

A: Go to admin > Users > YOUR USERNAME and check the box that says Show Toolbar when viewing site


text:
Q: Composing ActiveRecord scopes with selects Unfortunately, ActiveRecord's select replaces the existing SELECT clause instead of adding to it, so I can't compose queries. Does anyone have a workaround?
Example model:
class Story
  scope :recent, -> { where("created_at >= ?", 1.month.ago) }

  # deliberately simple examples, please don't get distracted memoizing, etc.
  scope :with_net_score, -> { select("`stories`.*, (upvotes - downvotes) as net_score" }
  scope :with_recent, -> { select("`stories.*, greatest(updated_at, last_vote_at) as recent") }
end

So while I can compose Story.recent.with_net_score, Story.with_net_score.with_recent fails. And both with_net_score and with_recent fail when Story comes after a join to an association.
How would you rewrite with_net_score so that it adds to the fields selected instead of replcaing them and can be composed with with_recent and joins?

A: Adding the author's own solution to this:
class ApplicationRecord < ActiveRecord::Base
  scope :select_fix, -> { select(self.arel_table.project(Arel.star)) }
end

https://github.com/lobsters/lobsters/blob/master/app/models/application_record.rb


text:
Q: Cruise control.NET Integration queues? This is a doubt regarding the material published in the
following link
 "http://confluence.public.thoughtworks.org/display/CCNET/Integratio+Queues"
which tells that "The default behaviour of CruiseControl.Net is that
each project defined in the configuration is given its own integration
thread, thereby allowing differently named projects to build
concurrently.
Note however that a single project can never be building more than
once at the same time. If you force a build on Project X while it is
already integrating, that force build request is effectively blocked
until the previous integration completes. So you can also think of
this as each project having its own dedicated integration queue, where
only the item at the head of the queue can be currently building, with
at most one request pending."
But this is really contradicting in my case as when i force my build
it opens my IDE and starts the integration and building which takes
about 3 min approx. but when i force my build in between the execution
on my webdash board i see that it again opens another IDE and starts
the building which is not acceptable.According to the link shown
above,it should queue and wait for the 1st IDE execution to complete
and then go for the 2nd one.
Can u plz suggest any solution to this problem??
with kind regards
Maddy

A: Maybe this is a problem (from the CCNet docs, even I didn't know about this setting):
duplicates: Specification of how to handle duplicate requests within a queue. Possible values are UseFirst, ApplyForceBuildsReplace and ApplyForceBuildsReAdd.
http://confluence.public.thoughtworks.org/display/CCNET/Queue+Configuration

A: We use Integration Queues for a pipe-lining purpose in-case your Projects have dependencies and u want to Build them in an order.
This is how it works:
  ...
  <!-- Put all related projects in same Q, here MyProjectQ-->
  <!-- Set queuePriority, based on who-is-dependent-on-whom -->
  <project queue="MyProjectQ" queuePriority="1">
    <name>MyProject.Main</name>
  </project>
  <project queue="MyProjectQ" queuePriority="2">
    <name>MyProject.Installer.All</name>
  </project>
  ...

HTH

A: This is the ccnet.config file shown below
cruisecontrol>
 <project name="VSAT" queue="Q1" queuePriority="1">
 <sourcecontrol type="filtered">
   <sourceControlProvider type="filesystem">
     <repositoryRoot>C:\MyProj</repositoryRoot>
     <autoGetSource>true</autoGetSource>
     <ignoreMissingRoot>false</ignoreMissingRoot>
   </sourceControlProvider>
 </sourcecontrol>
 <triggers>
        <intervalTrigger name="continuous" seconds="240" buildCondition="IfModificationExists" />
 </triggers>
 <tasks>
   <nant>
      <executable>C:\Nant-0.85\bin\NAnt.exe</executable>
  <buildFile>nant.build</buildFile>
   </nant>
 </tasks>

 <!--<triggers>
   <intervalTrigger seconds="50" buildCondition="ForceBuild"/>
  </triggers>-->
  </project>
</cruisecontrol>

My nant.build file is invoking an IDE always when it sees any modification.The problem is it doesnt queue even though i specify that in my ccnet.config file???
Thanks
Maddy


text:
Q: Mac OS Equivalent file path for Windows file path I am setting up a Java project which uses JBoss which is customized for our project. In one of the properties file under JBoss configuration it has absolute path for various files such as following:
com.mycompany.abc.host.certificate=file:///c:/somedir/jboss/myproject/configuration/security/xxx/test.crt

I am setting up my dev environment on MacBook having macOS Sierra. What would be the equivalent path on macOS for the corresponding Windows path, say for this file: /Users/john/jboss/myproject/configuration/security/xxx/test.crt

A: In Finder, do a right-click on the file of which you need the path. Then press the Option key (alt) to open the context menu. Select Copy "name_of_file" as path. Then you have the path, for example
/Library/Preferences/com.apple.AppleFileServer.plist

To get the file URI, add file://, like so
file:///Library/Preferences/com.apple.AppleFileServer.plist


text:
Q: How to Append string in Textarea in JAVA swing with delay (Without using a timer) I am trying to display results based on an event on the text area. These results are event driven.
jbtnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
File f = new File(installer);
if(f.exists()){
      area.setText("File exists...");
}else{
      area.setText("File not found!");
}
area.append("\n"+installer);
installer1=installer.concat("\\Autoplay");
area.append("\n"+installer1);
File f1 = new File(installer1);
if(f1.exists()){
      area.append("\nF1 File exists");
}else{
      area.setText("F1 not found!");
}

A: installer1=installer.concat("\\Autoplay");

This appears to be a long running task, so you need to execute this code in a separate Thread. The easiest way to do this is to use a SwingWorker. You can then update the text area when the SwingWorker is done.
Read the section from the Swing tutorial on Concurrency for more information and SwingWorker examples.

A: If both parts of the message are in one TextArea: part them via .substring(start, end).
Then print the first part in the way you want to, for example System.out.println().
Then use wait(2000) and then print the second part.
If both texts are in different textareas, just put their content in different variables.
Oh, and the content of the textarea can be returned by .getText().


text:
Q: Play a live, arbitrary waveform through speakers I have a C# program that currently generates a wave based on a formula entered into a parser - the wave can be anything, from a simple sine wave to a noise function. I want to play the wave as it generates through the speakers. What's the best way to do this?

A: Consider generating your waveform and then using NAudio or DirectSound to play it back.


text:
Q: I Tried Everything. No Video With IE-11 I upgraded to IE-11 from IE-8 last week. I don't regularly use IE, but software I use to daytrade with is based on IE. The did a major upgrade and I had to update to IE-11 for their software to work. Everything works fine, except for their CNBC stream. Its an embedded Flash-Player. But its not just this. No videos play at all Youtube, videos on websites... none of them.
Let me start by saying I have tried everything. Flash is current and enabled. Windows is all up to date. The ActiveX filter is off. I have gone through and tried every possible combination of the ActiveX settings and every other setting in IE both under the "advanced" tab and the "programs/manage add ons" settings.
And... when I go to Adobe's test page.... the little animated screen that has a tree growing with clouds floating by works fine. So apparently Flash is working fine, at least on Adobes site. https://forums.adobe.com/external-link.jspa?url=https%3A%2F%2Fhelpx.adobe.com%2Fflash-player.html
But on top of that I have done a "clean flash uninstall" where you run Adobe's on-line cleaner and then go in and manually delete files; followed up with a fresh install. https://forums.adobe.com/thread/928315
Firefox and Chrome..... no problems at all.
This is the error on YouTube: "An error occurred, please try again later"
This is the error on MSN's Homepage videos when I try to play them: We're sorry, an error has occurred when playing video (video format is not supported).
HP Pavillion
Windows 7 Home Premium. All up to date.
SP-1
64 Bit
I even went back through my Windows updates and rolled the IE-11 update back to IE-8.... just to check...everything works fine with IE-8. All videos play as advertised. (I put IE-11 back)
I turned off my firewall (Comodo) and Windows Defender.... that didn't help.
I created a new user account for the PC... that didn't help.
I am friggin lost for ideas.
I wish I understood what I was looking at when I click "inspect element" as I mouse over the inoperative video and all that code comes up because somehow I suspect my answer can be found there, but this is one notch above my skills. But I think I can honestly say I've tried all the obvious fixes. I spent the entire weekend surfing forums.
This is driving me crazy... I mean I can live without it.... but honestly, this is the first computer thing in 20 years I have not been able to figure out for myself.
Any ideas?

*

*Let me add, I tried to post this on Microsoft Community and their forums just kept refreshing as I hit post. Figures.

NEW:
Edit ... this is a screengrab of the "inspect element" of a video on MSN while it was trying to load. "inspect element screenshot

A: Let's try simple things first.
Go to Tools (Alt + X) and in the drop-down menu, there is Compatibility View settings.
Add https://www.youtube.com/ and try again. Let me know if that worked!


text:
Q: opencv2/calib3d.hpp : No suh file or directory (How to link opencv to qt correcttly) I installed opencv 3.4.0-dev and I want to use it with QT.
In the .pro I added :
LIBS += -L/usr/local/lib -lopencv_core -lopencv_imgcodecs -lopencv_highgui -lopencv_calib3d
INCLUDEPATH += /usr/local/include/opencv

but i still have the error
opencv2/calib3d.hpp : No such file or directory
(I also try with highgui, imgcedexs, core, same error)
Any idea to fix it ?
Thank you in advance.

A: As you've figured by yourself, the opencv header path is now nested in /usr/local/include/opencv4.
As for the error you've flagged in the comment, ximgproc is a contrib module and should be added manually. You therefore need to build OpenCV from source or find a pre-built package that has the contrib modules built in.
This question and this OpenCV doc page answers how to build OpenCV with the contrib modules.

A: I fixed it by installing following:
sudo apt install libopencv-calib3d-dev


text:
Q: java.nio.Files, java.nio.Paths on java 6 I need to rewrite some java 7 file IO code that should run on a Java 6 VM too.
The implementation uses handy Java 7 features like autoclosing, Paths and Files.
To be more specific, I need to handle expressions like /tmp/foo/*.bar to return all .bar files (currently implemented with Files.newDirectoryStream(dir, glob)).
Does anyone know a handy library for this?

A: The Apache Commons IO API is also a good choice. I used it for a similar work (rewrite some code from java7 to java6 that used Path object) and they work very well.

A: The Apache Ant API would be a good candidate for this, in particular their FileSet class might do the job.

A: guava runs on java6 and it has a nice I/O api.


text:
Q: Get-AzResourceGroup : 'this.Client.SubscriptionId' cannot be null Having a bit of an issue with Azure and Powershell. I'm just checking to see if a resource group exists and I keep hitting this error. The next step after this is to create the resource group if it does not exist, but that is also throwing the same error. Was hoping someone might be able to suggest some workarounds or fixes.
Please note, I have access to the subscriptions, I can see them and sucessfully set the default subscription as can be seen in the script below.
Full Error Returned
'this.Client.SubscriptionId' cannot be null.
At **********************\envir\create-env.ps1:21 char:1
+ Get-AzResourceGroup -Name $resourceGroup -ErrorVariable $doesNotExist ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-AzResourceGroup], ValidationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceGroupCmdlet

I've just installed the Az module, version details below.
Version    Name                                Repository
-------    ----                                ----------
1.6.0      Az                                  PSGallery

I'm just running a pretty straight forward script (below), I thought it might be something to do with a default subscription not been set, but setting that has made no difference.
$passwd = ConvertTo-SecureString $servicePrincipalKey -AsPlainText -Force
$pscredential = New-Object
System.Management.Automation.PSCredential($servicePrincipalUserName, $passwd)
Connect-AzAccount -ServicePrincipal -Credential $pscredential -TenantId $tenantId
Select-AzureSubscription -Default -SubscriptionName $subscriptioName
Get-AzResourceGroup -Name $resourceGroup -ErrorVariable $doesNotExist

I then get the error listed above.

A: I found the problem, the Service Principal I had created did not have sufficient access to the subscription as suggested by @4c74356b41, I ended up giving it a role of Contributor and that resolved the problem.


text:
Q: Getting my iPhone 6 to trust a computer after selecting Don't Trust I accidentally hit "Don't Trust" on my iPhone and now my MacBook won't unlock my phone. Is there a way to reverse this?

A: Go to Settings → General → Reset → Reset Location & Privacy.
This will reset your trusted computers (along with all your other privacy settings), and next time you connect the device a computer, it will prompt you to trust it. The privacy settings this will reset are all the settings under Settings → Privacy.


text:
Q: What are the options for simple file or data redundancy on a custom NAS? I'm asking this for the sake of clarity as I'm in the process of building a home NAS and going crazy trying to decide how to set it up.
What options are there for no hassle file/data rendundancy to avoid data loss?
What I've concluded so far:

*

*Hardware RAID: not a good idea as failure of the controller can make file/data recovery very difficult and expensive.

*Software RAID: Raid 10 and Raid 5 are interesting but vulnerable if more than one drive fails?

*File duplication: Manual file duplication is tedious and an automatic solution is better.

*FreeNAS: ZFS sounds great but requires a system that has ECC memory and doesn't have any repair utilities for the metadata?

*Unraid: Proprietary and I'm not clear on how this NAS operating system functions.

*Drive pooling: Solutions like drive bender sound robust but I want to find out what's behind the hype.

A: Reliable backup must protect from a lot of things at once - and failure of only one of that layers might make the complete solution useless:

*

*Protect from medium failure

*protect from file system corruption and similar software failure

*protect from deletion, encryption by malware, etc.

There are many tools out there to achieve this: Let's start with RAID:
RAID will protect you from loss of a disk or a few disks. Configured and monitored correctly, it will provide high resilience against medium loss. It does however, and that's important, provide no protection at all against the other two failure points.
File system corruption is rare, but if it hits it very often results in partial data loss. Murphy's law makes sure, it's the most important files that are lost. There are two main approaches to this:

*

*First of all use a very resilient file system: I am hesitant to make recommendations, but I dare say that XFS worked very well for me. In contrast to that, I have already lost ań ext4 file system to software failure.

*Next explore the use of snapshots: This has a lot of advantages, one of them being that even a hot snapshot of the file system is very likely to be mountable without major data loss if really necessary. In addition to that, monitoring the snapshot space usage gives you an idea of the file system change rate, thus alerting you of e.g. a crypto virus maybe before it is too late. It is also trivial to recover a deleted file from a snapshot.

Deletion, encryption, etc. must be fought on different levels: I already mentioned what snapshots can contribute to the mix, but basically what you need is a cold copy of the data. Snapshots may or may not be good enough, that needs to be your choice after deliberation of all circumstances.
EDIT
Let me add one more thing: If you explore ZFS, make sure you know what you do: If something happens to your ZFS strcuture you need very specialized knowledge to get out of that situation. My personal experience is to not rely on it, if you don't have years-long experience in how to recover from problems - else you risk losing everything in one swoop.


text:
Q: Change the flex-direction value to column in Safari and the first flex-item covers the page Sample:

body {
  margin: 0;
  height: 100vh;
  display: flex;
}

body:hover {
  flex-direction: column;
}

div {
  flex: 1;
}

div#tan {
  background: tan;
}

div#teal {
  background: teal;
}

Hover your mouse over the page and here's what you see in Safari 10, macOS Sierra:

And here's how it's supposed to look:

Why do other flex items disappear? What's the solution?


text:
Q: Python: multithreaded learning neural networks using PyBrain and Multiprocessing I'm trying to train a neural network in Python using PyBrain and Python's multiprocessing package.
Here is my code (it trains a simple neural network to learn the XOR logic).
import pybrain.tools.shortcuts as pybrain_tools
import pybrain.datasets
import pybrain.supervised.trainers.rprop as pybrain_rprop
import multiprocessing
import timeit

def init_XOR_dataset():
    dataset = pybrain.datasets.SupervisedDataSet(2, 1)
    dataset.addSample([0, 0], [0])
    dataset.addSample([0, 1], [1])
    dataset.addSample([1, 0], [1])
    dataset.addSample([1, 1], [0])
    return dataset

def standard_train():
    net = pybrain_tools.buildNetwork(2, 2, 1)
    net.randomize()
    trainer = pybrain_rprop.RPropMinusTrainer(net, dataset=init_XOR_dataset())
    trainer.trainEpochs(50)

def multithreaded_train(threads=8):
    nets = []
    trainers = []
    processes = []
    data = init_XOR_dataset()

    for n in range(threads):
        nets.append(pybrain_tools.buildNetwork(2, 2, 1))
        nets[n].randomize()
        trainers.append(pybrain_rprop.RPropMinusTrainer(nets[n], dataset=data))
        processes.append(multiprocessing.Process(target=trainers[n].trainEpochs(50)))
        processes[n].start()

    # Wait for all processes to finish
    for p in processes:
        p.join()

if __name__ == '__main__':
    threads = 4
    iterations = 16

    t1 = timeit.timeit("standard_train()",
                       setup="from __main__ import standard_train",
                       number=iterations)
    tn = timeit.timeit("multithreaded_train({})".format(threads),
                       setup="from __main__ import multithreaded_train",
                       number=iterations)

    print "Execution time for single threaded training: {} seconds.".format(t1)
    print "Execution time for multi threaded training: {} seconds.".format(tn)

In my code, there are two functions: one running single threaded and one (supposedly) running multithreaded using the multiprocessing package.
As far as I can judge, my multiprocessing code is sound. But when I run it, the multiprocessing code doesn't run on more than one core. I verified this by checking the run time (with threads = 4 and 4 cores it takes 4 times as long, while it should take approximately as long as a single threaded run). I double checked it by looking at htop/atop.
I know about the Global Interpreter Lock (GIL), but the multiprocessing package is supposed to handle this.
I also know about the issue that scipy causes the cpu affinity to be set in such a way that only one core is used. However, if I print the process affinity just after scipy is imported in the PyBrain package (print psutil.Process(os.getpid()).cpu_affinity()), I can see that the affinity is ok:
$ python ./XOR_PyBrain.py
[0, 1, 2, 3]
Execution time for single threaded training: 14.2865240574 seconds.
Execution time for multi threaded training: 46.0955679417 seconds.

I observe this behaviour on my Debian NAS as well on my Debian Desktop as well as on my Mac.
Version info for the Debian NAS:

*

*CPU: Intel(R) Atom(TM) CPU D2701   @ 2.13GHz

*Debian 8.4. Kernel: 3.2.68-1+deb7u1 x86_64

*Python 2.7.9

*PyBrain 0.3

*Scipy 0.14.0-2

So, my question is: how do I let PyBrain train on multiple cores?

A: Everything seems currect. I've tested your code and all cores were working. The problem with the timing comes from the fact that "When you try to process small amount of data, CPU cores can't achieve their fill potential."
The network you built, is very simple, so before each core gets 100% usage, the process will end. Think of it as if you wanna process millions of 5x5 pixel images. The time your computer waits for HDD to get the data is much more than time the CPU takes to process them.
The some goes here. But in much faster area (RAM) and much smaller amount of data (one decimal number). Probably if your computer has a DDR4 RAM, things would change. (But I really don't think so)
Try a heavier process, bigger network, more data, etc. and you'll see what you expect.


text:
Q: Select top 2 column sums and names I am trying to calculate the column sums, then select the top 2. This is a sample of the data frame:
df <- data.frame(precinct = c("A", "B", "C"),
                 steve = c(309, 337, 294),
                 mike = c(120, 151, 240),
                 allan = c(379, 442, 597))

I know how to use colSums to get the column totals.
dfColTot <- colSums(df[ , 2:ncol(df)])

From there, how do you select the top 2 sums and names?

A: You could use
top_2=head(sort(dfColTot, decreasing=TRUE), 2)

top_2
#> allan steve
#>  1418   940

Created on 2022-01-20 by the reprex package (v2.0.1)

A: Here is an alternative using order()
df <- data.frame(precinct = c("A", "B", "C"),
                 steve = c(309, 337, 294),
                 mike = c(120, 151, 240),
                 allan = c(379, 442, 597))

dfColTot <- colSums(df[ , 2:ncol(df)])

head(dfColTot[order(dfColTot,decreasing = TRUE)],2)

The result is:
> head(dfColTot[order(dfColTot,decreasing = TRUE)],2)
allan steve
 1418   940

A: Keeping a dplyr option as well.
library(dplyr)

    df %>%
      pivot_longer(cols=-precinct) %>%  #advisable to be it long format since summary is required by names.
      group_by(name) %>%
      summarise(value=sum(value)) %>% #summation per name.
      ungroup() %>%
      slice_max(order_by=value,n=2) # get the top2 based on descending value column

Output:
# A tibble: 2 × 2
  name  value
  <chr> <dbl>
1 allan  1418
2 steve   940

A: A dplyr and base R combination, if you do not want to have to pivot to long form. After summarizing the columns, I convert the row to a numeric list, then sort the the list and return the index number. I keep only the index number, $ix. Then, I sort and get the index of the top 2 values using tail. Then, I use the indices to select the columns.
library(dplyr)

df %>%
  summarise(across(-precinct, sum)) %>%
  select(c(tail(
    sort(as.numeric(.[1, ]), index.return = TRUE)$ix, 2)))

Output
  steve allan
1   940  1418


text:
Q: C++ condition is right but does not work I'm trying to build a simple program that asks for a grade whether it is numerical or general weighted average e.g. 75, 1.5 respectively. And when the user input a non numerical number a stated in the if condition, it prints error as stated also in the else condition. The problem is when I enter a 3-digit,4 , 5 digit number and so on, I get an error that is supposed to be Grade is not within the scope as stated in the nested if (else inside the if condition). Also the same thing happens when I enter 0. But the good thing is, when I enter a negative number or integer, it properly works well. Can I ask what is the problem with my condition? (Tnx in advance)
#include <iostream>
using namespace std;
int main ()
{
double grade;
cout<<"Enter Grade or GWA: ";
cin>>grade;
if (grade!=grade>='a'&&grade<='z'||grade!=grade>='A'&&grade<='Z')
/*The first If condition states that the user will get an error if
input a non-numerical integer or number.*/
{
    if (grade<=5&&grade>=1)
    {
        if (grade>2.5)
            cout<<"Failed"<<endl;

        else
            cout<<"Passed"<<endl;
    }

    else if (grade<75&&grade>=0)
        cout << "Failed" << endl;

    else if (grade>=75&&grade<=100)
        cout << "Passed" << endl;

    else
        cout<<"Grade is not within the scope!"<<endl;
}

else
    cout<<"Error!"<<endl;

cin.get();
return 0;
}

A: Okay, Here are some tips:
grade!=grade>='a'&&grade<='z'

this just does not work like that. grade<='z' is good (syntactically correct). However, grade!=grade>='a' IS NOT. For example;
int a =10;
int b=10;
int c=10;

if (a==b==c){
    cout<< "GOOD";
}
else{
    cout<< "NOT GOOD";
}

As you see you will get NOT GOOD all the time. unless you write (a==b && b==c).
After reading @melpomene comments it made me research more about what datatype should be used, float, double or long double. What I can tell is that it all depends. However the main points almost everybody agrees are:

*

*doubles are the common use for Floating-point-types.

*doubles outperforms floats in modern hardware.

*doubles have equal or better precision that floats. float(6 decimal places precision) doubles(15 decimal places precision).

*double storage size 8 bytes vs float storage size 4 bytes.

Therefore, it all depends, in this case I would agree on doubles :) but again it all depends on the conditions and what exactly we are trying to achieve; performance?, precision?, space?.
Also, you are asking for double values right? where the range is from 0 to 100 right? if so just check if (grade >= 0 && grade <= 100).
Then, if the user inputs 1 how can you say whether it is in the scale from 0-100 or 0-5. You see you have to keep that in mind as well, otherwise it will just go into the first if statement it finds. Oh yeah I got a 4/100 however because I am being checked with the 0 to 5 scale I pass :)

A: Any number bigger then 122 will fail because ascii of z is 122 so grade!=grade>='a'&&grade<='z' will fail.
and also grade!=grade>='A'&&grade<='Z'will fail (Z ascii is 90)
BTW, since grade is a double it will be zero is user enters an illigal number.Just check if(grade !=0)


text:
Q: Can I use same Self signed certificate for different servers? I am developing an Android App and I have different servers (ex: server.example1.com, server.example2.com, server.example3.com) and I do not know if I can use the same Self Signed Certificate in my App or not?
Can anybody explain to me what it the right thing to do?
Should I not use Self Signed Certificate pinned on my App at all or...?


text:
Q: Unexpected if statement behaviour I was running a small bash script, but I couldn't figure out why it was entering a if block even when condition should be false.
$ cat script.sh
#!/bin/bash

if [[ "$@"="-h" || "$@"="--help" ]]
then
    echo 'Show help'
    exit
fi

echo 'Do stuff'
$ ./script.sh
Show help
$ bash -x script.sh
+ [[ -n =-h ]]
+ echo 'Show help'
Show help
+ exit
$ bash -x script.sh -option
+ [[ -n -option=-h ]]
+ echo 'Show help'
Show help
+ exit

So why is $@ equal to -n when I didn't pass any arguments? Also even if it is, how does -n =-h evaluate to true? When I do pass an argument -option, why is it evaluated to true, too?

A: Whitespace is significant. Spaces between the arguments to [[ are mandatory.
if [[ "$@" = "-h" || "$@" = "--help" ]]

Also, "$@" means "all of the command-line arguments". It would be better to just check a single argument.
if [[ "$1" = "-h" || "$1" = "--help" ]]

And for what it's worth, variable expansions in [[ don't have to be quoted. It doesn't hurt, and quoting your variables actually a good habit to develop, but if you want you can remove the quotes.
if [[ $1 = -h || $1 = --help ]]

A: [[ string ]] return true if string is not empty, i.e. it's a shorcut for
[[ -n string ]]

In your case, the string was =-h, that's why you see
[[ -n =-h ]]

To test for string equiality, you have to use the = (or ==) operator, that must be preceded and followed by whitespace.
[[ "$@" = "-h" ]]

Note that "$@" means all the arguments:
set -- a b c
set -x
[[ "$@" == 'a b c' ]] && echo true

gives
+ [[ a b c == \a\ \b\ \c ]]
+ echo true
true

A: The other answers have already explained the problems with your code. This one shows that

*

*bashisms such as [[ ... ]] are not needed,

*you can gain flexibility by using a for loop to check whether at least one of the command-line argument matches -h or --help.

Script
#!/bin/sh

show_help=0
for arg in "$@"; do
  shift
  case "$arg" in
    "--help")
      show_help=1
      ;;
    "-h")
      show_help=1
      ;;
    *)
      ;;
  esac
done

if [ $show_help -eq 1 ]; then
  printf "Show help\n"
  exit
fi

Tests
After making the script (called "foo") executable, by running
chmod u+x foo

I get the following results
$ ./foo
$ ./foo -h
Show help
$ ./foo --help
Show help
$ ./foo bar
$ ./foo bar --help
Show help
$ ./foo bar --help baz -h
Show help


text:
Q: How can I use Scrapy, a python data-scraping API, inside of a web extension? I don't fully understand the limitations of web browser extensions. Can I include python in the file I upload and run python files as well? How do web extensions handle any javascript packages inside of it?

A: No, you can not use Python in your actual extension. WebExtensions are JavaScript, HTML, and CSS. You might want to read "What are WebExtensions?" on MDN.
You're extension can communicate with native applications, or over the network to a server. You could use either of those two methods to have functionality that is written in other languages.


text:
Q: How to create multi lenses or preview using one camera in Android
I wanted to create something like above, that three box, will be like  a camera preview. Any idea or concept on what to do?
I tried getting instance of the camera and place it to three camerapreview objects, but i'm getting an error message, i guess, it's not allowed. here is my code:
  private CameraPreview mPreview;
  private CameraPreview mPreview2;
  private CameraPreview mPreview3;
  private FrameLayout preview;
  private FrameLayout preview2;
  private FrameLayout preview3;

    mCamera=getCameraInstance();
    mCamera2=getCameraInstance();
    mCamera3=getCameraInstance();

    mPreview=new CameraPreview(getApplicationContext(), mCamera);
    mPreview2=new CameraPreview(getApplicationContext(), mCamera2);
    mPreview3=new CameraPreview(getApplicationContext(), mCamera3);

    preview=(FrameLayout)findViewById(R.id.camSetA_qr1);
    preview.addView(mPreview);
    preview2=(FrameLayout)findViewById(R.id.camSetA_qr1);
    preview2.addView(mPreview2);
    preview3=(FrameLayout)findViewById(R.id.camSetA_qr1);
    preview3.addView(mPreview3);

and my getinstance code
 public static Camera getCameraInstance() {
    Camera c = null;
    try {
        c = Camera.open();
    } catch (Exception e) {
    }
    return c;
 }

A: You can only open a given camera (front or back) once; you cannot open the camera multiple times to produce multiple preview streams.  In fact, on most devices, you can't open the front and back cameras simultaneously, since the camera processing pipeline is shared between the two cameras.
To do this, you need to only open the camera once, and then split the output preview data into the three parts that you then display.
If you need to run on Android versions before 3.0 (Honeycomb), then you need to use the preview callbacks. With them, you'll get a byte[] array of YUV data for each frame that you can then crop, convert to RGB, and place in an ImageView or SurfaceView.
On Android 3.0 or later, you can use the setPreviewTexture method to pipe the preview data into an OpenGL texture, which you can then render to multiple quads in a GLSurfaceView or equivalent.


text:
Q: Парсер на Jquery. Поиск конкретного элемента внутри всех найденных Здравствуйте.
Делаю парсер на jquery, но никак не пойму, как мне из нескольких найденных элементов с одинаковым тегом выделить именно нужный?
Поиск осуществляю так:

$(this).find("link_fajla_org").text()

Так вот в xml-документе объектов с именем link_fajla_org у каждого блока несколько. Как мне выделить нужный? Вот часть xml:
<fail>
  <tip_fajla>план первого этажа в зеркальном отображении</tip_fajla>
  <type_nr>6</type_nr>
  <link_fajla>111</link_fajla>
</fail>
<fail>
  <link_fajla_org>222</link_fajla_org>
  <type_nr>18</type_nr>
  <link_fajla>333</link_fajla>
  <tip_fajla>визуализация спереди большая</tip_fajla>
</fail>

Как, например, мне вытащить link_fajla, у которого type_nr=6?
A: Возможно так?
$(this).find("type_nr").each(function(i,elem) {
    if($(this).text() == 6) {
           var text = $(this).parent().find("link_fajla").text()
           alert(text);
        }

});

http://jsfiddle.net/8pzL0nt5/


text:
Q: Google maps api get lat and lng dynamically When I run my code, the map doesn't display. I am working on my localhost. I want to put lat and lng to inputs. Then when I change the lat and lng the inputs will change dynamically. How can I solve this problem?
<!DOCTYPE html>

Lat: <input type="text" id="lat">

Lng: <input type="text" id="lng">

A:
You have some bugs in your code.. and you are not calling the function
  initialize(). Try this updated code

<!DOCTYPE html>

Lat: <input type="text" id="lat">

Lng: <input type="text" id="lng">

A: Here I can save selected coordinates. İt may help someone.
<!DOCTYPE html>

Lat: <input type="text" id="lat">

Lng: <input type="text" id="lng">

result


text:
Q: values in primefaces edit dialog not getting updated I have table Providers.I am displaying the table contents in primefaces datatable and performing create,edit and delete operations on it using Jdbc and Tomcat 7.0.
In the edit dialog there are save and cancel buttons. When I click the cancel button and click on the edit button of another row the values of previous row are getting displayed.
I am getting the following warnings when I click on the cancel button:
com.sun.faces.application.view.FaceletPartialStateManagementStrategy saveDynamicActions
WARNING: Unable to save dynamic action with clientId 'editproviderform:btnCancelProviders' because the UIComponent cannot be found
Providers table structure:
ProviderId,
ProviderFirstName and
ProviderLastName
Providers.java
public class Providers implements Serializable {

private static final long serialVersionUID = 1L;
private Integer providerId;
private String providerFirstName;
private String providerLastName;

public Providers() {
}

public Providers(Integer providerId) {
    this.providerId = providerId;
}

public Providers(Integer providerId, String providerFirstName, String providerLastName) {
    this.providerId = providerId;
    this.providerFirstName = providerFirstName;
    this.providerLastName = providerLastName;
}

public Integer getProviderId()
{
    return providerId;
}

public void setProviderId(Integer providerId)
{
    this.providerId=providerId;
}

public String getProviderFirstName()
{
    return providerFirstName;
}

public void setProviderFirstName(String providerFirstName)
{
    this.providerFirstName=providerFirstName;
}

public String getProviderLastName()
{
    return providerLastName;
}

public void setProviderLastName(String providerLastName)
{
    this.providerLastName=providerLastName;
}

}
ProvidersBean.java
@ManagedBean(name = "providersBean")
@SessionScoped
public class ProvidersBean implements Serializable {

private Providers selectedProvider;

public Providers getSelectedProvider() {
    return selectedProvider;
}

public void setSelectedProvider(Providers selectedProvider) {
    this.selectedProvider = selectedProvider;
}
private Connection con;
@Resource(name = "jdbc/abc")
private DataSource ds;

public ProvidersBean() {
    try {
        Context ctx = new InitialContext();
        ds = (DataSource) ctx.lookup("java:comp/env/jdbc/ClinicalStudy");
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

public void updateProvider() {
    try {
        con = ds.getConnection();
        PreparedStatement ps = con.prepareStatement("UPDATE Providers SET
    ProviderFirstName=?,ProviderLastName=? WHERE ProviderId=?");
        ps.setString(1, selectedProvider.getProviderFirstName());
        ps.setString(2, selectedProvider.getProviderLastName());
        ps.setInt(3, selectedProvider.getProviderId());
        ps.executeUpdate();
        clearSelectedProvider();
        ps.close();
        con.close();
    } catch (SQLException e) {
        System.out.println("SQLException:" + e.getMessage());
    }
}

@PostConstruct
public void init()
{
    selectedProvider=new Providers();
}

public void clearSelectedProvider()
{
    selectedProvider = null;
}

public void close(CloseEvent event)
{
    event.getComponent().getChildren().clear();
    clearSelectedProvider();
}

}
Edit dialog code
<p:dialog id="_EditProvider" header="Edit Provider" widgetVar="EditProvider" modal="true"
                  showEffect="fade" hideEffect="fade" resizable="false" position="center"
                  appendToBody="true">
            <p:ajax event="close" listener="#{providersBean.close}"
                    update=":editproviderform" global="false"/>
            <h:form id="editproviderform">
                <p:panelGrid columns="2" rendered="#{not empty providersBean.selectedProvider}">

                    <h:outputLabel for="EdtProviderFirstName" value="ProviderFirstName*:"/>
                    <p:inputText id="EdtProviderFirstName" value="#{providersBean.selectedProvider.providerFirstName}"
                                 required="true" requiredMessage="FirstName must be entered" maxlength="30"
                                 validatorMessage="FirstName must be an alphanumeric value">
                        <f:validateRegex pattern="[a-zA-Z0-9\s]+"/>
                    </p:inputText>

                    <h:outputLabel for="EdtProviderLastName" value="ProviderLastName*:"/>
                    <p:inputText id="EdtProviderLastName" value="#{providersBean.selectedProvider.providerLastName}"
                                 required="true" requiredMessage="LastName must be entered" maxlength="30"
                                 validatorMessage="LastName must be an alphanumeric value">
                        <f:validateRegex pattern="[a-zA-Z0-9\s]+"/>
                    </p:inputText>

                    <p:commandButton id="btnUpdateProvider" value="Save" actionListener="#{providersBean.updateProvider()}"
                                     update=":providersform:providersdt :providersmessages:messages" oncomplete="handleEditProviders(xhr,status,args)"/>
                    <p:commandButton id="btnCancelProviders" value="Cancel" actionListener="#{providersBean.clearSelectedProvider()}"
                                     oncomplete="EditProvider.hide()"/>

                </p:panelGrid>
            </h:form>
        </p:dialog>

Below is the code for the edit button in datatable:
<p:column style="text-align: center;">
                    <p:commandButton id="btneditproviders" value="Edit" update=":editproviderform" oncomplete="EditProvider.show()" title="Edit">
                        <f:setPropertyActionListener value="#{item[0]}" target="#{providersController.selectedProvider}"/>
                    </p:commandButton>
                </p:column>


text:
Q: How to call a package added previously I'm using the package mcode to show matlab code in my thesis. This package requires the xcolor package so it automatically loads it. My problem is that I have to call the table option in the xcolor package but when I call it after mcode I get an error  because it was previously called in mcode. How can I resolve the issue?

A: Add
\PassOptionsToPackage{table}{xcolor}

before \documentclass{...} and no need of loading xcolor by yourself.
Or add the option table to document class itself:
\documentclass[table]{article}

A: Just use
 \usepackage[table]{xcolor}

before loading mcode


text:
Q: How to use Ant Script to Start and Stop JMeter test I'm new to JMeter and Ant and my web searches have not been fruitful so I'm posing a question here:  Is it possible to start and stop a JMeter script using Ant?
Here's what I'm trying to do:
I have a JMeter test plan with a loop in it that is to simulate a user (or several users) sitting on a page for an indeterminate amount of time after a page refresh.  In JMeter GUI mode, I can schedule the thread group to spin up users at a specified time and continue doing so for a specified duration. I'd ideally run this script for 45 minutes or so, stop the script and analyze the results.  I would like to automate the running of this script and Ant seemed like the way to go.  I did not see an appropriate property to specify a start time or a duration when running the script.  Does such a thing exist?  Is there a suitable workaround?  Any help that can be offered is greatly appreciated.

A: There is a JMeter Ant Task available. You can kick off your Test Plan using this Task according to documentation.
For 45 minutes test duration I would go for the following:
<jmeter
    jmeterhome="/path/to/your/JMeter/installation"
    testplan="/path/to/your/test/plan.jmx"
    resultlog="/path/to/your/test/results.jtl">
    <property name="duration" value="2700"/>
</jmeter>

And put ${__P(duration,)} into Thread Group Scheduler's "Duration" input field

Once you start Ant JMeter will pick up that "duration" property and ask threads to stop when 2700 seconds (45 minutes) pass. Remember that in case of high number of threads shut down process may not be immediate as JMeter might need some time to gracefully shut down all the test threads.
For detailed explanation on using JMeter Ant Task and few more options of running tests in non-GUI mode see 5 Ways To Launch a JMeter Test without Using the JMeter GUI guide.

A: From what have you written I think you want to schedule a test from non-gui mode and control the parameters also. I am not sure about ant but we have workaround.
For this you can use JMeter non-gui features

*

*If you want to start a test then you can use
Jmeter.bat/.sh -n -t

*You can stop the test using stoptest.bat/.sh and shutdown.bat/.sh at any time (Maybe a wrapper shell/batch script can help you to automate this)

*For specifying parameters you can override the existing parameters by specifying them from command line as properties local/global like,
-D[prop_name]=[value] - defines a java system property value
-J[prop name]=[value] - defines a local JMeter property

and use these properties in your test plan so that you can pass values while running the test for a specific amount of time or infinitely and stop the test in between (like you said after 45 min) using stoptest.bat/.sh
Example,
In Thread Group set Number of Threads to ${__property(users,,)} and specify it from command line as,
jmeter -Jusers=50 -n -t Test_Plan.jmx

Remember this local property and not global.
For using properties and non-gui mode you can refer this, Jmeter Manual


text:
Q: Limit Node express to specific hostnames? What's the best way to reject requests to my web server (running via Node express) that are coming in to an unrecognized hostname? I.e. I only want to respond to requests that are intended for my domain, not for requests that are just aimed at my IP address.

A: The easiest way would probably be to use the connect vhost middleware.
Where you would normally do this:
var app = express();
app.get('/', function(req, res){
   res.send('HI');
});

app.listen(80);

You would do this:
var vhostApp = express();
vhostApp.get('/', function(req, res){
   res.send('HI');
});

var app = express();
app.use(express.vhost('example.com', vhostApp));
app.listen(80);


text:
Q: How to make tableViewCell Vertical Paging like a carousel Currently tableview cells look like this: current cell image When my app first opens it looks like the picture on the left and when I scroll one page down it looks like the picture on the right.
However I want it to look like a carousel: like this
I want it so when it I scroll (paging enabled) the bottom cell comes to middle cell spot, and the new bottom cell is at the old bottom cell spot, and the middle cell is at the top cell spot.
Possible Solutions/Questions:
How would I make the UITableViewCells infinitely loop, and thus start off with the ability to scroll up and down, since the last cell would be above the first cell to begin with. Right now there is no cell above the first one, which poses a problem.
CODE:
 func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

        targetContentOffset.pointee.y = self.tableView.contentOffset.y + 100
    }

I want to basically snap the bottom card/ top card that is swiping to the middle of the screen.


text:
Q: Upgrading from 10.04 to 11.04 I want to upgrade Ubuntu 10.04 to 11.04 offline. I have burnt a Ubuntu 11.04 CD. During the installation there's an option; "Upgrade to 11.04". Will choosing this option affect my Windows partition? I don't want my Windows partition to be affected.

A:
The option "upgrade 10.04 to 11.04" is not like upgrading 10.04 to 11.04 via an upgrade to 10.10.. This option means that all data from your /home will be preserved but you will have to reinstall your idividual applications and you will also have to create your users again. User setting from these applications (including passwords in the keyring) will be preserved.
"Upgrade from 10.04 to 11.04" therefore is like a clean installation (i.e. "Erase Ubuntu and reinstall") but without formatting your drive and without erasing /home.
As with all OS upgrades it is strongly recommended to backup your data before you proceed.
Your Windows partition(s) will only be touched and deleted by choosing "Erase everything".

A: Since long ago, all LiveCD installations from Ubuntu give the option to delete the whole partition, install side by side with the OS you already have installed and even resize the partition if you want to give more or less to Ubuntu. So the answer is NO it will not delete your windows. You have to literally tell it to do so with an option that says something like "Delete the partition and install Ubuntu".
I can vouch for 9.10, 10.04, 10.10 and 11.04. Do not remember from way back more. You do not loose data, corrupt the hard drive, etc..

A: The upgrade option won't touch windows, and all going to plan, should not damage your data on your Ubuntu partition either. However many things can go wrong with an update, especially with regards to the install media, so like previous posters have said, back up your data.
It certainly wouldn't hurt to put your /home data on a separate partition, at least then you can format the system partition, if need be, without harming either your personal files or program configurations. The programs would need to be reinstalled however

A: Don't worry, Windows won't be touched if you click 'Upgrade Ubuntu 10.04 LTS to 11.04' If you click 'Erase everything and reinstall' then Windows will still be installed, but everything will be gone like Documents, Pictures, Programs etc. Just make sure that you click Upgrade Ubuntu!

A: you can't upgrade from 10.04 to 11.04, you need to upgrade to 10.10 first od do a clean install of 11.04. Do as you wish and luck ;)


text:
Q: Magento2 - Is it possible to get specific store url in cms block? I am trying to get store URL or base URL for a specific store in cms block.
I have tried {{store _store="1"}}
Also, {{config path="web/secure/base_url"}}
I wanted to know if this is going to work or is there any solution for this

A: You Can try this
Link to Base URL

or This may be helpful
Link to Base URL

A: You can use base url followed by store code {{base url=''}}storecode
or
{{base url='storecode'}}

A: The below solution worked for me:
Why ABC


text:
Q: Wrap text function not creating new lines I have a d3 chart with a title. The title is the chart. However, on small screens the text needs to be wrap as not to over flow.
However the Bl.ocks text wrap method is not creating new lines and instead creating a new tspan for every word and then placing each text/tspan on top of one another
Here is a jsfiddle of the issue: jsfiddle here
Here is the relevant code
var chartTitle = svg.append("text")
                .attr("y", -15 )
                .attr("text-anchor", "start")
                .text("This is a very long chart title that should be wrapped!")
                .attr('class','chartTitle')
                      .call(wrap, width/2);

        function wrap(text, width) {
            text.each(function() {
              var text = d3.select(this),
                  words = text.text().split(/\s+/).reverse(),
                  word,
                  line = [],
                  lineNumber = 0,
                  lineHeight = 1.1, // ems
                  y = text.attr("y"),
                  dy = parseFloat(text.attr("dy")),
                  tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
              while (word = words.pop()) {
                line.push(word);
                tspan.text(line.join(" "));
                if (tspan.node().getComputedTextLength() > width) {
                  line.pop();
                  tspan.text(line.join(" "));
                  line = [word];
                  tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
                }
              }
            });
          }

CSS
.chartTitle{
  font-size:20px;
}

A: That wrap function, originally written by Mike Bostock (D3 creator) for wrapping labels, uses the text dy attribute (which is automatically created by the axis generator). That being said, the problem with your code is that there is no dy attribute in that text element.
You can simply tweak the function or just set a zero dy attribute. Here is a demo using the latter:

var svg = d3.select("body")
  .append("svg");

var chartTitle = svg.append("text")
  .attr("y", 20)
  .attr("dy", 0)//set the dy attribute
  .attr("text-anchor", "start")
  .text("This is a very long chart title that should be wrapped!")
  .attr('class', 'chartTitle')
  .call(wrap, 300 / 2);

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
      words = text.text().split(/\s+/).reverse(),
      word,
      line = [],
      lineNumber = 0,
      lineHeight = 1.1, // ems
      y = text.attr("y"),
      dy = parseFloat(text.attr("dy")),
      tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>


text:
Q: Jquery pegando o pai do  Boas pessoal, preciso pegar o ID da tr do  que foi clicado. Meu HTML é o seguinte:

        Nome
        Data de Nascimento
        Telefone
        Email

      @foreach($clients as $client)

id }}">
            {{ $client->name }}
            {{ $client->birthdate }}
            {{ $client->phone }}
            {{ $client->email }}
            delete_forever

      @endforeach

Estou usando o Blade do Laravel para iterar o objeto que vem do Controller, minha dúvida é o seguinte, se o usuário clicar nesta em uma , como eu faço para o pegar o id que está na tr dele, estou tentando fazer assim:
$(this).closest('tr').html()

O JS está assim:
$(".delete_client").click(function(e){

  console.log($(this).closest('tr').html());

});

O problema é que ele pega a tr sempre da primeira iteração, se eu tiver 10 linhas, ela pega sempre a primeira, e eu preciso pegar a do que foi clicado..
Alguma dica?
Agradeço, abraços

A: A resposta do @Dvd foi a correta,
$(this).closest('tr').attr("id")

Eu estava usando o .html(), por isso estava me mostrando todo conteúdo dentro da TR e não o .attr("id") para obter o ID da tr.
Agradeço quem respondeu.

A: Uma vez que estás a montar isso no PHP tens 2 possibilidades:
Passando o ID com o PHP com onclick="delete("{{ $client->id }}")":

  @foreach($clients as $client)

id }}">
        {{ $client->name }}
        {{ $client->birthdate }}
        {{ $client->phone }}
        {{ $client->email }}
        id }}")">delete_forever

  @endforeach

Assim precisas só de ter uma função de nome deleteRow que recebe a ID.
Usando JavaScript (ou jQuery):
Aqui é mais como menos como já referiste:
$(".delete_client").click(function(e){
  var id = this.closest('tr').id;
  // ou com jQuery
  // var id = $(this).closest('tr').attr("id");
});


text:
Q: Control (avoid) changing fields with side-effects I have been thinking about a design problem and possible solutions in my own. I am pretty sure I am not the first one to have noticed it, but I cannot google for it since I do not know the standard naming of the different participants.
It is NOT the state pattern.
My problem is that, when dealing with ORM, I often end with something like that
Employee
--------
Id
Name
Surname
BirthDate
DefunctionDate

And using an Object Relation-Mapping (in my case JPA), I end with two entities, Employee and Contract.
Now, most of the fields of Employee are just "intranscendent"(*1). It really does not affect the application if the Employee's name changes from 'John' to 'Mike'. As long as I put some validation for the input fields. But if, say, defunctionDate changes from null to some date, some logic must be executed (for instance, closing the current contracts, revoking system access, etc.). I would call those terms "transcendent"(*1).
The first step would be add an specific operation which sets such field setDefunctionDate and handles such logic, and I am ok with that. The problem that appears is how to ensure that the fields are not updated when updating "cargo" data.
I see three "easy" options:

*

*Ignore changes in a bean: If I have an update(Employee employee) method, then each time the method is executed I should retrieve the object from DB and set the "transcendent" field(defunctionDate) of the incoming object with the value from the object stored in the DB. That "retrieve the object from DB" means one or several extra accesses to DB, which are not a good thing. Also, this has issues when there is cascading of the changes.

*"Observer" pattern: Like 1., but in this case a modification is found in a "trascendental" change a listener that handles the extra logic is fired.

*Another possible solution is having a method for each field in the entity, but I think this will usually be too verbose, and will break the purpose of having an ORM.
Of the previous options, I thing 2) would be the best, but I still do not like the fact of the extra DB accesses even when no trascendent field has been changed.
The only solution I can think of would be moving those "trascendental" fields to a separate entity, which would be in a one-to-one relationship with the original entity. Something like
Employee
--------
Id                   Employee_Trascendent
Name       --------> ---------
Surname              Employee_Id
BirthDate            DefunctionDate

The API would only allow direct modification of the Employee entity, and DefunctionDate would only be modified by an specific API method.
That said, I find my solution a bit overcomplicated and, since I cannot see any reference to anything similar, I think that maybe I am missing some more obvious solution.
I would like your help to determine the correct terms to search ideas for and, if why I propose has a name, its name.
*1: If you know a better term please tell me it, remember I do not know the proper terminology.

A: As I see it, the ORM doesn't create the side effects, your code does.  If you ask an ORM to save an entity, it does so, without performing additional operations, or should there be a database trigger of some sort, in my personal opinion you should remove it in favor of having more control in your program.
As such, don't worry about saving your entity multiple times (perhaps once in creation of an Employee once you know first name, last name, birth date, etc., then later in a later step).    If your program handles input of this information in multiple steps, then it should be saving as you go along.  The stress that you put on the database is only slightly more than it would be otherwise, and look what you gain in exchange:  stability and simplicity.  These are two commodities worth far more than performance and I would choose to have a stable and simple program with a slight performance hit over a fast instable and complicated program any day of the week.
I suggest that you use option 4.  You have one dbo section in your program that performs the actual duty of saving an Employee.  It gets accessed from different areas of your program, namely when you need to update information on an Employee that won't create side effects, and when you need to update information on an Employee that will create side effects.  In the latter case, you should perform all side effects in a transaction such that should the side effects or actual save of Employee fail, nothing is done.
The dbo should only provide the means to perform the save in its own transaction or as part of another transaction, but it should not know what side effects result from saving Employee.
I hope that answers your question.


text:
Q: Proving variation of log-sum-exp is convex Let $S$ be a proper subset of $\{1,\ldots,n\}$ and consider a function
$$f(x_1,\ldots,x_n) = \log \sum_{i=1}^n e^{x_i} - \log \sum_{i \in S} e^{x_i},$$ so that the first term is a log-sum-exp function of n variables, and the second term is a log-sum-exp function of a subset of this variables.
Is this function convex? It is the difference of two convex functions, and it seems that the first term should be ``more convex'' than the second one, but the Hessian gets very messy.

A: Consider $n=3$ and $S=\{1,2\}\subset\{1,2,3\}$. If the corresponding $f$ is convex, then
$$ t \mapsto f(t, -t, 0) = \log\left(1+\frac{1}{2\cosh t}\right) $$
should be also convex. However, this functions is not convex. (Note that this function achieves the maximum value at $t = 0$ and then decays to $0$ as $t \to \pm \infty$.)


text:
Q: Remove Delete Icon From One2many Field on condtion Base(Odoo 11) I want to remove the delete icon in Odoo for some line in the one2many field where the Boolean field is True

A: You need to disable default delete button, then create your own delete button and apply your condition on it:
<tree string="My Tree" delete="false">
    <field name="my_field1"/>
    <field name="my_field2"/>
    <field name="my_boolean_field"/>
    <button name="unlink"
            string="Unlink"
            type="object"
            class="btn-secondary"
            attrs="{'invisible': [('my_boolean_field', '=', False)]}"
            icon="fa-trash-o"/>
</tree>


text:
Q: Unable to echo user queries in results I am learning PHP and in the process of making a search engine. The following code will not echo the users input, in the search field, on the results page.
The search page:
<!DOCTYPE html>

    <title>Search Engine</title>

    <form action="result.php" method="post">
      <input type="text" name="user_query" size="80" placeholder="Enter Search Here" />
      <input type="submit" name="search" value="Search Now" />

The results page:
<!DOCTYPE html>

    <title>Results</title>

    <form action="result.php" method="get">
      Enter Query Here:
      <input type="text" name="user_keyword" size="80" />
      <input type="submit" name="result" value="Search Now" />
    </form>

    <?php
      if(isset($_GET['search'])) {
          $get_value = $_GET['user_query'];

          echo "

              $get_value;

";
      }
    ?>

Can someone tell me why the user's input is not being echoed when the search is run?

A: If you using method=post
In form tag you must receive you data as $_POST
Also method=get use $_GET
Edit this lines in result page to this
<?php

    if(isset($_POST['search'])){
    $get_value = $_POST['user_query'];

    echo "
{$get_value}
";

    }

?>

A: well the problem lies in your form tag you should have used method="get" if you want to get some data from database and if you are using method="post" you should have to use $_POST['search'] so your form tag shuld have to be like this
<form action="result.php" method="get">

and if you are going to use method="post" anyway than your $_GET['search'] should have to be $_POST['search']
but i will suggest you to use method="get" for searching query from database


text:
Q: Center inline-block Div not working So I'm trying to create a drop down menu with the select and options elements that displays when the device width gets small enough.  My problem is I can't center the div that the select element is contained within for some reason (the div id is "navbar2").  It just hugs the left side of the screen.  Can anyone see my mistake here?
#navbar2 {
  display:none;
}

@media (max-width:380px) {
  #navbar2 {
      display:inline-block;
      width:80%;
      margin-left:auto;
      margin-right:auto;
      border:1px solid red;
  }

  #navbar2 select {
      width:40%;
  }
}

A: So I figured this out.  Apparently the "auto" trick doesn't work on inline-block elements.  So I switched the "display" to "display: block;" and it centered the div horizontally.


text:
Q: Regular Expression to check starting and ending of a email id to check bounced users I need to check for bounced users from a list.
user_testfirstname@companyit.com = correct
user_testfirstname@gmail.com = incorrect
users_testfirstname@companyit.com = correct
it should start with either user_ or users_ and end with @companyit.com
only starts with is there i need a combination of both as above.
$email_id = "user_test@companyid.com";

if (preg_match("#^user_(.*)$#i", $email_id)){

echo 'bounced';

}
else{

echo 'registered';

}

Any suggestions ???

A:
should start with either user_ or users_ and end with @companyit.com

Try this regex:
preg_match("#^users?_(.*?)@companyit\.com$#i", $email_id);


text:
Q: Why is my C program skipping over this if statement? I have this C program that I am writing in code composer studio.
#include <msp430.h>

/*
 * main.c
 */
int main(void)
{
    WDTCTL = WDTPW | WDTHOLD;    // Stop watchdog timer

    int R5_SW=0, R6_LED=0, temp=0;

    P1OUT = 0b00000000;     // mov.b    #00000000b,&P1OUT
    P1DIR = 0b11111111;     // mov.b    #11111111b,&P1DIR
    P2DIR = 0b00000000;     // mov.b    #00000000b,&P2DIR

    while (1)
    {
        // read all switches and save them in R5_SW
    R5_SW = P2IN;

    // check for read mode
        if (R5_SW & BIT0)
          {
            R6_LED = R5_SW & (BIT3 | BIT4 | BIT5); // copy the pattern from the switches and mask
            P1OUT = R6_LED;            // send the pattern out
          }

        // display rotation mode
        else
            {
            R6_LED = R5_SW & (BIT3|BIT4|BIT5);
            // check for direction
            if (R5_SW & BIT1) {// rotate left
                R6_LED << 1;
            } else {
                R6_LED >> 1;
            }   // rotate right

            // mask any excessive bits of the pattern and send it out
            R6_LED &= 0xFF;             // help clear all bits beyound the byte so when you rotate you do not see garbage coming in
                P1OUT = R6_LED;

                // check for speed
            if (R5_SW & BIT2)   {__delay_cycles( 40000); }  //fast
                else            {__delay_cycles(100000); }  //slow
         }
    }
}

When it gets to this if statment in debug mode
if (R5_SW & BIT1) {// rotate left
    R6_LED << 1;
} else {
    R6_LED >> 1;
}   // rotate right

It skips over it, it doesn't run the if or the else block. At this point in the code R5_SW is 22 which is 0010 0010 in binary so R5_SW & BIT1 should evaluate to true. What am I missing here?

A: If you use an operation like << or >> without assigning it then the result is just discarded.  Try this:
if (R5_SW & BIT1)
{
    R6_LED = R6_LED << 1;
}
else
{
    R6_LED = R6_LED >> 1;
}

Or, for brevity:
if (R5_SW & BIT1)
{
    R6_LED <<= 1;
}
else
{
    R6_LED >>= 1;
}

A: This piece of code...
if (R5_SW & BIT1) {// rotate left
    R6_LED << 1;
} else {
    R6_LED >> 1;
}   // rotate right

evaluates either the expression R6_LED >> 1 or the expression R6_LED << 1 but it doesn't do anything with the result of it, so the compiler chooses to throw it away the entire IF statement.
A line such as a>>b by itself doesn't modify a. It is not like for example a++ which does modify a.


text:
Q: MongoDb insert date field without ISODate option I've to insert one date field in mongodb document without ISODate option. Whenever i insert date filed in mongodb it will automatically saved as ISODate format.. I dont want this behaviour.
For example,
"_id" : ObjectId("54992436a3baafe79eb67903"),
"name" : "example",
"insert_dt" : new Date("2014-12-26 12:36:00")

I need to be store in same above mentioned order.

A: MongoDB, when you don't give timezones to your dates (as in your example), assumes that they're UTC (http://en.wikipedia.org/wiki/Coordinated_Universal_Time), which is the only sane thing it can do (a date/time, without timezone info, means nothing).
What you really want to do is handle timezones in your program, because if you don't your program will behave erratically when you use it in winter/summer (depending on how DST works in your country), or when someone uses it from another country, or even in a different part of the US (yay for eastern/central/pacific time zones).
Fortunately, most programming languages come with facilities to deal with timezones, or have easily downloadable external libs to do that. As a Python dev my favorite is PyTZ (http://pytz.sourceforge.net/), and it looks like Node has a nice one at https://www.npmjs.com/package/timezone


text:
Q: How do I create n canvases from within Javascript? I am looking for a way to create canvases as I need them at run time. my code so far is
    var isCanv = new Array();//bool array for which places in the arrays are/are not in use
    var canv = new Array();//for the canvases
    var ctx = new Array();//for the contexts
    var inhtml = new Array();//for the html canvas tags for each canvas
    var upperBound = -1;//the highest index used so far

    function createCtx(){
      var i = 0;
      while(isCanv[i]){
        i++;
      }
      inhtml[i] = '<canvas id="canv'+i+'" width="'+800+'px" height="'+800+'px" style="display:block;background:#ffffff+;"></canvas>';
      isCanv[i] = true;
      if(i>upperBound){
        upperBound = i;
      }
      var tohtml = '';
      for(var j = 0; j<= upperBound; j++){
        if(isCanv[i]){
          tohtml+=inhtml[j];
        }
      }
      document.getElementById('game').innerHTML=tohtml;
      canv[i] = document.getElementById('canv'+i);
      ctx[i] = canv[i].getContext('2d');
      return(i);
    }

    function keyEvent(event) {
      var i = 0;
      while(isCanv[i]){
        ctx[i].fillStyle="#00FFFF";
        ctx[i].fillRect(0,0,800,800);
        i++;
      }
    }

and the html looks like this
    <!doctype html>

        <meta charset="utf-8">
        <title>redicated</title>

This works for the first canvas, but any subsequent addition breaks it all.
Does anyone know how I could fix this, or of a better way of doing it?
Edit:
I figured it out. I need to recreate the context every time there is an addition. now my code looks like
    function createCtx(){
      var i = 0;
      while(isCanv[i]){
        i++;
      }
      inhtml[i] = '<canvas id="canv'+i+'" width="'+800+'px" height="'+800+'px" style="display:block;background:#ffffff+;"></canvas>';
      isCanv[i] = true;
      if(i>upperBound){
        upperBound = i;
      }
      var tohtml = '';
      for(var j = 0; j<= upperBound; j++){
        if(isCanv[j]){
          tohtml+=inhtml[j];
        }
      }
      document.getElementById('game').innerHTML=tohtml;
      for(var j = 0; j<= upperBound; j++){
        if(isCanv[j]){
          canv[j] = document.getElementById('canv'+j);
          ctx[j] = canv[j].getContext('2d');
        }
      }

      return(i);
    }

A: The for loop:
 for(var j = 0; j<= upperBound; j++){
    if(isCanv[i]){
      tohtml+=inhtml[j];
 }

is only ran once since when it is first executed j == upperBound. To fix this try removing
  if(i>upperBound){
    upperBound = i;
  }

and whats the point of upperBound anyways it will always be equivalent to i so why not just use that.


text:
Q: Three.JS model viewer feasible in phonegap? I'm trying to make a very simple 3D model viewer in a phonegap app for use on an iPhone 4. I'm using three.js which is working fine when I make a simple website. The problem is that when I try it out on the phone the 3D object doesn't appear. Simple geometrical shapes like a cube and cylinder will load on the canvas but obj files won't.
I use an objLoader to bring in the .obj file and have all relevant files in the same directory in the app just in case. I think the problem might lie with using webGL on iOS but I'm not really sure.
Thanks very much for your help. If anyone has any suggestions for building a model viewer in phonegap for display in iOS I'd be delighted to hear them.

A: As very few mobile browsers support WebGL at the moment I opted to use the canvas to render the 3D models. I used a simple web 3D object viewer called JSC3D to create a model viewer in PhoneGap on iOS. It can use webGL but I just went with rendering using the 2D canvas.
I tested my app on an iPhone 4 and the result was that the model took between 2 and 5 seconds to load up and when you go to rotate the object it takes some time to redraw it depending on how complex it is. While not the most satisfactory result it did do the job. I'm going to try it out on a more advanced phone in Android and I'll let you know the result.

A: I suggest you try use XDK Intel if you are packaging for iphone but for android use AIDE Phonegap. Make sure you use only var renderer = new THREE.CanvasRenderer();and avoid using
Anything that has to do with WebGL for its not supported on most devices except BB Playbook and BB 10.

A: I think IOS render ability is better than Android, some scene renders well in IOS, but not in the Android.
Usually the movile have more render ability, than tha mobile app. I use the firefox to render the three.js obj demo, it works well. But when I use the webview in the app, it renders nothing.
I've make an Android app to render stl models. First when I use the mobile browser to render the scene, it not render the full scene, and when I remove the shadow  effect, it renders. Then I try to use webview with WebGlRenderer or CanvasRenderer, no works. Last I refer to the XWalkView of crosswalk a web engine which can used as an addin of the app, to replace the webview, I also close the shadow effect, I renders well.
You can refer this answer for more info.
Here is the render result.

A: You definitely should not use WebGL renderer of three.js as it's not supported on iOS. Try Canvas or SVG renderer.


text:
Q: Error in small sh script When I run program and I click on "Yes" throws an error:
/home/zygis/tools/script: 26: Syntax error: ")" unexpected (expecting ";;")

Code:
DIALOG=${DIALOG=dialog}

$DIALOG --title " My first dialog" --clear \
        --yesno "You really want to run this program?" 10 30

case $? in
  0)
    if [ "$1" = "start" ];
    then
            echo "Enter OS: ";
            read OS
            echo OS
            python /home/zygis/tools/dj.py $OS
    else
        if [ "$1" = "uprint" ];
        then
            echo "usage: {start}";
            echo "example: (./boot start)";
        else
            echo "Invalid choice";
            echo "To usage use uprint";
        fi
    fi
  1)
    echo "No chosen.";
  255)
    echo "ESC pressed.";
esac

A: Each case of your case/esac must be terminated by ;;.  See the man page...
case $? in
  0)
    if [ "$1" = "start" ];
    then
            echo "Enter OS: ";
            read OS
            echo OS
            python /home/zygis/tools/dj.py $OS
    else
        if [ "$1" = "uprint" ];
        then
            echo "usage: {start}";
            echo "example: (./boot start)";
        else
            echo "Invalid choice";
            echo "To usage use uprint";
        fi
    fi
    # Terminate.....
    ;;
  1)
    echo "No chosen.";
    # Terminate.....
    ;;
  255)
    echo "ESC pressed.";
    # Terminate.....
    ;;
esac

A: You have to use ";;" to end your cases.
case $? in
    0)
        echo "case 0";;
    1)
        echo "case 1";;
esac

A: Use two semicolon ;; to end each case i.e:
case ...
1) some_command ;;
2) other command ;;
esac


text:
Q: Did Harry's tea leaf prophecy come true? In their first divination class Ron, helped by Professor Trelawney, reads some interesting things about Harry via tea leaves. Was this a real prophecy of the future or simply some plot foreshadowing set up by JKR? Did all the events Ron/Trelawney state come true?

"My turn..." Ron peered into Harry's teacup, his forehead wrinkled with effort. "There's a blob a bit like a bowler hat," he said. "Maybe you're going to work for the Ministry of Magic... "But this way it looks more like an acorn.... (which means)"'A windfall, unexpected gold.' he turned the cup again, "that looks like an animal... yeah, if that was its head... it looks like a hippo... no, a sheep..."Professor Trelawney whirled around "Let me see that, my dear," she said reprovingly to Ron, sweeping over and snatching Harry's cup from him.Professor Trelawney was staring into the teacup, rotating it counterclockwise."The falcon... my dear, you have a deadly enemy." "The club... an attack. I thought that was a bowler hat," said Ron sheepishly."The skull... danger in your path,  gave the cup a final turn, gasped, and then screamed.There was another tinkle of breaking china; Neville had smashed his second cup"My dear," Professor Trelawney's huge eyes opened dramatically,"You have the Grim."

*

*Bowler hat

*Acorn

*hippo/sheep

*falcon

*club

*skull

*grim

A: You are misinterpreting Ron's assessment with what was actually there.
Notice - there isn't actually a bowler hat - Ron misread the club as being a bowler hat.
Trelawney sees four things: falcon, club, skull, grim
These four things directly foreshadow events in that particular book as well as the rest of the series.
Book 3 / Overall
Falcon: Petigrew / Voldemort
Club: Lupin-wolf / Death-eaters / Voldemort
Skull: Petigrew & Lupin-wolf / every situation ever, etc...
Grim: book 3 plot armor / death. Harry avoids death in this story but as is pointed out by @ibid, he does in fact meet this fate (in a way) eventually
And yes, Trelawney is not generally shown to be reliable, but this is due more to her characterization and less about the subject itself. "Fraud" may not be an appropriate term for her (especially if one considers someone like Lockhart). There were certainly teachers prior to Trelawney who were probably less....unique. Even if she is daft, the practice itself is generally accepted and we should accept her as an authority (even considering Dumbledore's generosity towards her).
Despite Hermione's feelings, it is not likely that Hogwarts would teach a subject that was entirely rubbish. Sybill is indeed shown to have had an ability to receive prophetic visions so, at least in her capabilities as a teacher and expert practitioner of interpreting what one can assume is a generally approved of form of witchcraft and wizardry (again, if not, it wouldn't be taught at all at a legitimate school), we should trust her interpretation over that of Ron.

A: I doubt that all of it was really intended as a real prophecy of the future or as any major plot foreshadowing.
That said, we can try to find various things in Harry's life that matches these predictions:
1 Harry ended up becoming the Head of the Department of Aurors.
2 Maybe the Triwizard Tournament winnings?
3 It's never said what a hippo or a sheep represents. (We can't just refer to real-life Tasseography as then the other things won't match up.)
4 Voldemort
5 & 6 These are about as vague as it gets. Harry was attacked and faced danger numerous times. You can really choose literally anything.
7 Harry technically dies towards the end of book 7


text:
Q: Probability: Characteristic function of random sum of i.i.d. rand var. If $N \in Fs(p)$ and $X_i \in Ge(\alpha)$ and we define $Y=\sum_{i=1}^N X_i$ then show that the distribution of $Y$ is $Ge(\beta)$.
Clearly the characteristic functions are required, as $\varphi_Y (t) = \varphi_N(\varphi_{X_i}(t))$
$\varphi_N (t)= \frac{p*\exp(i*t)}{1-(1-p)\exp(i*t)}: 0 \le p \le 1$
$\varphi_X (t)= \frac{\alpha}{1-(1-\alpha)\exp(i*t)}: 0 \le \alpha \le 1$
So I need to show that there is SOME $\beta$ such that
$\varphi_Y (t)= \frac{\beta}{1-(1-\beta)\exp(i*t)}: 0 \le \beta \le 1$
I'm getting stuck pretty early with the algebra....  maybe a hint would be greatly appreciated as I want to solve this myself.  Thank you all.

A:
You are confusing characteristic functions and generating functions.

If $Y=\sum\limits_{k=1}^NX_k$, as in your question, then $g_Y=g_N\circ g_X$ where, for every integer valued random variable $Z$ and every real number $s$ in $[0,1]$, $g_Z(s)=\mathbb E(s^Z)$.
Here, $g_N(s)=\dfrac{ps}{1-(1-p)s}$ and $g_X(s)=\dfrac{\alpha}{1-(1-\alpha)s}$ hence you should reach the result that $g_Y(s)=\dfrac{r}{1-(1-r)s}$ for some $r$ depending on $p$ and $\alpha$ whose value I will let you discover.


text:
Q: Angular App - Toggle Between Modes (Demo mode and App Mode)? I've been working on Angular application and I have a weird scenario that I'm trying to come-up with a solution for.
We have an application eg: test.com, that uses multiple restful API's (built by us). Our business wants us to capture dummy response of these rest APIs in a static json files and host those json files in a static folder in our codebase itself.
They want to toggle between application mode that uses real RestFul APIs and demo mode that uses the static json response objects.
test.com - triggers application that uses Restful APIs and test.com/demo triggers application that uses static JSON.
If /demo is not the solution, are there any other solutions.
How do I approach this scenario?
P.S - We don't want to manage 2 different code-bases!

A: Two things I can think of.
(1) Have an attribute on the logged in user that indicates if said user is a test user (user.test evaluates to true). When you log in as that user, you load the DEMO resources.
(2) If you want to stick with the URL condition, you could usethis.router.url === '/demo' as your check.
Personally, I prefer (1).


text:
Q: How can I clear the task of my App without calling startActivity() or finishAffinity() I have four Activities open A,B,C,D ("A" activity is not my launcher activity) and the app is in background (i.e. Home button pressed).
Now based on some GCM message received I need to finish all the activities or clear the task. So that next time when user open the app a completely new activity "E" gets open.
So neither 1> I can not do startActivity with CLEAR_TASK flag
nor 2> finishAffinity() as I will not have activity reference.
3> There is a solution to use BroadcastReceiver and finish the Activities manually but in some low configuration mobiles this solution is giving problem.
So is there any way to achieve this ?

A: When you are handling the notification you can kill the app by doing the following
android.os.Process.killProcess(android.os.Process.myPid())
The four components - Activity, Service, Content Provider, Broadcast Receiver runs in separate thread under one process. So when you will be requesting myPid() it will be giving the same id of the process which also has your activities !
I hope this solves your problem !


text:
Q: CMOS imager digital number versus reflectance
The image linked above is captured by a camera shooting in RAW mode using an RGB CMOS imager. The image contains four calibrated reflectance targets, of 5.2%, 9.4%, 23.1% and 52%, reflectance, respectively. What I believed I would see in the image is digital numbers in each color channel from that part of the image corresponding to each target that are proportional to reflectance, e.g. DN / reflectance basically a constant within the same color channel of the image. This is based on literature that says DN = kI + b, where I is incident energy, k is a scaling constant, and b is the noise equivalent exposure DN. In other words, twice as much reflectance is twice as many photons.
That is not what I see. For example, the average red channel DN values for each target are 152, 217, 504, and 844, respectively (all values on a 10 bit scale).
This is what I know:

*

*Gamma correction is turned off, so response should be linear.

*According to the imager documentation, my measured noise equivalent exposure of 53 is typical, and those values have been subtracted from all of the DNs above.

*All values taken from the same image and the same color channel from within that image.

*All four targets are operating in the "linear" range of the focal plane array, not yet saturated and beyond the noise-dominated floor.

I subsequently took a picture in RAW mode with a DSLR camera and obtained similar results, with DN values of 51, 84, 175, 242. I don't have knowledge about whether noise equivalent exposure has been subtracted here or not, but the results are close enough to the other imager that I've concluded that I'm not understanding something fundamental here.
My question is: why is the measured DN not proportional to the percentage reflectance in the calibrated reflectance targets?


text:
Q: Charge in the each capacitor when connected in parallel Consider a situation where we have three capacitors of  capacitances A, B and C connected in parallel to a battery of emf V. The equivalent capacitance of the combination would be A + B + C. The charge in the equivalent capacitor would therefore be V times A+B+C. Let's call it Q.
Is Q the sum of charges on all the three capacitors A, B and C or the charge in each capacitor?

A: Capacitors in parallel have the same voltage, since you know the following relation
$$Q=CV$$
One can write down $Q_{total}$ based on our initial statement aka $V_{total}=V$ where $V$ is the voltage through each capacitor
$$Q_{total} = C_{total}V_{total}= C_A V+C_B V+C_C V = V( C_A +C_B +C_C) $$
Where $C_i$ stands for different capacitance $i=A, B, C$. After simplifying the voltages you get the parallel capacitance relation as
$$C_{total}= C_A +C_B +C_C $$
For the total charge, check the equation before the last one

A: It is the sum of charge on all 3 capacitors. This is because the charge on a single ideal capacitor only depends on the voltage applied across it. When wired in parallel, each capacitor gets the same voltage. The charge on one of them is then independent of the others being present, so the total charge is $Q=V (A+B+C)$.


text:
Q: Getting
* value with ng-model below I have a selectable dropdown list. I need to pass the choosed value to ng-model directive:
ng-model="$root.specCategory_search"

But its not working in my example. How can I do it?
Previously I used it with select option and its working fine with ng-model directive. For that I used the value="" attribute within option tag.
HTML Dropdown

   <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
   Select One
   </button>

First item

Another item

This is a longer item that will not fit properly

CSS
.btn-input {
   display: block;
}

.btn-input .btn.form-control {
    text-align: left;
}

.btn-input .btn.form-control span:first-child {
   left: 10px;
   overflow: hidden;
   position: absolute;
   right: 25px;
}

.btn-input .btn.form-control .caret {
   margin-top: -1px;
   position: absolute;
   right: 10px;
   top: 50%;

JS
      $( document.body ).on( 'click', '.dropdown-menu li', function( event ) {

      var $target = $( event.currentTarget );

      $target.closest( '.btn-group' )
         .find( '[data-bind="label"]' ).text( $target.text() )
            .end()
         .children( '.dropdown-toggle' ).dropdown( 'toggle' );

      return false;

   });

A: The best solution in your case would be to create a directive that will attach the an event listener on click and extract the required value.
Then using the isolate scope you can bind the value of the dropdown and use it where you need it in your app.
Here is a starting point that you can further develop:

(function() {

  var app = angular.module('demoApp', []);

  app.directive('ddMenu', function() {
    return {
      restrict: 'A',
      scope: {
        ddMenu: '='
      },
      link: function(scope, element) {
        // set the initial value
        var $el = $(element);
        scope.ddMenu = $el.find('li:first').text();

        // listen for changes
        $el.on('click', 'li', function() {
          scope.ddMenu = $(this).text();
          scope.$apply();
        });
      }
    };
  });

})();

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

   <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
   Select One
   </button>

First item

Another item

This is a longer item that will not fit properly

  Val: {{ddValue}}


text:
Q: Unusual behavior with or operator in vimrc I usually do a search and replace in vim that looks like this:
:%s/\([\.!?]\|[\.!?]"\)\s\s/\1text /g

So it looks for either a period, exclamation point, question mark, or any of the above followed by a quote and two spaces.  It works fine.
But when I map this in my vimrc like so
map <F4> :%s/\([\.!?]\|[\.!?]"\)\s\s/\1text /g<CR>

and then press F4 I get this error message:
E486: Pattern not found: \([\.!?]|[\.!?]"\)\s\s

It is removing the backslash before the pipe for some reason and I have no idea why.  Does anyone know how to correct this behavior?

A: In a :mapping, the pipe character is special. Use <Bar> instead:
:noremap <F4> :%s/\([\.!?]\<Bar>[\.!?]"\)\s\s/\1text /g<CR>

Also, you should use :noremap; it makes the mapping immune to remapping and recursion.