text:
Q: rename files with list of special characters in python What's an efficient way to remove a list of special characters from a filename? I want to replace 'spaces' with '.' and '(', ')', '[',']' with '_'. I can do it for one, but I'm not sure how to rename multiple characters.
import os
import sys
files = os.listdir(os.getcwd())

for f in files:
    os.rename(f, f.replace(' ', '.'))

A: You could do a for loop that checks each character in the file name and replace:
import os
files = os.listdir(os.getcwd())
under_score = ['(',')','[',']'] #Anything to be replaced with '_' put in this list.
dot = [' '] #Anything to be replaced with '.' put in this list.

for f in files:
    copy_f = f
    for char in copy_f:
        if (char in dot): copy_f = copy_f.replace(char, '.')
        if (char in under_score): copy_f = copy_f.replace(char,'_')
    os.rename(f,copy_f)

The trick with this is the second for loop runs len(copy_f) times which will certainly replace all characters that match the criteria :)
Also, there was no need for this import:
import sys

A: This solution works; and if you're request for efficiency is to avoid O(n^2) behavior for time complexity, then this should be OK.
import os

files = os.listdir(os.getcwd())
use_dots = set([' '])
use_underbar = set([')', '(', '[', ']'])

for file in files:
    tmp = []
    for char in file:
        if char in use_dots:
            tmp.append('.')
        elif char in use_underbar: #You added an s here
            tmp.append('_')
        else:
            tmp.append(char)
    new_file_name = ''.join(tmp)
    os.rename(file, new_file_name)

You could increase the efficienty of this if you started using a bytearray; this would avoid the 'tmp' list, and creating a new string with the subsequent join on it.


text:
Q: elasticsearch azure repository verification exception I have installed repository-azure and configured elasticsearch with below settings:
path.data: /datadrive/elasticsearch/data
path.logs: /datadrive/elasticsearch/log
cloud:
    azure:
        storage:
            my_account:
                account: teststorage
                key: NtZQddasdasdasdsadsadfdsdsfsafsadasdyyP==

When I am trying to take a snapshot it's giving an error.
Request:
PUT _snapshot/es_snapshot
{
    "type": "azure"
}

Response:
{
  "error": {
    "root_cause": [
      {
    "type": "repository_verification_exception",
    "reason": "[es_snapshot] path  is not accessible on master node"
      }
    ],
    "type": "repository_verification_exception",
    "reason": "[es_snapshot] path  is not accessible on master node",
    "caused_by": {
      "type": "i_o_exception",
      "reason": "Can not write blob master.dat",
      "caused_by": {
    "type": "storage_exception",
    "reason": "The specified container does not exist."
      }
    }
  },
  "status": 500
}

A: Before taking a snapshot, you need to register the Azure repository with Elasticsearch.
Create a storage account in Azure and under that, create a Container BLOB and then register it to the repository es_snapshot as below:
PUT _snapshot/es_snapshot
{
    "type": "azure",
    "settings": {
      "container": "es_snapshot",
      "compress" : true
    }
}

Once the repository es_snapshot is registered, you can then take snapshots

A: "The specified container does not exist"
Error is clear - Create a container of name "es_snapshot" and the try

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mysql After Update/İnsert Triggers and 1442-Error I want to see new records and updates entered in the log table, I created a trigger for this but I get error 1442. Can you help me, please?
CREATE TRIGGER `trigger_changes`
    AFTER UPDATE ON `customers`
    FOR EACH ROW
    Update customers c INNER JOIN cust_changes ch ON ch.id = c.id SET ch.name = c.name

1442 - Can't update table 'cust_changes' in stored function/trigger because it is already used by statement which invoked this stored function/trigger

A: You have to reference the data in the trigger using the pseudo table name OLD or NEW.
Update cust_changes
SET name = NEW.name
WHERE id=NEW.id

A: If you use OLD.id (or NEW.id) in the updated statement then mysql (as @PeterHe) suggested is happy. If your model is different or you are doing something different then you need to tell us.
drop table if exists t,t1;
create table t(id int, name varchar(3));
create table t1(id int,name varchar(3));

insert into t values(1,null);
insert into t1 values(1,null);

CREATE TRIGGER t
    AFTER UPDATE ON t
    FOR EACH ROW
    Update t INNER JOIN t1  ON t1.id = old.id
        SET t1.name = t.name;

update t set name = ('aaa');

select * from t1;

+------+------+
| id   | name |
+------+------+
|    1 | aaa  |
+------+------+
1 row in set (0.00 sec)

As expected with no errors. Please add your versions for mysql and phpmyadmin.


text:
Q: Displaying returned array as radio buttons I'm trying to display a set of radio buttons (male or female) on my index page. Within my Form I build the form like this:
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
    ->add('gender', ChoiceType::class, array(
        'choices'  => array(
            'Male' => 1,
            'Female' => 2,
        )));
}

Then within the Controller:
public function indexAction(Request $request)
{
    $participantEntry = new Participants();

    $form = $this->createForm(ParticipantsType::class, $participantEntry,[
        'action' => $request->getUri()
    ]);

    $form->handleRequest($request);

    return $this->render('SurveyBundle:Page:index.html.twig',
        ['form' => $form->createView()]);

}

However, I'm not sure how to actually display as RadioButtons within my Twig file, this is what I've tried:
{% for g in form.gender %}
    {{ g.value }}
{%  endfor %}

BTW: The $gender within my Entity is an int
Which doesn't work, does anyone know what I am doing wrong?

A: Change the add into builder as follow
->add('gender', ChoiceType::class, array(
    'choices'  => array(
        'Male'   => 1,
        'Female' => 2,
    ),
    'expanded' => true,
    'multiple' => false
);

The combination of 'expanded' => true and 'multiple' => false will generate radio buttons, then in twig, just use
form_widget(form.gender)


text:
Q: How to add a class to first result of a foreach with a list? I'd like to add a class to the first result of a query inside a foreach and then echo the rest of the information.
I am using the following code to retrieve and show only the first result
foreach ($highlightedArticles as $data)
{
    $article_title      = $data['article_title'];
    $article_image      = $data['article_image'];

    echo '

            news

'.$article_title.'

    ';
}

The issue that I cannot resolve now is how to add the rest of the results(4 resulsts total with the class"first") since everything is inside an echo and I need to add the results that are in a
 .
This is what I would like to show..

'.$article_title.'

another result

another result

another result

A: is that what you are looking for?
$out= '

            news

';
foreach ($highlightedArticles as $data)

{

    $article_title      = $data['article_title'];
    $article_image      = $data['article_image'];

$out.= '

'.$article_title.'

';
}
$out.='

';
echo $out;

A: please modify your the code that you tried in following ways:
$firstLoop = true;
foreach( $network_value as $key => $value ){

   if( $firstLoop ){
       //do things on only the first loop
       $firstLoop = false;
       continue;
   }

   //do other things

}

edit
$out= '

        news

';
$firstloop=true;
foreach ($highlightedArticles as $data)

{

   $article_title      = $data['article_title'];
   $article_image      = $data['article_image'];
   if($firstloop){
     $out.= '

'.$article_title.'

';
    $firstloop = false;
    continue;
 }

 $out.= '

'.$article_title.'

';
}
$out.='

';
echo $out;

A: I would do it like this:

*

*Get the first item of the $highlightedArticles like this $highlightedArticles[0] and echo the image and the title.

*Then call array_slice($highlightedArticles, 1); which will return the $highlightedArticles except first element and then iterate and echo the returned items.

A:

        news

    <?php foreach ($highlightedArticles as $key => $data)
    {
        $article_title      = $data['article_title'];
        $article_image      = $data['article_image'];

        reset($highlightedArticles);

        printf('

%s

            ',
            $key === key($highlightedArticles) ? 'class="first"' : '',
            $article_image,
            $article_title
        );
    } ?>


text:
Q: How to set custom ringtone to contact in android Here is my code to update contact and set the custom ring tune it is running successfully but it is not working and I'm using API 9
        sound = new File(folder,SONG);
                ContentValues values = new ContentValues();
                values.put(MediaStore.MediaColumns.DATA, sound.getAbsolutePath());
                values.put(MediaStore.MediaColumns.TITLE, "1-800-hotlinebling");
                values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
                values.put(MediaStore.Audio.Media.ARTIST, "Umair Ali");
                values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
                values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
                values.put(MediaStore.Audio.Media.IS_ALARM, true);
                values.put(MediaStore.Audio.Media.IS_MUSIC, true);
                values.put(ContactsContract.Data.RAW_CONTACT_ID, contactID);
                values.putNull(ContactsContract.Data.CUSTOM_RINGTONE);
                Uri localUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, contactID);
                getContentResolver().update(localUri, values, null, null);

A: In StackOverflow similar issue Setting contact custom ringtone, how? you would find that answer

I found out how it works. Below you can see the fixed code code:
    Uri contactData = ContactsContract.Contacts.CONTENT_URI;      String contactId = contactData.getLastPathSegment();
          Cursor localCursor = managedQuery(contactData, PROJECTION, null, null, null);       localCursor.move(120/*CONTACT ID NUMBER*/);

  String str1 =
  localCursor.getString(localCursor.getColumnIndexOrThrow("_id"));
  String str2 =
  localCursor.getString(localCursor.getColumnIndexOrThrow("display_name"));
  Uri localUri =
  Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, str1);
  ContentValues localContentValues = new ContentValues();

  localContentValues.put(ContactsContract.Data.RAW_CONTACT_ID, contactId);
  localContentValues.put(ContactsContract.Data.CUSTOM_RINGTONE,
  f.getAbsolutePath()+"/Adventure.ogg");
  getContentResolver().update(localUri, localContentValues, null, null);
  Toast.makeText(this, "Ringtone assigned to: " + str2, 0).show();

Just change the contact id number to the id of the contact you want to
  change.

Hope it help


text:
Q: Spring cloud stream rabbitmq - consumer retries 3 times for all exception I am trying to stop the retires for my spring boot cloud application completely or retry for only specific exceptions
I have tried several ways to completely stop it from retrying 3 times I set the following configuration but even then it retires
spring.cloud.stream.bindings.input.consumer.max-attempts=1

spring.cloud.stream.rabbit.bindings.input.consumer.requeue-rejected=true

To retry for specific exceptions I used below code but didn't work out it still tries to retry for exceptions I don't want to
cloud:
      stream:
         rabbit:
            bindings:
               input:
                  consumer:
                     autoBindDlq: true
                     republishToDlq: true
                     prefix: local-
                     maxAttempts: 3
                     backOffInitialInterval: 1000
                     backOffMaxInterval: 10000
                     backOffMultiplier: 2.0
                     defaultRetryable: true
                     retryableExceptions:
                        com.ss.*: true
                        java.lang.*: false

Any idea on how to make it not retry or retry for specific exceptions


text:
Q: Is there a simple way to do bulk file text substitution in place? I've been trying to code a Perl script to substitute some text on all source files of my project. I'm in need of something like:
perl -p -i.bak -e "s/thisgoesout/thisgoesin/gi" *.{cs,aspx,ascx}

But that parses all the files of a directory recursively.
I just started a script:
use File::Find::Rule;
use strict;

my @files = (File::Find::Rule->file()->name('*.cs','*.aspx','*.ascx')->in('.'));

foreach my $f (@files){
    if ($f =~ s/thisgoesout/thisgoesin/gi) {
           # In-place file editing, or something like that
    }
}

But now I'm stuck. Is there a simple way to edit all files in place using Perl?
Please note that I don't need to keep a copy of every modified file; I'm have 'em all subversioned =)
Update: I tried this on Cygwin,
perl -p -i.bak -e "s/thisgoesout/thisgoesin/gi" {*,*/*,*/*/*}.{cs,aspx,ascx

But it looks like my arguments list exploded to the maximum size allowed. In fact, I'm getting very strange errors on Cygwin...

A: You may be interested in File::Transaction::Atomic or File::Transaction
The SYNOPSIS for F::T::A looks very similar with what you're trying to do:
  # In this example, we wish to replace
  # the word 'foo' with the word 'bar' in several files,
  # with no risk of ending up with the replacement done
  # in some files but not in others.

  use File::Transaction::Atomic;

  my $ft = File::Transaction::Atomic->new;

  eval {
      foreach my $file (@list_of_file_names) {
          $ft->linewise_rewrite($file, sub {
               s#\bfoo\b#bar#g;
          });
      }
  };

  if ($@) {
      $ft->revert;
      die "update aborted: $@";
  }
  else {
      $ft->commit;
  }

Couple that with the File::Find you've already written, and you should be good to go.

A: You can use Tie::File to scalably access large files and change them in place. See the manpage (man 3perl Tie::File).

A: Change
foreach my $f (@files){
    if ($f =~ s/thisgoesout/thisgoesin/gi) {
           #inplace file editing, or something like that
    }
}

To
foreach my $f (@files){
    open my $in, '<', $f;
    open my $out, '>', "$f.out";
    while (my $line = <$in>){
        chomp $line;
        $line =~ s/thisgoesout/thisgoesin/gi
        print $out "$line\n";
    }
}

This assumes that the pattern doesn't span multiple lines.  If the pattern might span lines, you'll need to slurp in the file contents.  ("slurp" is a pretty common Perl term).
The chomp isn't actually necessary, I've just been bitten by lines that weren't chomped one too many times (if you drop the chomp, change print $out "$line\n"; to print $out $line;).
Likewise, you can change open my $out, '>', "$f.out"; to open my $out, '>', undef; to open a temporary file and then copy that file back over the original when the substitution's done.  In fact, and especially if you slurp in the whole file, you can simply make the substitution in memory and then write over the original file.  But I've made enough mistakes doing that that I always write to a new file, and verify the contents.

Note, I originally had an if statement in that code.  That was most likely wrong.  That would have only copied over lines that matched the regular expression "thisgoesout" (replacing it with "thisgoesin" of course) while silently gobbling up the rest.

A: You could use find:
find . -name '*.{cs,aspx,ascx}' | xargs perl -p -i.bak -e "s/thisgoesout/thisgoesin/gi"

This will list all the filenames recursively, then xargs will read its stdin and run the remainder of the command line with the filenames appended on the end. One nice thing about xargs is it will run the command line more than once if the command line it builds gets too long to run in one go.
Note that I'm not sure whether find completely understands all the shell methods of selecting files, so if the above doesn't work then perhaps try:
find . | grep -E '(cs|aspx|ascx)$' | xargs ...

When using pipelines like this, I like to build up the command line and run each part individually before proceeding, to make sure each program is getting the input it wants. So you could run the part without xargs first to check it.
It just occurred to me that although you didn't say so, you're probably on Windows due to the file suffixes you're looking for. In that case, the above pipeline could be run using Cygwin. It's possible to write a Perl script to do the same thing, as you started to do, but you'll have to do the in-place editing yourself because you can't take advantage of the -i switch in that situation.

A: If you assign @ARGV before using *ARGV (aka the diamond <>), $^I/-i will work on those files instead of what was specified on the command line.
use File::Find::Rule;
use strict;

@ARGV = (File::Find::Rule->file()->name('*.cs', '*.aspx', '*.ascx')->in('.'));
$^I = '.bak';  # or set `-i` in the #! line or on the command-line

while (<>) {
    s/thisgoesout/thisgoesin/gi;
    print;
}

This should do exactly what you want.
If your pattern can span multiple lines, add in a undef $/; before the <> so that Perl operates on a whole file at a time instead of line-by-line.

A: Thanks to ephemient on this question and on this answer, I got this:
use File::Find::Rule;
use strict;

sub ReplaceText {
    my $regex = shift;
    my $replace = shift;

    @ARGV = (File::Find::Rule->file()->name('*.cs','*.aspx','*.ascx')->in('.'));
    $^I = '.bak';
    while (<>) {
        s/$regex/$replace->()/gie;
        print;
    }
}

ReplaceText qr/some(crazy)regexp/, sub { "some $1 text" };

Now I can even loop through a hash containing regexp=>subs entries!


text:
Q: Logic of binary search I read a Pseudo Code of binary search in a data structure book and then I started to writing code. the code that i written is :
#include <iostream.h>
#include <conio.h>
template <class T>

int BSearch(T x[], const int n, T item)
    {
    int loc, first = 0, found = 0, last = n-1;
        while(first <= last && !found)
        {
            loc = (first + last)/2;
            if(item < x[loc])
                last = loc - 1;
            else if(item > x[loc])
                first = loc + 1;
            else
                found = 1;
         }
      return found;
   }

int main()
    {
    const int n =5;
      int x[n],item;
      cout << "Pls enter " <<n<<" number(s): ";

      for(int i = 0; i < n;i++)
        cin >> x[i];
      cout << "Pls enter the item to Search: ";
        cin >> item;
      if(BSearch(x,n,item))
        cout << "\n\t Item Exist";
      else
        cout << "\n\t Item NOT Exist";

      getch();
      return 0;
   }

there is no any Error but a logic fault is there . it just return 0 value from BSearch function and i just get this message "Item NOT Exist". where is my bug ?! i didn't find it.
Thanks

A: The binary search only works for ordered lists. But you don't order the list you get from std::cin, therefore you get wrong results from your binary search.
To fix this you either have to restrict the input to pre-ordered lists, or you have to initially order your list before doing the binary search.

A: I tried your code out and it seems to work ok. You've got to remember that that the numbers you enter must be ordered from small to big.

A: Binary Search involves reducing the search range to half by dividing the range into half of its original size.  Binary Search operates upon sorted array.  It compares the element at the mid of this range with the value to be searched, if the value is smaller than the mid value, then the value is looked up in the range from first element to mid, otherwise the new search range becomes mid to last element.  This process continues until the required element is located or lower bound becomes greater than upper bound.  Efficiency of Binary Search is O(log2n) in average and worst case and is O(1) in best case.  The 'C' program to perform Binary Search is given below:
/* Binary Search */
#include <stdio.h>

#define MAX 10

int main(){
int arr[MAX],i,n,val;
int lb,ub,mid;
printf("nEnter total numbers?");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("nEnter number?");
scanf("%d",&arr[i]);
}
printf("nEnter the value to search?");
scanf("%d",&val);
lb=0;ub=n-1;
while(lb<=ub){
mid=(lb+ub)/2;
if(val<arr[mid])
ub = mid-1;
else if(val>arr[mid])
lb = mid+1;
else {
printf("nNumber found…!");
return;
}
}
printf("nNumber not found…!");
}


text:
Q: Get CDF of one variable conditional Probability Let $U\sim\text{Unif}[0,Z]$ and $Z\sim\text{Unif}[1,e^2]$.
I'm interested in the CDF of $U$.
From the above, we can write the densities:
$$f_{U\mid Z}(u\mid z)=\begin{cases}\frac{1}{z} &0\leq u\leq z\\0 & \text{otherwise}\end{cases}$$
From here, I tried to integrate to get the pdf of $U$, but am not confident in my work.
$$f_U(u) = \int_1^{e^2} f_{U\mid Z}(u\mid z) f_Z(z)\mathrm{d}z$$
I got $\frac{2}{e^2-1}$ from this integral.  Is this correct?
I also have the following notational question.
I've seen that $F(t) = P(U =< t) = \int P(U\leq t\mid Z = z)f(z)\mathrm dz$. I thought the notation $P(U\leq t\mid Z = z)$ was already the CDF, and am confused about this notation.  I'd appreciate if someone could clarify this for me.

A: Remember that
$$f_{U|Z}(u|z)=\frac {f_{U,Z}(u,z)}{f_Z(z)}$$
Which implies that $$f_{U,Z}(u,z)=f_{U|Z}(u|z)f_Z(z)=\frac 1z \frac {1}{e^2-1}$$
Coupled with $$\int f_{U,Z}(u,z) \mathrm{d}z=\int\frac 1z \frac {1}{e^2-1}\mathrm{d}z=f_U(u)$$
You have to split the integral in two as follows:

We know that $0\le u\le z$ and $1\le z\le e^2 \Rightarrow \max (u,1)\le z \le e^2$
From this we get two different bounds:
$$0 \le u\le 1 \quad \mathrm{and} \quad 1\le z\le e^2 $$
$$1 \le u\le z \quad \mathrm{and} \quad u\le z\le e^2 $$
And our integral becomes:
$$\int_1^{e^2}\frac 1z \frac {1}{e^2-1}\mathrm{d}z=\frac {2}{e^2-1} \quad 0\le u\le 1$$
And
$$\int_u^{e^2}\frac 1z \frac {1}{e^2-1}\mathrm{d}z=\frac {2-\ln u}{e^2-1} \quad 1\le u\le e^2$$
Which means that our PDF is defined as:
$$ f_U(u) = \frac {1}{{e^2-1}}
\cases{ 2 & if $\quad 0\le u\le 1$\cr
        2-\ln u & if $\quad 1\le u\le e^2$\cr}$$
So you were just off by the bounds of $u$.

With regards to your other question, $F_X(t)=\mathbb{P}(X<t)\ne \mathbb{P}(X<t|Z=z)$ the latter is conditional on $z$, and it is analogous to conditioning with discrete probabilities, where instead of integrating, you sum over all the partitions of the sample space, i.e.
$$\mathbb{P}(X=x)=\sum_i \mathbb{P}(X=x|Y=i)\mathbb{P}(Y=i)$$

A: Let's calculate the integral to check your work for the first part.
The densities $f_{U\mid Z}$ and $f_Z$ are correct.  So, we can write:
$$f_U(u) = \int_1^{e^2} f_{U\mid Z}(u\mid z)f_Z(z)\mathrm{d}z$$
just as you did.  Substituing in our densities, we get that:
$$f_U(u) = \int_1^{e^2}\frac{1}{z}\chi_{[0,z]}(u)\frac{1}{e^2-1}\mathrm{d}z$$
Here, I'm using a characteristic function $\chi_{[0,z]}(u)$. These are defined as:
$$\chi_{[0,z]}(u) = \begin{cases} 1 & u\in[0,z] \\ 0 & u\not\in[0,z]\end{cases}$$
Now, as $U\sim\text{Unif}(0,Z)$, we have that $u\in[0,z]$. So, the characteristic function is always $1$, and we get that:
$$f_U(u) = \int_1^{e^2} \frac{1}{e^2-1}\frac{1}{z}\mathrm{d}z = \frac{1}{e^2-1}\ln(e^2) = \frac{2}{e^2-1}$$
So, it seems like this is the right answer.
Regarding the integral of the CDF, it does show up, but not in the way you're stating it.  Suprisingly, the following identity holds:
$$E[X] = \int_0^\infty (1-F_X(t))\mathrm{d}t$$
Her,e $1-F_X(t)$ is known as the complementary cdf.
To see this, we can integrate by parts:
\begin{align*}
u & = 1-F_X(t),\quad \mathrm{d}v = \mathrm{d}t \\
\mathrm{d}u & = -f_X(t)\mathrm{d}t,\quad v = t \\
\int_0^\infty 1- F_X(t)\mathrm{d}t & =\left(t(1-F_X(t))\right|_0^\infty+\int_0^\infty tf_X(t)\mathrm{d}t
\end{align*}
On the left part, putting in $0$ clearly gives us $0$.
The infinite limit gives an indeterminate form, which seems to require a little work to justify, but as this isn't the main point of this post just assume it goes to $0$.
Then, we get that:
$$\int_0^\infty (1-F_X(t))\mathrm{d}t = E[X]$$
I haven't seen $\int_0^\infty F_X(t)\mathrm{d}t$, but there may be some usage for it.  You'd have to clarify your question to address it sufficiently.


text:
Q: Accessing child object in nested form during edit - rails 4 I'm sure this is simple but I can't seem to find a solution and I'm sure others will benefit from this question.
I have a nested form with:
has_many :children
accepts_nested_attributes_for :children

belongs_to :parent

I have a nested form setup as follows which is creating and editing parent and multiple children perfectly however to improve usability I want to access some variables in the child object during edit. I'm using a rails scaffold so this is the same form for both my new and edit actions.
<%= form_for(@parent, :html => {class: "form-horizontal"}) do |f| %>

  Parent form stuff here

  <%= f.fields_for :children, @parent.children do |c| %>

    Child form stuff here

    I WANT TO ACCESS CHILD OBJECT HERE DURING EDIT eg c.foo

  <% end %>

<% end %>

By this I want to access something like c.foo, child.foo or @parent.child.foo or similar.
It would also be great if I could access the index for the children as well.
Thanks in advance

A: In Rails form helpers, object is used to access the underlying object.
In your example, you should be able to access a child's foo variable within your fields_for block by calling c.object.foo.


text:
Q: Hyper-V 2019 Server network drivers What OS driver is used for Hyper-V 2019 server (host) network adapters?
Is it a Windows 2012 Server or Windows 10 driver?

A: Hyper-V 2019 Server drivers are Windows 10 based.
Be sure your PnP device ID is in the
[Intel.NTamd64.10.0]

section of the *.inf file to make it working under HV'19 Server
Could be ID is stated under
[Intel.NTamd64.10.0.1]

section. If so, just copy it down to the 10.0 section to enable driver for HV'19 Server.


text:
Q: Unable to Query XML file with OPENXML in SQL I am trying to query a good number of XML files using SQL Server 2014. I am using the below code and I am unsure what is wrong with the syntax because nothing is being returned. My suspicion is there is something strange with the XML file.
If put in only parts of the XML text directly into the query file instead of pointing to it locally then it seems to work but I have a lot of files and really need to be able to query from a local source without manual manipulation of the files.
Example XML: https://s3.amazonaws.com/irs-form-990/201600349349300510_public.xml
My code:
DECLARE @x xml
SELECT @x = R
FROM OPENROWSET (BULK 'C:\Users\USER\990\Example.xml', SINGLE_BLOB) AS     ReturnData(R)

SELECT @x

DECLARE @hdoc int

EXEC sp_xml_preparedocument @hdoc OUTPUT, @x

SELECT * FROM OPENXML (@hdoc, '/Return/ReturnData/IRS990ScheduleHIRS990ScheduleH/FinancialAssistanceAtCostTyp',3)
  WITH (FinancialAssistancePolicyInd  int   '../FinancialAssistancePolicyInd',
        FPGReferenceDiscountedCareInd int   '../FPGReferenceDiscountedCareInd',
        PersonsServedCnt int,
        NetCommunityBenefitExpnsAmt int)

EXEC sp_xml_removedocument @hdoc

Thanks in advance. IF there is a better way to do this then please do let me know, I am new to working with XML in SQL.

A: There are several flaws:

*

*FROM OPENXML is outdated and should not be used any more (rare exceptions exist)

*your XML included a default namespace, which must be declared

*your XPath is wrong: /Return/ReturnData/IRS990ScheduleHIRS990ScheduleH/ should be /Return/ReturnData/IRS990ScheduleH/
But anyway you shoudl turn to modern XQuerymethods. Try it like this:
--This will read the XML into a declared variable.
--attention Your XML is declared with utf-8, this might lead to problems with special characters...
DECLARE @x xml
SELECT @x = R
FROM OPENROWSET (BULK 'C:\Users\USER\990\Example.xml', SINGLE_BLOB) AS ReturnData(R);

--This is the query, first declare the namespace(s), than use .nodes() and .value():
WITH XMLNAMESPACES(DEFAULT 'http://www.irs.gov/efile'
                          ,'http://www.w3.org/2001/XMLSchema-instance' AS xsi)
SELECT ct.value('(FinancialAssistancePolicyInd)[1]','int') AS FinancialAssistancePolicyInd
      ,ct.value('(FPGReferenceDiscountedCareInd)[1]','int') AS FPGReferenceDiscountedCareInd
      ,ct.value('(FinancialAssistanceAtCostTyp/PersonsServedCnt)[1]','int') AS PersonsServedCnt
      ,ct.value('(FinancialAssistanceAtCostTyp/NetCommunityBenefitExpnsAmt)[1]','int') AS NetCommunityBenefitExpnsAmt
FROM @x.nodes('/Return/ReturnData/IRS990ScheduleH') AS A(ct)


text:
Q: Paragraph Styles Trying to set up a section mimicking U.S.C. format:  Question - Is there a way to set up personal paragraph styles. ie. paragraph section; paragraph subsection; clause, etc.  Indents are set at 2em each level (other than titles (not LaTex titles) and (not shown)..

Can one do something like: create a paragraph style
"\makeparagraphstyle{secheader}{
    \medskip
    \leftskip{0pt}}" [  Sec. 2. Definitions ]
"\makeparagraphstyle{sectext}{
    \medskip
    \leftskip{2em}}" [  In this Act... ]

clause etc..

\documentclass[a4paper,10pt]{book}
\usepackage{fancyhdr}

\usepackage{makeidx}

\begin{document}

\thispagestyle{empty}

\noindent
 \hrulefill
\begin{center}
\textbf{Department of Homeland Security Interoperable Communications Act}
\\(Public  Law 114-29)

This law has not been amended

 \hrulefill
\end{center}
\medskip
\textsc{\small {AN ACT To amend the Homeland Security Act of 2002 \index{Homeland Security Act of 2002}to require the Under Secretary for Management of the Department of Homeland Security to take administrative action to achieve and maintain interoperable communications capabilities among the components of the Department of Homeland Security, and for other purposes.}}
\medskip
\\
\textit{Be it enacted by the Senate and House of Representatives of the United States of America in Congress assembled, }
\medskip

\pagestyle{fancy}
\markright{Sec. 1\hfill DHS Interoperable Communications Act\hfill \thepage}

\medskip
\setlength{\leftskip}{0pt}}
\noindent
\textsc{\textbf{SECTION 1. Short Title.}}

\setlength{\leftskip}{0pt}}This Act may be cited as the ``Department of Homeland Security Interoperable Communications Act'' or the ``DHS Interoperable Communications Act''. \index{DHS Interoperable Communications Act} \index{Department of Homeland Security Interoperable Communications Act} \index{Interoperable Communications Act}

\pagestyle{fancy}
\markright{Sec. 2\hfill DHS Interoperable Communications Act\hfill \thepage}

\medskip
\setlength{\leftskip}{0pt}}
\noindent
\textsc{\textbf{Sec. 2. Definitions.}}

In this Act\textemdash

\setlength{\leftskip}{2em}(1) the term ``Department'' means the Department of Homeland Security; \index{Department of Homeland Security}

\setlength{\leftskip}{2em}(2) the term ``interoperable communications'' has the meaning given that term in section 701(d) of the Homeland Security Act of 2002, as added by section 3; and

\setlength{\leftskip}{2em}(3) the term ``Under Secretary for Management'' means the Under Secretary for Management of the Department of Homeland Security. \index{Department of Homeland Security!Under Secretary of Management}

\pagestyle{headings}
\markright{Sec. 3\hfill DHS Interoperable Communications Act\hfill \thepage}

\medskip
\setlength{\leftskip}{0pt}}
\noindent
\textsc{\textbf{Sec. 3.  Inclusion of Interoperable Communications Capabilities in Responsibilities of Under Secretary for Management.}}

\setlength{\leftskip}{2em}Section 701 of the Homeland Security Act of 2002 (6 U.S.C. 341) \index{6 U.S.C. ! 341} is amended\textemdash
\end{document}


text:
Q: How to get results in OPENJSON from whole json? I have a JSON structure which has several elements with their respective values.
Each element has method.mash_temp, ingredients.malt and ingredients.hops, all of which can has multiple values.
How would I query it so I get values from each element? (there's 25 elements, in this example is only 2 for simplification)
I use sql server 2019
P.S. I'm not even sure if I'm using "elements" in te correct context, but I think you'll get what I'm trying to do
DECLARE @json nvarchar(max) = '
 {
        "id": 1,
        "name": "Buzz",
        "tagline": "A Real Bitter Experience.",
        "first_brewed": "09/2007",
        "description": "A light, crisp and bitter IPA brewed with English and American hops. A small batch brewed only once.",
        "image_url": "https://images.punkapi.com/v2/keg.png",
        "abv": 4.5,
        "ibu": 60,
        "target_fg": 1010,
        "target_og": 1044,
        "ebc": 20,
        "srm": 10,
        "ph": 4.4,
        "attenuation_level": 75,
        "volume": {
            "value": 20,
            "unit": "litres"
        },
        "boil_volume": {
            "value": 25,
            "unit": "litres"
        },
        "method": {
            "mash_temp": [
                {
                    "temp": {
                        "value": 64,
                        "unit": "celsius"
                    },
                    "duration": 75
                }
            ],
            "fermentation": {
                "temp": {
                    "value": 19,
                    "unit": "celsius"
                }
            },
            "twist": null
        },
        "ingredients": {
            "malt": [
                {
                    "name": "Maris Otter Extra Pale",
                    "amount": {
                        "value": 3.3,
                        "unit": "kilograms"
                    }
                },
                {
                    "name": "Caramalt",
                    "amount": {
                        "value": 0.2,
                        "unit": "kilograms"
                    }
                },
                {
                    "name": "Munich",
                    "amount": {
                        "value": 0.4,
                        "unit": "kilograms"
                    }
                }
            ],
            "hops": [
                {
                    "name": "Fuggles",
                    "amount": {
                        "value": 25,
                        "unit": "grams"
                    },
                    "add": "start",
                    "attribute": "bitter"
                },
                {
                    "name": "First Gold",
                    "amount": {
                        "value": 25,
                        "unit": "grams"
                    },
                    "add": "start",
                    "attribute": "bitter"
                },
                {
                    "name": "Fuggles",
                    "amount": {
                        "value": 37.5,
                        "unit": "grams"
                    },
                    "add": "middle",
                    "attribute": "flavour"
                },
                {
                    "name": "First Gold",
                    "amount": {
                        "value": 37.5,
                        "unit": "grams"
                    },
                    "add": "middle",
                    "attribute": "flavour"
                },
                {
                    "name": "Cascade",
                    "amount": {
                        "value": 37.5,
                        "unit": "grams"
                    },
                    "add": "end",
                    "attribute": "flavour"
                }
            ],
         }
},
{
        "id": 2,
        "name": "Trashy Blonde",
        "tagline": "You Know You Shouldnt",
        "first_brewed": "04/2008",
        "description": "A titillating, neurotic, peroxide punk of a Pale Ale. Combining attitude, style, substance, and a little bit of low self esteem for good measure; what would your mother say? The seductive lure of the sassy passion fruit hop proves too much to resist. All that is even before we get onto the fact that there are no additives, preservatives, pasteurization or strings attached. All wrapped up with the customary BrewDog bite and imaginative twist.",
        "image_url": "https://images.punkapi.com/v2/2.png",
        "abv": 4.1,
        "ibu": 41.5,
        "target_fg": 1010,
        "target_og": 1041.7,
        "ebc": 15,
        "srm": 15,
        "ph": 4.4,
        "attenuation_level": 76,
        "volume": {
            "value": 20,
            "unit": "litres"
        },
        "boil_volume": {
            "value": 25,
            "unit": "litres"
        },
        "method": {
            "mash_temp": [
                {
                    "temp": {
                        "value": 69,
                        "unit": "celsius"
                    },
                    "duration": null
                }
            ],
            "fermentation": {
                "temp": {
                    "value": 18,
                    "unit": "celsius"
                }
            },
            "twist": null
        },
        "ingredients": {
            "malt": [
                {
                    "name": "Maris Otter Extra Pale",
                    "amount": {
                        "value": 3.25,
                        "unit": "kilograms"
                    }
                },
                {
                    "name": "Caramalt",
                    "amount": {
                        "value": 0.2,
                        "unit": "kilograms"
                    }
                },
                {
                    "name": "Munich",
                    "amount": {
                        "value": 0.4,
                        "unit": "kilograms"
                    }
                }
            ],
            "hops": [
                {
                    "name": "Amarillo",
                    "amount": {
                        "value": 13.8,
                        "unit": "grams"
                    },
                    "add": "start",
                    "attribute": "bitter"
                },
                {
                    "name": "Simcoe",
                    "amount": {
                        "value": 13.8,
                        "unit": "grams"
                    },
                    "add": "start",
                    "attribute": "bitter"
                },
                {
                    "name": "Amarillo",
                    "amount": {
                        "value": 26.3,
                        "unit": "grams"
                    },
                    "add": "end",
                    "attribute": "flavour"
                },
                {
                    "name": "Motueka",
                    "amount": {
                        "value": 18.8,
                        "unit": "grams"
                    },
                    "add": "end",
                    "attribute": "flavour"
                }
            ],
            "yeast": "Wyeast 1056 - American Ale™"
        },
        "food_pairing": [
            "Fresh crab with lemon",
            "Garlic butter dipping sauce",
            "Goats cheese salad",
            "Creamy lemon bar doused in powdered sugar"
        ],
        "brewers_tips": "Be careful not to collect too much wort from the mash. Once the sugars are all washed out there are some very unpleasant grainy tasting compounds that can be extracted into the wort.",
        "contributed_by": "Sam Mason <samjbmason>"
}';

Here's a query for ingredients.malt which works, but only gets data from the first element, how would I query it so I get all data?
SELECT name, amount_value, amount_unit
FROM OPENJSON(@json, '$.ingredients.malt')
WITH (
    name nvarchar(30) '$.name'
    , amount nvarchar(max) '$.amount' as JSON
)
CROSS APPLY OPENJSON(amount, '$')
WITH (
  amount_value varchar(5) '$.value'
  , amount_unit nvarchar(50) '$.unit'
)
;

A: Opening the JSON on a higher level than the path $.ingredients.malt, will return other categories besides malt.
You can use the json_value() function to fetch values from a JSON string.
select  category.[key] as CategoryName,
        json_value(ingredient.[value], '$.name') as IngredientName,
        json_value(ingredient.[value], '$.amount.value') as IngredientAmount,
        json_value(ingredient.[value], '$.amount.unit') as IngredientUnit
from openjson(@json, '$.ingredients') category
cross apply openjson(category.[value], '$') ingredient

This gives me
CategoryName  IngredientName          IngredientAmount  IngredientUnit
------------  ----------------------  ----------------  --------------
malt          Maris Otter Extra Pale  3.3               kilograms
malt          Caramalt                0.2               kilograms
malt          Munich                  0.4               kilograms
hops          Fuggles                 25                grams
hops          First Gold              25                grams
hops          Fuggles                 37.5              grams
hops          First Gold              37.5              grams
hops          Cascade                 37.5              grams

To get the data from the second object in the JSON ("id": 2), the invalid JSON from the question must be corrected to be valid first. It is missing the square array brackets [].
This turns the invalid JSON
{
  "id": 1,
  ...
},
{
  "id": 2,
  ...
}

into a valid JSON
[
  {
    "id": 1,
    ...
  },
  {
    "id": 2,
    ...
  }
]

To parse the malt data from all objects, you can then use the query below:
select  json_value(item.[value], '$.name') as ItemName,
        json_value(ingredient.[value], '$.name') as MaltName,
        json_value(ingredient.[value], '$.amount.value') as MaltAmount,
        json_value(ingredient.[value], '$.amount.unit') as MaltUnit
from openjson(@json2, '$') item
cross apply openjson(item.[value], '$.ingredients.malt') ingredient;

Resulting in
ItemName       MaltName                MaltAmount  MaltUnit
-------------  ----------------------  ----------  ---------
Buzz           Maris Otter Extra Pale  3.3         kilograms
Buzz           Caramalt                0.2         kilograms
Buzz           Munich                  0.4         kilograms
Trashy Blonde  Maris Otter Extra Pale  3.25        kilograms
Trashy Blonde  Caramalt                0.2         kilograms
Trashy Blonde  Munich                  0.4         kilograms


text:
Q: Get name from snd_kcontrol - Linux kernel sound driver I declare something like this:
SOC_SINGLE_EXT("EXAMPLE_NAME", SND_SOC_NOPM, 0, 1, 0,
example_get, example_put),

with:
static int example_get(struct snd_kcontrol *kcontrol,
               struct snd_ctl_elem_value *ucontrol)
{
     struct snd_soc_component *component = snd_soc_kcontrol_component(kcontrol);
     struct struct_priv *my_struct = snd_soc_component_get_drvdata(component);

     return 0;
}

How do I fetch the name EXAMPLE_NAME in example_get? I looked through the snd_kcontrol struct and the snd_soc_component one too, but snd_kcontrol doesn't seem to have a name and snd_soc_component->name isn't what I want.
Anyone idea?

A: Answering my own question since I figured out the answer and thought it might be useful to others.
Using kcontrol->id.name is what I needed. This returns EXAMPLE_NAME in my example case, which is what I was looking for.


text:
Q: Check with JavaScript that JSEcoin mining is online or not? I embedded JSECoin's browser mining script to my website. It's a javascript based cryptocurrency miner script, that runs only on 100%, if the browser tab is in focus, and it doesn't eats the CPU, so it's much friendlier than other scripts.
At the first visit, the script shows a popup, that tells: mining is running on this site. Here is the first place, where you can deny it.
The second option to deny the mining is that you install an adblocker plugin to your browser.
When I can't (or don't want to) check both, there is only one option left: checking, that the mining is currently running or not? The script is sending messages to the console, eg:

*

*(index):1 Loaded
https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js

*(index):1 JSE Socket Connected!

*(index):1 JSE Data Received (500hps): [...hash...]

Is it possible to check, that the mining is running or not? I can't understand the JS code well.
There is a site for sample mining:
https://developer.jsecoin.com/API/#MinerCode
And a site to check it, with adblock solution:
https://jsecoin.com/misc/adblocker/demo.html
Thanks a lot!
I asked for it on the official FB page, but nothing answer. :/
<script>
  !function(){
    var e=document,
      t=e.createElement("script"),
      s=e.getElementsByTagName("script")[0];

    t.type="text/javascript",
    t.async=t.defer=!0,
    t.src="https://load.jsecoin.com/load/2895/jsecoin.com/optionalSubID/0/",
    s.parentNode.insertBefore(t,s)
  }();
</script>


text:
Q: Running total per account per month I have created the following table:
create table AccountBalances (
    Year varchar(255),
    Period varchar(255),
    Account numeric,
    Amount numeric
)

Insert into AccountBalances(Year, Period, Account, Amount)
    Values ('2014', '1', '1210', '100'),
           ('2014', '1', '1210', '200'),
           ('2014', '3', '1210', '100')

Now I want to calculate the running total for each period per account. However may main issue is calculating running totals for periods without transactions. I want my result like this:
Year     Period     Account     Amount
2014        1         1210        300
2014        2         1210        300
2014        3         1210        400

From the transaction table period 2 is not present, but I want to calculate the running total for this period in my running total table.

A: From SQL Server 2012 onwards you can do this
SELECT
    *,
    SUM(Amount) OVER (PARTITION BY Year, Account ORDER BY Period RANGE UNBOUNDED PRECEDING)
FROM
    AccountBalances

A: A system-neutral (works on all database systems and versions) and widely used approach to problems like this, is to maintain a Date table containing one row for every day of every year that your application or analysis is interested in.
I believe some database systems can generate something like this on-the-fly, but a stored table takes up very minimal space (365 or 366 rows per year - nothing to a relational database) and can be used in a huge variety of situations. Populate it once for a long number of years into the future and it will serve you well.
For your particular case, you'd want this Date table to include both Year and Period columns: you need to determine how periods are defined, e.g. is that the same as a month or something else like 4-week chunks of time?
Then you can do a query along these lines (please treat as pseudocode - your exact requirements may vary):
with cteAllPeriods as (
    select      distinct
                Year
                ,Period
    from        Date
    where       Year >= 2014    -- Whatever suitable restrictions here
    )
select      D.Year
            ,D.Period
            ,AB.Account
            ,sum(AB.Amount)
from        cteAllPeriods   D
                                -- Assuming this is a running total
                                -- from the start of the calendar year
left join   AccountBalances AB  on D.Year=AB.Year
                                and D.Period>=AB.Period -- Gets everything UP TO the current period

group by    D.Year
            ,D.Period
            ,AB.Account

A: Another approach would be to use a separate Period_lookup table having all possible periods (Months) for a year.
Then we could do an outer join and apply the IsNull / Coalesce function in the select to return the desired results.


text:
Q: Issue with Implementing callback in node.js code I have this node.js function process() which is supposed to return a value when called. I am facing issue with creating a callback for my process(). The value should return from process() only after it gets response back from  ec2.runInstances(params, function(err, data) call.
------------- Snippet from app.js (express.js)--------------------
var createEngine = require('./ec2_create.js');
app.get('/create', function (req, res) {
    res.render('create', {
        status: createEngine.process()
    });

});

------------------------Code snippet from ec2_create.js -----------------------
function process(callback) {

    var status = null;
    // Create the instance
    ec2.runInstances(params, function (err, data) {
        if (err) {
            //console.log("Could not create instance", err);
            status = "Could not create instance: " + err;
        } else {
            var instanceId = data.Instances[0].InstanceId;
            //console.log("Created instance", instanceId);
            status = "Created instance: " + instanceId;
        }

    });
    callback(status);
};

module.exports.process = process;

A: Try as follows
function ec2process(callback){

var status = null;
// Create the instance
ec2.runInstances(params, function(err, data) {
if (err) {
    //console.log("Could not create instance", err);
    status = "Could not create instance: " + err;
    }
else{
    var instanceId = data.Instances[0].InstanceId;
    //console.log("Created instance", instanceId);
    status = "Created instance: " + instanceId;
  }
callback(status); // Callback moved

});

};

exports.
process = ec2process

A: since your process method expects a callback function and does not return a value, you could call it rather like this:
app.get('/create', function (req, res) {
    createEngine.process(function(status){
        //you're inside the callback and therefor have the status value
        res.render('create', {
            status: status
        });
    }):
});

A: You should move the code which calls the callback into the callback for runInstances:
function process(callback) {

  var status = null;
  // Create the instance
  ec2.runInstances(params, function (err, data) {
    if (err) {
        //console.log("Could not create instance", err);
        status = "Could not create instance: " + err;
    } else {
        var instanceId = data.Instances[0].InstanceId;
        //console.log("Created instance", instanceId);
        status = "Created instance: " + instanceId;
    }
    callback(status);
  });

};


text:
Q: Mostrar todas las tablas en filas a columnas Quiero hacer un vacuum full a todas las tablas de un esquema, tengo este query que me muestra todas las tablas:
SELECT 'vacuum full '
       || table_name
       || ';'
FROM   information_schema.tables
WHERE  table_schema = 'public'
ORDER  BY table_schema,
          table_name;

Me da como resultado lo siguiente:

Y lo que realmente me gustaría que me diera sería algo así:
vacuum full tabla1, tabla2, tabla3, tabla4;
¿Alguna sugerencia?
Gracias de antemano

A: Hola podría usara la función STRING_AGG()

https://www.postgresqltutorial.com/postgresql-aggregate-functions/postgresql-string_agg-function/

En su caso quiere agrupar las tablas por esquema.
Una posible solución seria así:
SELECT table_schema , 'vacuum full ' || string_agg(table_name, '; ') as "names_table"
FROM   information_schema.tables
WHERE  table_schema = 'public'
group by (table_schema);


text:
Q: Import Outlook User-Defined Field to Excel with VBA I would like to import mail data from Outlook.
I have no problem to import classic fields such as: From, Subject ... etc. I cannot find how to import my "User-defined field".
The User-defined field is named "DemandQTY" and contains only numbers.
I get my data from a shared mailbox.
Sub GetFromOutlook()

Dim OutApp As Outlook.Application
Dim OutNS As Namespace
Dim Folder As MAPIFolder
Dim OutMail As Variant
Dim i As Integer
Dim objOwner As Outlook.Recipient
Dim FileName As String
Dim MI As Outlook.MailItem
Dim Item As Object
Dim Atmt As Attachment

Set OutNS = GetNamespace("MAPI")
Set OutApp = New Outlook.Application
Set objOwner = OutNS.CreateRecipient("emailadress")
objOwner.Resolve

If objOwner.Resolved Then
    Set Folder = OutNS.GetSharedDefaultFolder(objOwner, olFolderInbox)

    i=2
    For Each OutMail In Folder.Items
        Sheets(2).Cells(i, 1) = OutMail.EntryID
        ' (etc....)
        Sheets(2).Cells(i, 32) = OutMail.ReminderTime
        i = i + 1
    Next OutMail
    MsgBox "Importation Terminée"
    Sheets(2).Select
    Sheets(2).Cells(1, 1).Select
    Set OutApp = Nothing
    Set OutNS = Nothing
    Set Folder = Nothing
End If
End Sub

I tried different methods found on internet, but nothing worked.

A: We can do this by first testing if the property exists.  If it doesn't and you try to work with it, it will throw an error. Afterwards we can access the value if the property is found.
For Each OutMail In Folder.Items

        Sheets(2).Cells(i, 1) = OutMail.EntryID
       (etc....)
        Sheets(2).Cells(i, 32) = OutMail.ReminderTime

        If Not(OutMail.UserProperties.Find("DemandQTY", True) Is Nothing) Then
            Sheets(2).Cells(i, 33) = OutMail.UserProperties("DemandQTY").Value
        End If

        i = i + 1
Next OutMail


text:
Q: Sequencal Workflow Designer I am looking for some kind of a workflow editor for WF, has anyone seen anything like this?
I would like to be able to edit XML files, but then have those XML files be opened by my app.
Maybe a different approach is ok too!
Bill.

A: One way would be to rehost the WF4 designer in your app, similar to the one that is available in Visual Studio. Its also possible to host it on Internet Explorer as an XBAP application.
As for manipulating the XAML XML file(s) containing your workflow structure, the easiest way would be to create your activities via code and serialize them down (and up) using the ActivityXamlServices type. See here for more info on this.


text:
Q: Derivation of properties of Regular open sets. I've been stuck on this question for quite a while and I would appreciate if someone could help me out.
A is regular open iff $A=A^{{\bot\bot}}$ where $A^{\bot}$ = X - $\overline{A}$.
$A^{\bot} = int(A^{c})$ and $A^{{\bot\bot}} = A = X - \overline{int(A^{c})}$
I don't know how to continue from here, in particular how does this imply A is regular open .

A: Suppose that $A$ is a regular set, let's show that $A^{\bot\bot}=A$.
$ A\subset \bar A$ implies that $X-\bar A\subset X-A$ since $A$ is open, $X-A$ is closed, we deduce that $\overline{X-\bar A}\subset X-A$. Let $x\in X-A$, suppose that $x$ is not in $\overline{X-\bar A}$, this implies that $x$ is in $int(\bar A)=A$ since $A$ is regular contradiction. We deduce that $X-A=\overline{X-\bar A}$. This is equivalent to saying that $A=X-(X-A)=X-\overline{X-\bar A}=A^{\bot\bot}$.
Conversely, suppose that $A^{\bot\bot}=A$, $X-\overline{X-\bar A}=A$ this implies that $X-A=\overline{X-\bar A}$, $A\subset \bar A$ implies that $int(A)\subset in(\bar A)$, we have to show that $int(\bar A)\subset A$. Let $x\in int(\bar A)$, if $x$ is not in $A$, $x\in X-A=\overline{X-\bar A}$. This implies that the intersection of every open subset containing $x$ and $X-\bar A$ is not empty, in particular $int(\bar A)\cap (X-\bar A)$ is not empty. Contradiction.


text:
Q: PHP datetime operations from string format I have several shops in my system. Now i online want to show shops that are open or will open if the nowtime is before the closing time. the time strings I use are 24 hour format like "01:00" and "23:22" I came up with a code like this:
    public function willOpen($open, $closed, $nowTime) {
    $open = str_replace(":", "", $open);
    $closed = str_replace(":", "", $closed);
    $nowTime = str_replace(":", "", $nowTime);
    if ($open >= $nowTime) {
        if ($closed <= $nowTime) {
            return false;
        } else {
            return true;
        }
    }
    return false;
}

But this does not seem right because if the close time is for ex. 01:00 and the current time is 9:00 and the shop will open for ex 11:00 then this code will return false because the close time is smaler then the now time.....
what is the best approach do to this ?

A: I would cast all of the dates to unix time and compare from that. It's much more accurate and designed for this sort of thing. date("U") is the unix time since epoc (and is an integer), so comparing > and < on it is a breeze.
$open = date("U",strtotime($open));
$closed = date("U",strtotime($closed));
$nowTime = date("U");
if ($open >= $nowTime) {
 if ($closed <= $nowTime) {
  return false;
 }
 else {
  return true;
 }
}
return false;

A: The best way to go is using DateTime classes, as time operations is supported. So it's would be something like this:
function willOpen(Datetime $open, Datetime $closed)
{
    $nowTime = new DateTime(); # defaults to now

    // if ($nowTime > $closed) ...
}

$open   = Datetime::createFromFormat('H:i', '01:00');
$closed = Datetime::createFromFormat('H:i', '09:00');

If closed is the next day so you could a bit like:
$closed->add(new DateInterval('P1DT12H')); # 1 day + 12 hours


text:
Q: Create Customer Refund from a Return Authorization How can I create a Customer Refund record from the Return Authorization form?
I'd like to intercept the action associated with the Refund button on the Return Authorization form, but I'm not sure how to do that.
Short of that I've tried adding a "Customer Refund" button onto the Return Authorization from using a Workflow. That doesn't seem to work, I can never get the button to show on the form. I've added a single "State 1" to the workflow with an Add Button with a label of "Customer Refund" that triggers on "Before Record Load". So far the button never shows up on the form.

A: Copied from original comment: I think that is controlled by the "Custom Form" selection. I believe by default, there are two standard forms for a Return Authorization: Standard Return Authorization - Cash and Standard Return Authorization - Credit. The form you select determines the workflow for refunding. Try switching the Custom Form to the Credit version


text:
Q: Counting lattice polytopes by volume For any $n \in \mathbb{N}$ and $B \in \mathbb{R}_{\geq 0}$, let $\mathcal{P}(n,B)$ be the set of $n$-dimensional convex polytopes $\Delta \subseteq \mathbb{R}^n$, taken up to integral, unimodular affine transformations, whose vertices lie in $\mathbb{Z}^n$ and whose Lebesgue volume is bounded above by $B$.
It is not difficult to see that the set $\mathcal{P}(n,B)$ is finite.
Is there any known asymptotics for the cardinality of $\mathcal{P}(n,B)$ as $n \to +\infty$ and/or $B \to +\infty$?
Do these asymptotics get more pleasing if we consider the cardinality of $\mathcal{P}\left(n,\frac{B}{n!}\right)$, i.e. if we consider the integral volume of polytopes instead of the Lebesgue one?
Are these asymptotics related to the number of simplices with which one can triangulate $\Delta \in \mathcal{P}(n,B)$?
I could not find anything in the literature, but I am not an expert in convex geometry or combinatorics, so I unfortunately do not know the literature very well.
Thank you very much!


text:
Q: Python: Assign multiple system arguments in one simple line I've tried to find an answer to this, but nothing seems to fit the problem...
I want to in one simple line assign a sys.argv to a variable, in one simple line instead of doing the following:
var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]
var4 = sys.argv[4]
var5 = sys.argv[5]
var6 = sys.argv[6]
etc...

is this possible?
Cheers,
MHibbin

A: Yep:
var1,var2,var3,var4 = sys.argv[1:5]

This will only work if the iterable on the right side has 4 elements.  Python3.x extends this capability a bit:
var1,var2,var3,var4,*rest = sys.argv[1:]

In this variation, you unpack the first 4 elements of sys.argv[1:] into variables and the rest of sys.argv gets put into the list rest.
For commandline parsing, I would definitely recommend argparse.  It ships with python2.7, and can easily be installed for older versions of python.

A: You can use this syntax:
var1, var2, var3 = sys.argv[1:]

Note that the number of variables must match the length of the list. Usually, it's better to use the getopt module.


text:
Q: How do you calculate and angle using Math.asin()? I'm trying to create a triangle calculator to practice my JavaScript Math functions and i hit a roadblock. Using Math.asin(opp/hyp) gives me a number between 0-1, so how would i calculate B with the opposite and hypotenuse?
if(((opp!=""||opp!=0)&&(hyp!=""||hyp!="0"))&&((A=="0"||A=="")&&(B=="0"||B==""))){
    var sin = Math.asin(opp/hyp)
    document.getElementById("B").value=(sin)
}

I would be grateful for alternative solutions and fixes to my issue as i'm not very experienced in the area

A: Math.asin gives you an angle in radians.
1rad × 180/π = 57.296° (just multiply by 180 and divide by Math.PI)


text:
Q: Como pegar valores de um ou mais inputs Estou começando a programar com JavaScript e estou com dúvida se consigo pegar os 3 valores do input.
O resultado sempre vem Not A Number (NAN)

function media(){
    var a = parseInt(document.getElementById('valor1'));
    var b = parseInt(document.getElementById('valor2'));
    var c = parseInt(document.getElementById('valor3'));

    var resultado = (a + b + c) / 3;

    alert("A média é : " + resultado);
}
        form {
        /* Apenas para centralizar o form na página */
        margin: 0 auto;
        width: 400px;
        /* Para ver as bordas do formulário */
        padding: 1em;
        border: 1px solid #CCC;
        border-radius: 1em;
        }
         label {
        /*Para ter certeza que todas as labels tem o mesmo tamanho e estão propriamente alinhadas */
        display: inline-block;
        text-align: right;
        }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <title>Média</title>

    <form>

Cálculo Média

            Valor 1
            <input type="text" id="valor1" class="form-control col-6">

            Valor 2
            <input type="text" id="valor2" class="form-control col-6">

                Valor 3
                <input type="text" id="valor3" class="form-control col-6">

            <button type="submit" class="btn btn-primary ml-5 my-3" onclick="media()">Calcular</button>
    </form>

A: Você precisa colocar o value para pegar o valor do input:
var a = parseInt(document.getElementById('valor1').value);
var b = parseInt(document.getElementById('valor2').value);
var c = parseInt(document.getElementById('valor3').value);


text:
Q: MySQL : compare string with the result of a query Is it possible to compare the result of a query to a string in MySQL? Something like :
select case when 'Captain' = (select role from roleassociation ra
inner join users urs
on ra.userentityid = urs.invuserid
where invuserid = 007)
        then 'true' else 'false' end as result;

The above query is incorrect, but is it possible to implement? Thanks in advance.

A: I would probably just put the CASE expression in the subquery:
SELECT
    CASE WHEN role = 'Captain' THEN 'true' ELSE 'result' END AS result
FROM roleassociation ra
INNER JOIN users urs
    ON ra.userentityid = urs.invuserid
WHERE
    invuserid = 007;

Assuming you expect the result to be only a single record, you will still have just a single result with this approach.


text:
Q: member login and read own notes I have created a website where the user can become register and log in with their username / password when they log in, they can create his own notes + (here's my problem started> it must also be an option where they can read or see his own notes for ex on a second page.
I confused, maybe you guys can help me and I try also with different SQL statements and different Inner Join but,nothing happens on that page,where users can see his own notes after they finished with create his own notes.
My DB looks like this. 2 table. tblUser (fldID, fldusername, fldpassword) and tblNote (fldID, fldnotes)
My Code-behind and SQL statements look like this:
    Code-behind: Createnotes.aspx

    protected void btnCreate_Click(object sender, EventArgs e)
    getContent objNote = new getContent();
    objNote._Note = txtText.Text;
    objNote._IDnote = Convert.ToInt32(Session["UserId"]);
    objNote.AddNotes();

    litSvar.Text = "You have now create a Notes";
    Response.AddHeader("Refresh", "5; URL=Createnote.aspx");
}

    SQL statement :
    public void AddNotes()
{
    string strSQL = "INSERT INTO tblNote (fldnote) VALUES(@Note)";
    SqlCommand CMD = new SqlCommand(strSQL);
    CMD.Parameters.AddWithValue("@Note", _Note);
    CMD.Parameters.AddWithValue("@IDnote", _IDnote);

    objData.ModifyData(CMD);
}
 ................

    Code-behind: Usernotes.aspx
    if (Session["UserId"] != null)
    {
        objdinnote._IDnote = Convert.ToInt32(Session["UserId"]);
        DataTable dtnotes =    objdinnote.getNotesbyID(Convert.ToInt32(Request.QueryString["id"]));
        foreach (DataRow notes in dtnotes.Rows)
        {
            litSvar.Text += notes["fldnote"];
        }
       }

    SQL statement:
     public DataTable getNotesbyID(int _Id)
     {
    string strSQL = ("select tblLogin.*, tblNote.fldnote from tblLogin INNER  JOIN tblNote ON tblLogin.fldID = tblNote.fldIDnote where tblLogin.fldID = @ID");
    SqlCommand CMD = new SqlCommand(strSQL);
    CMD.Parameters.AddWithValue("@ID", _Id);
    return objData.GetData(CMD);
    }

A: You don't need to join it with login if you know the field you can directly pass it to tblnote and get related notes
select fldnote from tblNote where  fldID= @ID


text:
Q: Remove words with spaces I want to find all the "phrases" in a list in remove them from the list, so that I have only words (without spaces) left. I'm making a hangman type game and want the computer to choose a random word. I'm new to Python and coding, so I'm happy to hear other suggestions for my code as well.
import random
fhand = open('common_words.txt')

words = []

for line in fhand:
    line = line.strip()
    words.append(line)

for word in words:
    if ' ' in word:
        words.remove(word)

print(words)

A: Use str.split(). It separates by both spaces and newlines by default.
>>> 'some words\nsome more'.split()
['some', 'words', 'some', 'more']
>>> 'this is a sentence.'.split()
['this', 'is', 'a', 'sentence.']
>>> 'dfsonf 43 SDFd fe@2'.split()
['dfsonf', '43', 'SDFd', 'fe@2']

Read the file normally and make a list this way:
words = []
with open('filename.txt','r') as file:
    words = file.read().split()

That should be good.

A: Sets are more efficient than lists. When lazily constructed like here, you can gain significant performance boost.
# Load all words
words = {}
with open('common_words.txt') as file:
    for line in file.readlines():
        line = line.strip()
        if " " not in line:
            words.add(line)
# Can be converted to one-liner using magic of Python
words = set(filter(lambda x: " " in x, map(str.strip, open('common_words.txt').readlines())))

# Get random word
import random
print(random.choice(words))

A: with open( 'common_words.txt', 'r' ) as f:
    words = [ word for word in filter( lambda x: len( x ) > 0 and ' ' not in x, map( lambda x: x.strip(), f.readlines() ) ) ]

with is used because file objects are content managers. The strange list-like syntax is a list comprehension, so it builds a list from the statements inside of the brackets. map is a function with takes in an iterable, applying a provided function to each item in the iterable, placing each transformed result into a new list*. filter is function which takes in an iterable, testing each item against the provided predicate, placing each item which evaluated to True into a new list*. lambda is used to define a function (with a specific signature) in-line.
*: The actual return types are generators, which function like iterators so they can still be used with for loops.

A: I am not sure if I understand you correctly, but I guess the split() method is something for you, like:
with open('common_words.txt') as f:
    words = [line.split() for line in f]

words = [word for words in words_nested for word in words]  # flatten nested list

A: As mentioned, the
    .split()
Method could be a solution.
Also, the NLTK module might be useful for future language processing tasks.
Hope this helps!


text:
Q: Dose anyone know Help Authoring Tools for User Guide and Source document? I have a larg scale program and I have to create a perfect User Guide and a Source document for it.
I have used 2 difrent tools for user guide and source document in Java.
Now I need some tools that have these tow option in one(Source Document Generator and User Guide Generator) .
please help me out with this

A: If your program is an API, I would suggest swagger.io .
If you want more generic technical documentation tools you can look at the following softwares:

*

*HelpNdoc

*ClickHelp

*Whatfix

*ProcessStreet


text:
Q: Send keyboard input to a specific child control Ok, ill try to keep this quick and to the point.
In C# Winforms, I have a GUI window which displays a datagridview and a textbox. Basically what I want to do is, when either the Up Arrow key or Down arrow key is pressed, to send this input straight to the datagridview in order to move up and down through the list. If any other key is pressed, I want to send this input to my textbox.
I've tried over-writing the ProcessCmdKey method and setting focus based on the keyData keycode, but what happens is the first key press will only set the control focus, then, the 2nd key press will actually work on the focused control. I'd like the input to work immediately without that one key delay.
Extra details:
The GUI class is a generic class.
Hope this makes sense! I will edit if more details are needed
Thank you!

A: This is tricky to do, DataGridView is difficult to tinker with.  It has the ProcessUpKey() and ProcessDownKey() methods but they are protected.  You'd have to override the class and add public methods so you can call them.  What you tried to do failed because by the time you got the keyboard message, it is already committed to the window that has the focus.
A bit of sly hackorama that will work without making big changes to your existing form is just posting the keyboard message back, but this time with the DataGridView as the target window.  Paste this snippet into your form class:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
    if (msg.HWnd != dataGridView1.Handle && (keyData == Keys.Up || keyData == Keys.Down)) {
        PostMessage(dataGridView1.Handle, msg.Msg, msg.WParam, msg.LParam);
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr PostMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);


text:
Q: display count on same field based on different criteria from same table Say my table has only 2 fields: Id and color.
id  color
----------
1   Green
2   Red
3   Yellow

I want the count to be displayed in a row not in a column.
  SELECT COUNT(color), color
    FROM MYTABLE
GROUP BY color

This gives me:
count   color
--------------
10      Green
20      Red
15      Yellow

I need it to be displayed as:
Green  Red  Yellow
-------------------
10     20   15

A: SELECT
  COUNT(CASE Color WHEN 'Green'  THEN 1 END) AS Green,
  COUNT(CASE Color WHEN 'Red'    THEN 1 END) AS Red,
  COUNT(CASE Color WHEN 'Yellow' THEN 1 END) AS Yellow
FROM MYTABLE

You don't need grouping here. Basically, every COUNT passes all the rows but counts only those where Color matches a certain value.

A: select (select COUNT(color) from MyTable where color='Green') as 'Green',
       (select COUNT(color) from MyTable where color='Red') as 'Red'.
       (select COUNT(color) from MyTable where color='Yellow') as 'Yellow'

A: Another way to do this (in MySQL only) is:
SELECT SUM(color = 'Green')  AS "Green"
     , SUM(color = 'Red')    AS "Red"
     , SUM(color = 'Yellow') AS "Yellow"
FROM MyTable ;

A: Try this link http://blog.programmingsolution.net/sql-server-2008/sql-server-pivot-converting-rows-to-columns-with-dynamic-query/
but if you do somthing like this
 select [ID],[COLOUR] from

 ( SELECT [ID],[COLOUR] FROM [dbo].[table] ) as S

 Pivot ( COUNT([COLOUR])

 FOR COLOUR IN ([YELLOW],[RED],[GREEN])

 ) as P


text:
Q: DirectX: How to apply an Effect to a texture drawn with ID3DXSprite.Draw(..) I want to write a very simple Effect for a DirectX program which uses the ID3DXSprite interface to draw a 2D-Hud. In XNA I simply called
        spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);

        effect.Begin();
        effect.CurrentTechnique.Passes[0].Begin();
        spriteBatch.Draw(texture, new Rectangle(0, 0, 300, 300), Color.White);
        effect.CurrentTechnique.Passes[0].End();
        effect.End();

        spriteBatch.End();

But in C++, nearly the same code doesnt work
pSprite->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_DONOTSAVESTATE | D3DXSPRITE_SORT_TEXTURE);

anEffect->SetTechnique(technique);

anEffect->Begin(&passes, 0);

anEffect->BeginPass(0);

pSprite->Draw(pTexture, NULL, NULL, &position, 0xFFFFFFFF);

anEffect->EndPass();

anEffect->End();

pSprite->End();

NOTE: The effect is loaded  correctly!

A: Well, first of all the XNA code you have is for XNA 3.1, and it's wrong. This blog post explains how to do it for both XNA 3.1 and 4.0 (the API changes in between).
In XNA 3.1, when using SpriteSortMode.Immediate, SpriteBatch will set up its shaders and other device state in the Begin call, instead of in the End call. This gives you the opportunity to replace parts of the device state before drawing actually takes place (in Draw or End, depending on when it flushes). And then you are supposed to End your effect after you End the sprite batch (so everything gets drawn first).
Now, in DirectX, I would suggest that the same incorrect ordering of your End calls is to blame. Specifically refer to this part of the documentation for the second parameter to ID3DXEffect::Begin

determines if state modified by an effect is saved and restored. The default value 0 specifies that ID3DXEffect::Begin and ID3DXEffect::End will save and restore all state modified by the effect

The upshot is that, when you End the effect, it is resetting the device back to normal sprite drawing, before you call End on the ID3DXSprite, which is what is actually sending your sprite batch to be drawn.
I would guess that the reason your incorrectly-ordered code works on XNA is that XNA is probably doing the equivalent of passing D3DXFX_DONOTSAVESTATE, when beginning the effect, under the hood.

A: Usage of Sprite with HLSL Effect: (for C++ Game Developers)
Below is the sample code which explains how sprite draw can work with HLSL effect files
Pseudo Code:
ID3DXEffect*                g_pEffect = NULL;       // D3DX effect interface

void loadTextureEffect() {
  D3DXCreateTextureFromFile(gD3dDevice,L"image.png",&gTextureBackdrop);
  DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE;
  D3DXCreateEffectFromFile( gD3dDevice, "shader.fx", NULL, NULL, dwShaderFlags,
                                    NULL, &g_pEffect, NULL );
}

void Render()
{
   unsigned int passes;
   gD3dDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x00000000, 1.0f, 0);
   gD3dDevice->BeginScene();
   gSprite->Begin(0);
   g_pEffect->SetTechnique("PostProcess");
   g_pEffect->SetTexture( "Tex0", gTextureBackdrop );
   float blurFactor = 25;
   g_pEffect->SetValue("TextureBlur",&blurFactor ,sizeof(float));
   g_pEffect->Begin(&passes, 0);
   for(unsigned int pass = 0; pass < passes; ++pass)
   {
    g_pEffect->BeginPass(pass);
    D3DXVECTOR3 spritePos(0.0f, 0.0f, 0.0f);
    gD3dDevice->SetTexture(0,gTextureBackdrop);
    gSprite->Draw(gTextureBackdrop, 0, 0, &spritePos, 0xffffffff);
    gSprite->End();
    g_pEffect->CommitChanges();
    g_pEffect->EndPass();
   }
g_pEffect->End();
gD3dDevice->EndScene();
gD3dDevice->Present(NULL,NULL,NULL,NULL);
}


text:
Q: Beautiful Soup using html.parser having troubles decoding quotation marks I have a simple program to grab the text of an article from Fox News, but for some reason I am having troubles getting the quotation marks to be decoded correctly.
from bs4 import BeautifulSoup
import urllib

r = urllib.urlopen('http://www.foxnews.com/politics/2016/10/14/emails-reveal-clinton-teams-early-plan-for-handling-bill-sex-scandals.html').read()
soup = BeautifulSoup(r, 'html.parser')

for item in soup.find_all('div', class_='article-text'):
    print item.get_text().encode('UTF-8')

This grabs the text I am looking for, but for almost all quotation marks in the article they are printed like this: Bill Clinton's.  I have tried specifically defining the decoding to be in utf-8 and have looked at the page to see what encoding it declares and it is utf-8 as well so I am not sure why this is happening.

A: So this does not solve why Beautiful Soup was having issues decoding the text, but I have found two roundabout ways to solve the issue.  One is to declare an encoding at the top of the script:
      # This Python file uses the following encoding: utf-8

The other is to decode and remove all Unicode characters, then encode again with ascii.
print(temp.decode('unicode_escape').encode('ascii','ignore'))


text:
Q: Updating app uses FFMpeg version used in older version of app I was using FFMpeg old version in my app and now i updated my app to new FFMpeg version.But when i update my old app version to new app version it still seems to use old version of FFMpeg until i uninstall old app version and then install new app version.I tried programmatically delete cache data in my new version of app using below code but with that also I face problem in some devices which still uses old FFMpeg version-
  private void clearData()
    {
        try {
            PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            int mCurrentVersion = pInfo.versionCode;
            SharedPreferences mSharedPreferences = getSharedPreferences("xyz",  Context.MODE_PRIVATE);
            SharedPreferences.Editor mEditor = mSharedPreferences.edit();
            mEditor.apply();
            int last_version = mSharedPreferences.getInt("last_version", -1);
            if(last_version != mCurrentVersion)
            {
                deleteCache(this);
            }
            mEditor.putInt("last_version", mCurrentVersion);
            mEditor.commit();
        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(e);
        }
    }
    private void deleteCache(Context context) {
        try {
            File dir = context.getCacheDir();
            deleteCacheDir(dir);
        } catch (Exception e) { FirebaseCrashlytics.getInstance().recordException(e);
        }
    }
    private boolean deleteCacheDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteCacheDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
            return dir.delete();
        } else if(dir!= null && dir.isFile()) {
            return dir.delete();
        } else {
            return false;
        }
    }


text:
Q: My on hover drop down menu hidden behind content (image) I make a navigation menu for my photo gallery with codeigniter and use fancybox for image popup. But when I use drop down in my menu, drop down part goes to behind the image, I use z-index in CSS but not get any solution. I give my code and screen short. Please help me.
My html code for nav:

<a href="<?php echo base_url(); ?>">Home

<a href="<?php echo base_url(); ?>gallery/official">Official Photo

<a href="<?php echo base_url(); ?>gallery/program">Program

Foreign Photo

Test

Test1

Test2

<a href="<?php echo base_url(); ?>upload">Upload

Contact

My html code for contant:

    <?php foreach ($image as $value) { ?>

<a class="fancybox" rel="gallery1" href="<?php echo base_url() . "gallery/$value->name" ; ?>" title="<?php echo $value->name; ?>"><img class="pici" src="<?php echo base_url() . "gallery/$value->name" ;?>" height="140" width="100%" >

    <?php } ?>

And my css code is:

#cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a,
#cssmenu #menu-button {
  margin: 0;
  padding: 0;
  border: 0;
  list-style: none;
  line-height: 1;
  display: block;
  position: relative;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
#cssmenu:after,
#cssmenu > ul:after {
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}
#cssmenu #menu-button {
  display: none;
}
#cssmenu {
  width: auto;
  font-family: Raleway, sans-serif;
  line-height: 1;
  float: left;
  height: 44px;
}
#cssmenu > ul {
  /*background: #3db2e1;*/
}
#cssmenu > ul > li {
  float: left;
  -webkit-perspective: 1000px;
  -moz-perspective: 1000px;
  perspective: 1000px;
}
#cssmenu.align-center > ul {
  font-size: 0;
  text-align: center;
}
#cssmenu.align-center > ul > li {
  display: inline-block;
  float: none;
}
#cssmenu.align-right > ul > li {
  float: right;
}
#cssmenu > ul > li > a {
  padding: 16px 20px;
  margin: 0 2px;
  font-size: 12px;
  color: #ffffff;
  letter-spacing: 1px;
  /*text-transform: uppercase;*/
  text-decoration: none;
  background: #008000;
  -webkit-transition: all .3s;
  -moz-transition: all .3s;
  -o-transition: all .3s;
  transition: all .3s;
  -webkit-transform-origin: 50% 0;
  -moz-transform-origin: 50% 0;
  transform-origin: 50% 0;
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
}
#cssmenu > ul > li.active > a {
  color: #dff2fa;
}
#cssmenu > ul > li:hover > a,
#cssmenu > ul > li > a:hover {
 /* color: #dff2fa;
  -webkit-transform: rotateX(90deg) translateY(-23px);
  -moz-transform: rotateX(90deg) translateY(-23px);
  transform: rotateX(90deg) translateY(-23px);
  -ms-transform: none;*/
}
#cssmenu > ul > li > a::before {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: -1;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 16px 20px;
  color: #dff2fa;
  background: #19799f;
  content: attr(data-title);
  -webkit-transition: background 0.3s;
  -moz-transition: background 0.3s;
  transition: background 0.3s;
  -webkit-transform: rotateX(-90deg);
  -moz-transform: rotateX(-90deg);
  transform: rotateX(-90deg);
  -webkit-transform-origin: 50% 0;
  -moz-transform-origin: 50% 0;
  transform-origin: 50% 0;
  /*-ms-transform: translateY(- -18px);*/
}
#cssmenu > ul > li:hover > a::before,
#cssmenu > ul > li > a:hover::before {
  background: #3db2e1;
}
#cssmenu.small-screen {
  width: 100%;
}
#cssmenu.small-screen > ul,
#cssmenu.small-screen.align-center > ul {
  width: 100%;
  text-align: left;
}
#cssmenu.small-screen > ul > li,
#cssmenu.small-screen.align-center {
  float: none;
  display: block;
  border-top: 1px solid rgba(100, 100, 100, 0.1);
}
#cssmenu.small-screen > ul > li:hover > a,
#cssmenu.small-screen > ul > li > a:hover {
  color: #dff2fa;
  -webkit-transform: none;
  -moz-transform: none;
  transform: none;
  -ms-transform: none;
}
#cssmenu.small-screen > ul > li > a::before {
  display: none;
}
#cssmenu.small-screen #menu-button {
  display: block;
  padding: 16px 20px;
  cursor: pointer;
  font-size: 14px;
  text-decoration: none;
  color: #ffffff;
  text-transform: uppercase;
  letter-spacing: 1px;
  background: #008000;
}
#cssmenu.small-screen #menu-button:after {
  content: "";
  position: absolute;
  right: 20px;
  top: 17px;
  display: block;
  -webkit-box-sizing: content-box;
  -moz-box-sizing: content-box;
  box-sizing: content-box;
  border-top: 2px solid #ffffff;
  border-bottom: 2px solid #ffffff;
  width: 22px;
  height: 3px;
}
#cssmenu.small-screen #menu-button.menu-opened:after {
  border-top: 2px solid #dff2fa;
  border-bottom: 2px solid #dff2fa;
}
#cssmenu.small-screen #menu-button:before {
  content: "";
  position: absolute;
  right: 20px;
  top: 27px;
  display: block;
  width: 22px;
  height: 2px;
  background: #ffffff;
}
#cssmenu.small-screen #menu-button.menu-opened:before {
  background: #dff2fa;
}
#cssmenu > ul > li > ul > li { display: none;}
#cssmenu > ul > li:hover ul > li {display: block;padding: 8px 10px; background-color: #008000;color:#fff;overflow: visible;}
#cssmenu ul li ul li a{color:#fff;font-size: 12px;}
#cssmenu ul li ul li{border: 1px solid #fff;}

A: The navbar div parent should be position:relative and its z-index bigger than the container of photo gallery parent which should be position:relative also. This , probably will fix the problem.


text:
Q: Приложение не работает с api28 и выше Приложение получает данные из интернета. Запускается и отлично работает на api25, но выше api28, включительно, нет.
Насколько я знаю, в >=api28 встроена защита против загрузки данных из http.
Как разрешить подключение?

A: Как оказалось, я просто не смог правильно сформулировать вопрос, поэтому не нашел на просторах нета ответ.
Собственно, решение на удивление простое. Для того, чтобы разрешить все типы сетевых подключений HTTP и HTTPS нужно добавить атрибут в манифест с разрешением всех http запросов:
<application>
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
    android:name="org.apache.http.legacy"
    android:required="false" />
</application>


text:
Q: Index on a TEXT column with defined set of values mysql> describe marketing_details;
+--------------------------+---------------------+------+-----+-------
------------+-----------------------------+
| Field                    | Type                | Null | Key |
Default           | Extra                       |
+--------------------------+---------------------+------+-----+-------
------------+-----------------------------+
| id                       | bigint(20)          | NO   | PRI | NULL
| auto_increment              |
| platform_origin          | varchar(100)        | NO   | MUL |
|                             |
| partner_id               | bigint(20) unsigned | NO   | MUL | 0
|                             |
+--------------------------+---------------------+------+-----+-------
------------+-----------------------------+

For a query like,
SELECT *
FROM partners
INNER JOIN marketing_details ON partners.id = marketing_details.partner_id
where marketing_details.platform_origin IN ('platform_A', 'platform_B');

The platform_origin column can have a set of defined values (one of 4 values). So adding index/full text index does not seem to be of use here. But the data can be huge and there can be multiple constraints in the query. What will be a good way to optimise the query?

A: For this query:
SELECT . . .
FROM partners p INNER JOIN
     marketing_details md
     ON p.id = md.partner_id
WHERE md.platform_origin IN ('platform_A', 'platform_B');

You should try indexes on:

*

*marketing_details(platform_origin, partner_id)

*partners(id)
You probably already have the second one if id is declared as the primary key.

A: Another suggestion would be to have a check constraint on platform_origin to have only the 4 possible values
Also it would help if you have histograms on the column platform_origin if your version allows. This would give the optimizer more inputs while creating an optimal plan if there is data skew on the values in the column.
Have a look at the following link.
https://mysqlserverteam.com/histogram-statistics-in-mysql/


text:
Q: How to make an app to play ringer with behaviors similar to iphone native phone ring I am working on a VOIP app on iOS. I have encountered some problems when implementing "Ignore incoming ringer" feature. It has the following requirements:
1. Should stop ringer if pressed screen lock or volume button
2. Should stop ringer if mute button is pushed to "mute" state
3. Should not play ringer if mute button is in "mute" state
Since iOS SDK provide no information of the phone's hardware buttons, I can only rely on setting AVAudioSession category. Before playing ringer, I set the category to ambient so screen lock and mute button can stop the audio. But this method cannot satisfy my requirements because app cannot play ringer when in background because ambient category cannot support background audio.
In order to solve this problem, I start playing the ringer in playbackandrecord category to make the audio stream come out and change the category to ambient immediately. Though it can meet my requirements, but this method caused many problems and bugs. For exameple, MPVolumeView cannot display the output devices correctly.
Can anyone provide a more elegant way way to simulate ringer? Or can this be done in iPhone?  Since it will be in app store, I cannot use private apis. Thanks in advance.


text:
Q: User input custom control (text editor) I am developing a CAD like application. This application is cross platform in the sense that I have a main window which is native to the platform it is running on (Linux, Windows and Apple). Within this window I have an OpenGL context and there I do all my rendering. The application in question does not really rely on common controls (radio buttons, check-boxes, labels etc), however there is the need for the user to be able to enter/edit some text. This text could be a few lines long but not more than one hundred.
How would I go about implementing such a control, I don't want to go as deep as developing my own text editor but it would be nice if it had some basic editor controls (cursor movement, delete, insert etc). I also don't want to use the native systems common controls as my own none cross platform code at the moment is the main window.
Any ideas?
Edit: This is informative
OPENGL User Interface Programming
Thank you

A: I think you are taking a longer approach here.
Rather than providing an interface through OpenGL and writing my own controls, I would go for a cross-platform GUI toolkit such as wxWindows, and use the GLCanvas provided to do my rendering. You'll have all the might and flexibility of common controls, you'll still be able to OpenGLize whatever you want, and the look of your application will be more standard, thus friendlier.


text:
Q: Reuse last line of output from shell command I am compiling something and depending on success (last line of output contains "success"= I want to scp the binary to the target. I'd prefer a piped oneliner. Is there a way to do this?

A: Try this:
your command | tail -n1 | grep -q 'success' && scp ...

Example:
% cuonglm at ~
% printf "sad\nsadsa\nsuccess\n" |
  tail -n1                       |
  grep -q 'success' && echo 'this command run'
this command run

A: You're not giving any information on what/how you are compiling. However, in most cases, the compiler will return a successful exit signal if it compiled correctly so you could just use the shell's features directly:
$ gcc -o foo.bin foo.c && echo YES || echo NO
YES
$ gcc -o foo.bin foo.txt && echo YES || echo NO
foo.txt: file not recognized: File truncated
collect2: error: ld returned 1 exit status
NO

So, in your case, you could probably simply run
$ complile_command && scp binary user@server:/remote/path

A: One way:
cmd | awk 'END{exit!/success/}' && scp ...

A: You could, indeed, use a one-liner:
command | grep -q success && othercommand

This would execute othercommand if the command outputs something containing success.


text:
Q: Using the indexOf() method, is there a way for me to return the first index in a string that is an alphabetical letter? Java Title. I'm new to this site sorry if it's bad question. I'm trying to make it so that my method returns -1 if there isn't an alphabetical letter in the string. I already set up a way to iterate through the string but now I need to know how to see if it returns true if it finds ANY alphabetical letter in the string and -1 if not.

A: To find the index of the first letter in a string, use a regular expression:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

static int indexOfLetter(String input) {
    String regex = "[a-zA-Z]";
    //         or: "\\p{Alpha}";  // same as [a-zA-Z]
    //         or: "\\p{L}";      // all unicode letters
    Matcher m = Pattern.compile(regex).matcher(input);
    if (m.find())
        return m.start();
    return -1;
}

Test
System.out.println(indexOfLetter("123456789")); // prints: -1
System.out.println(indexOfLetter("12345ABCD")); // prints: 5
System.out.println(indexOfLetter("@#$XYZ%^&")); // prints: 3

If you use the \p{L} regex, it'll find accented letters too.
static int indexOfLetter(String input) {
    Matcher m = Pattern.compile("\\p{L}").matcher(input);
    return (m.find() ? m.start() : -1);
}

Test
System.out.println(indexOfLetter("...ñ...")); // 3  'LATIN SMALL LETTER N WITH TILDE' (U+00F1)
System.out.println(indexOfLetter("..ß.."));   // 2  'LATIN SMALL LETTER SHARP S' (U+00DF)
System.out.println(indexOfLetter(".Δ."));     // 1  'GREEK CAPITAL LETTER DELTA' (U+0394)

UPDATE
If you're not allowed to use regex ("not allow me to use additional import statements"), a simple search loop calling Character.isLetter will do:
static int indexOfLetter(String input) {
    for (int i = 0; i < input.length(); i++)
        if (Character.isLetter(input.charAt(i)))
            return i;
    return -1;
}

That does support Unicode letters, but not surrogate pairs. Given the rarity of letters outside the Basic Multilingual Plane (BMP), that's probably not an issue. If it is, the following change will support those too:
static int indexOfLetter(String input) {
    for (int i = 0; i < input.length(); i = input.offsetByCodePoints(i, 1))
        if (Character.isLetter(input.codePointAt(i)))
            return i;
    return -1;
}


text:
Q: How ID stage reads the data just being writen? So this is a question about computer organization
Consider following instruciotns:
add $t2, $t2, $t2
nop
nop
add $t2, $t2, $t2

We can draw cycle diagram like:
add| IF| ID|EXE|MEM| WB|
nop|   |   |   |   |   |
nop|   |   |   |   |   |
add|   |   |   | IF| ID|EXE|MEM| WB|

first add is in WB stage and second add is in ID stage.
Textbook tell me that this won't make hazard since you can write Registerfile in first half cycle and read it in second half cycle. It doesn't make sence if we assume pipeline stage and registerfile both are positive edge trigger. The behavior can described by verilog like:
always @(posedge clk)begin
    if(RegWrite) regfile[waddr] <= wdata;
end

Here is the timing diagram I think:
This
As you see when second add is reading registerfile, the new data is just being written. How can you write in first half cycle when RegWrite is "LOW"?
At least there will be a clk to Q delay. It is impossible to write register at positive edge.
If clock phase of pipeline register and registerfile are different, it's not a problem anymore, but no one said that.
Or just simply tell me you can read data just being written somehow.
==============================
clk      __/‾‾‾\___/‾‾‾\___
RegWrite ____/‾‾‾‾‾‾‾‾\____

there must be a clk to q delay for RegWrtie.
how Regfile write data at "clock edge" when RegWrite is LOW?


text:
Q: SVG Height not adjusting with aspect ratio Used one svg image in the div with the width 50px, but in IE11 , SVG height is coming as 150px. It should have been 50px X 50px . width 50px is applying correctly not the height. Any suggestion ,

.svg-cont{
  width:50px
}
img{
  max-width:100%;
  height:auto;
}

Thanks in advance for any help. codepen: http://codepen.io/shmdhussain/pen/YZmrOq

A: Thanks Issue is solved after setting the width:100% to the image tag . issue resolved pen codepen: http://codepen.io/shmdhussain/pen/XMvzWv

.svg-cont{
  width:50px
}
img{
  max-width:100%;
  width:100%;
  height:auto;
}

reference: https://tympanus.net/codrops/2014/08/19/making-svgs-responsive-with-css/


text:
Q: What defines a bruiser? What makes them a "bruiser"? By that I mean which stat defines them as a bruiser or is it something else that makes them a bruiser?

A: Tanky dps. Bruisers generally also have pretty strong lane sustain that allows them to farm. They're steady and reliable DPS for your team, not high or accurate enough to be a classic carry but enough of a threat to warrant focusing.

A: Yeah. They're pretty beefy- Perhaps even enough to offtank. They can also dish out TONS OF DAMAGE (As Phreak would say), but not enough to count as a true Carry a la Tryndamere, Yi, etc.

A: A bruiser is a strong sustain hero that can deal damage consistently.


text:
Q: Databinding behaving differently on textbox and label I have a database with a row that has "TEXTTEXT" inside a "noteText" column and null in that column for a different row.  If I run a query that generates 1 rows, then run a different query that has 2 rows, Eval("noteText") returns different information when placed in a TextBox vs. placed in a Label. The TextBox and Label were created specifically for this test; it is not referenced in the codebehind.  I think the TextBox for row 1 of the second query is somewhow pulling the data used in row1 of the first query.
I don't think it could be a browser-related issue since the source code of the returned page is itself incorrect.
Aspx file code:
<asp:TemplateField HeaderText ="Notes" SortExpression="noteid">
    <ItemTemplate>
        STARTXX
        <asp:TextBox ID="AtxtNote" ViewStateMode="Disabled" runat="server"
            TextMode= "SingleLine" Width="260" Text='<%# Eval("noteText")  %>' />

        <asp:Label ID="BtxtNote" runat="server" Width="260"
            Text='<%# Eval("noteText") %>' />

        ENDXX
    </ItemTemplate>
</asp:TemplateField>

Source code on page:
STARTXX
    <input name="ctl00$CPH1$gv$ctl02$AtxtNote" type="text"
            value="TEXTTEXT" id="ctl00_ContentPlaceHolder1_gv_ctl02_AtxtNote"
            style="width:260px;" />

ENDXX

Actual spacing is a bit different; I edited the text of the source and output code to prevent horizontal scrolling.
I expected both Eval calls to show an empty string.

A: We fixed it by adding more calls to DataBind.
The current theory is that the TextBox was being submitted when clicking the button to query the database.  After the DataBind happened, Asp.Net repopulated the TextBox with the data that was submitted.  The TextBox now logically corresponded to a different row in the database, but was in the same position as the TextBox from the previous page view and thus had the same ClientID.
One reason for this suspicion is that the posts were triggering OnTextChanged events.
I'm still unhappy with this; I don't have full confidence that I know what's going on, even though it is now working.