text:
Q: Can two machines on VPN connect to each other We have our Middleware server which is connected to client network through VPN.
Now we need to connect to this server.
My question is if we connect our development systems to client network using VPN, will we be able to access the server, which should be theoratically.
Also will this be the best solution or we can do something better?

A: There are lots of things at play here but in theory yes, if you connect over VPN to the same end network you should be able to access the resources on that network based on the rules the VPN/Firewall server has in place.
Why didn't you just test it out?

A: If I understand you correctly.  Yes, if you VPN into your client network you should be able to access their network and the middleware server, since they are able to access the middleware server.
If the client can VPN into their own network from home and access the middleware server, then you should be able to do the same thing with them once setup on their VPN.
Hope that helps.

A: It is possible.
Since you haven't mentioned which VPN solution you are using, i can just guess, but you should siable client isolation, and check any potential firewall rules, to allow traffic between them


text:
Q: Is there exist a continuous onto function $f : S^1 \rightarrow S^2 $ or $S^2 \rightarrow S^1$? Yes/no $1. $ Is  there  exist  a  continuous onto function  $f : S^1 \rightarrow S^2 $?
$2.$ Is there exist a continuous onto function  $f : S^2 \rightarrow S^1$?
My thinking : I thinks in both cases $1$ and $2$ it is not possible    because $S^2$ minus two points is connected while $S^1$ minus two points isn't.

A: For $t\in [0,\pi]$ let $f_1(\cos t,\sin t)=t/\pi.$ For $t\in [\pi,2\pi]$ let $f_1(\cos t, \sin t)=(2\pi-t)/\pi.$
There exists a continuous surjection $f_2:[0,1]\to  [0,1]^2.$ See "Peano  Curve" in Wikipedia.
For $(x,y)\in [0,1]^2$ let $f_3(x,y)=(\cos 2\pi x, \sin 2\pi x \cos \pi y, \sin 2\pi x \sin \pi y).$
Now $f=f_3f_2f_1$ is a continuous surjection from $S^1$ to  $S^2.$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Qt Combobox Model Using SQLite With Sq-lite, how can I set a model for the combo-box that has two table columns added together (ie surName +' '+ firstName)...with MS SQL Server I simply use a view.
When I tried with Sq Lite...nope! all other widgets (ie.QLineEdit and QDateEdits) loose their content and only combo-boxes display please Help!
Edit:
Using QSqlRelationalModel the QWidgetDataMapper does not work on my form. All widgets are null except the comb-boxes using the default delegate
parInd = model->fieldIndex("stPar");
model->setRelation(parInd,QSqlRelation("allParents", "parID", "parName"));
QSqlTableModel *parModel = model->relationModel(parInd);
ui->stParent->setModel(parModel);
ui->stParent->setModelColumn(parModel->fieldIndex("parName"));

The allParents is a view saved on my sqlite db When I change reference table to tblParents(the base table) all widgets are ok with data...the problem is the parent field displays only firstname yet I need the fullname. How can I work around this!


text:
Q: How to set a bool variable to true when a key is pushed and false when it is pushed again? I am having quite an issue in C# right now I am trying to code a function that detects when the F8 button is pushed and set the bool F8Pushed to true then when it is pushed again set F8Pushed to false.
Here is the code I have so far:
static bool IsKeyPressed() //This Function Returns True if F8 Is Pushed and False if F8 is up
{
    bool is_pressed = (GetAsyncKeyState(119) & 0x8000) != 0;
    return is_pressed;
}

static void CheckHotKey() //This is the Function that I am calling the other function from for debugging.
{
    while (true)
    {
        Console.WriteLine(IsKeyPressed());
    }
}

Now the problem that I am having and cannot resolve is that I cant find a way to get the variable to copy its self to another variable and be able to go back to false if that makes sense. I can get a bool set to true if IsKeyPressed() == true however I cannot figure out how to get it back to false when it returns true again.
Thanks in advance!
EDIT:
Thanks for you help guys however I am still having some trouble heres an update.
static bool IsKeyPressed()
    {
        is_pressed = (GetAsyncKeyState(119) & 0x8000) != 0 && !is_pressed;
        return is_pressed;
    }

    static void CheckHotKeys()
    {
        while (true)
        {
            IsKeyPressed();
            if(is_pressed)
            {
                F8Pushed = true;
            }
            Console.WriteLine(F8Pushed);
            if(IsKeyPressed())
            {
                F8Pushed = false;
            }
            Console.WriteLine(F8Pushed);
        }
    }

I managed to get it to work kinda however it is very buggy and alot of times the key stroke doesnt detect any ideas?

A: I'm not sure whether I fully understand what you are trying to accomplish. Your code contains so many problematic parts, that I choose to write a completely new code:
class Program
{
  const byte VK_F8 = 0x77;
  const byte VK_ESC = 0x1b;

  static bool globalAppState = false;

  static void Main(string[] args)
  {
    bool lastState = IsKeyPressed(VK_F8);
    while (!IsKeyPressed(VK_ESC))
    {
      bool newState = IsKeyPressed(VK_F8);
      if (lastState != newState)
      {
        if (newState)
        {
          Console.WriteLine("F8: pressed");
          globalAppState = !globalAppState;
        }
        else
          Console.WriteLine("F8: released");
        lastState = newState;
      }
    }
  }

  static bool IsKeyPressed(byte keyCode)
  {
    return ((GetAsyncKeyState(keyCode) & 0x8000) != 0);
  }

  [DllImport("user32.dll")]
  static extern short GetAsyncKeyState(int vKey);
}

Function IsKeyPressed(VK_F8) tells you always the current state (pressed/released) of the specified key.
When you need to do some action only on change (from pressed to released, or from released to pressed) replace the console output functions with your specific task.
When you need some multi-threading like processing the event in a new thread, that is a different question... (outside of this scope)
EDIT: Added change of variable on each new key pressed event. This is dirty solution...

A: You have to make that variable is_pressed as global to keep current state. then make a Try like this:
static bool is_pressed;
static bool IsKeyPressed()
{
    is_pressed = (GetAsyncKeyState(119) & 0x8000) != 0 && !is_pressed;
    return is_pressed;
}

Where && !is_pressed will toggles the value for you every time

A: Assuming you're storing the result of the key press in a boolean:
bool isKeyPressed = true;

You could then do this:
isKeyPressed == IsKeyPressed() && !isKeyPressed;


text:
Q: Could I add an item in `/etc/fstab` to bind an old directory with a new one? I have a problem with binding two directories. The problem comes that storage on hard disk is almost run out and I install another disk moving files in ~/Documents/ into one folder of the new disk. I still want mount --bind folder_on_new_disk ~/Documents, thus I will not change my favor.
The problem is that could I add an item in /etc/fstab to achieve this automatically when system startup?

A: @Paul's fstab example is, basically, the way to go if you want an answer to the question as asked. However, I would suggest that unless you have specific reasons for only moving your documents, it might not be a bad idea to move the whole /home directory to the new disk, and use the same technique to bind /home to its new location (or even just move /home/* to the root of a partition on the new drive and mount that partition at /home). This will provide two major benefits:

*

*You are likely to get more space for your home directory.

*You completely separate the operating system, system-wide configuration files and application binaries from your own files.

The point on separation to me is the bigger issue: it means that if you need to reinstall the OS for some reason, you won't have to worry anywhere near as much about your personal files (e-mails, documents, music, etc etc).
Unix mount points are a very flexible construct - do take advantage of that.

A: You can add this to fstab as follows:
/mnt/new_disk/folder /home/[username]/Documents    none    bind    0 0

Replace the correct folder name, and the username where the documents folder is.  It also presumes the /home directory is where your user folders are, so adjust accordingly if not.


text:
Q: Replace a color using Wand I'm trying to replace a color in an image with another color, by defining the coordinates of one of its pixels.
But when I run the code the result is exactly the same as the original.
here's the original image:

here's the code:
from wand.image import Image
from wand.display import display
from wand.drawing import Drawing
from wand.color import Color

with Drawing() as draw:
    draw.fill_color = Color('#ff0000')
    draw.color(192,84,'replace')

    with Image(filename='rgb.jpg') as img:
        img.save(filename='rgr.jpg')
        display(img)

192,84 is somewhere around the middle of the blue section of the image.
Which should now be red, except nothing changes.
I thought maybe it has something to do with the "fuzz" but i can't figure out the syntax. I tried:
draw.color(192,84,'replace',fuzz=10)

But I got the "unexpected keyword argument 'fuzz'" error.
so I tried:
draw.fuzz = 10

I got no errors, but the image still had no change.

A: I would guess that you did not apply the drawing context to the image.
from wand.image import Image
from wand.display import display
from wand.drawing import Drawing
from wand.color import Color

with Drawing() as draw:
    draw.fill_color = Color('#ff0000')
    draw.color(192,84,'replace')

    with Image(filename='gb.jpg') as img:
        draw(img)  # <= here
        img.save(filename='rgr.jpg')
        display(omg)


text:
Q: Last exit status from within script without source Supposing someone invokes a non-existent command, the only way I know to retrieve its error status from a script I execute right after is by using source
I.e., let's say this script's name is dummy where its contents are simply
#!/bin/bash

echo $?

I know I will only get the exit status I'm looking for (127) if I invoke source dummy, but is there another way to facilitate getting the exit status (preferably without using alias) from the last command from within the script, without using source so I could simply call dummy to get my desired behaviour?
I am simply trying to make a script to check for a typo in the previous command. This requires detecting the previous exit status to make sure there was a potential typo in the first place, so I need to be able to get the exit status of the last command from within the script. I am also hoping to minimize the amount of setup a user would have to do, so that a user could simple invoke dummy, for example, and the rest would be taken care of. This is my reason for trying to avoid source or ., or alias.
My initial test for exit status of the last command was to use
#!/bin/bash
ESTATUS=$? # Saved exit status for later
echo $ESTATUS

but this required having to run that script with source. Is there a good way to replicate this without having to use source, or .?

A: You could perhaps use the script at https://github.com/rcaloras/bash-preexec (as discussed at https://superuser.com/questions/175799/does-bash-have-a-hook-that-is-run-before-executing-a-command) and use the precmd() function to do your $? checking

A: I'm not quite sure where that will lead to, but you can do:
alias dummy='sh dummy $?'
the_program_with_errors
dummy

and your dummy script would contain:
echo $1

An approach without alias is to use a shell function:
function dummy { sh dummy $? ;}

With that definition you can get the following behaviour (simulated with true, false, and a subshell process):
$ true
$ dummy
0
$ false
$ dummy
1
$ (exit 42)
$ dummy
42

A: It sounds to me as if the scripts that you are calling should provide the responses that you desire. Here's a way to test for a command and use a specific exit code in those scripts.
#!/bin/bash

# Test for the existence of a command in the path.
command=typo_command
if [[ ! $(command -v $command) ]]; then
    echo "$command does not exist"
    exit 127 # or the code you choose
fi

A: Write a function
Your shell is one process, and has a value for $?. Your script is a separate, child process, and has its own value for $?.
If you want to be able to check the $? belonging to your shell, you need your command to run in the shell process. source is one way to do that, but a simpler way is to write a function.
function dummy(){
  echo $?
}

If declared in the user's .bashrc or equivilant, this should be available and work as you expect.
(If you want, it could even call out to a script to do whatever else you want, and pass to the script the value of $?.)


text:
Q: Bootstrap grid align with box on top, not with row For one of my websites, I was using a bootstrap grid (container > row > col-3, etc.). It looked something like below.

It ended up looking like the image below.

However, I don't want it to look like that. I want it to look like the below image.

My Question: Is there any way to accomplish this? (Preferably using the same bootstrap grid feature, but if it isn't possible that way, I'm open to other suggestions)
Note: I don't want the grid to be set previously. The height will be adaptive (If the text is longer, the height would be longer. If the text is shorter, the height is shorter).


text:
Q: How validate a select field on the same button click that opens a modal? I'm trying to validate a select which is required to select an option to continue with the process. If any option is not selected then it should give an alert box, else it should open the modal. In my case the modal gets opened either way.
<select  class="form-control" id="account_name"  name="account_name">
<option  value="">Select Customer..</option>
     <?php
    while ($rows = pg_fetch_assoc($result)) { ?>
          <option value="<?= $rows['address1'] . ' ' .
              $rows['address2'] . ' ' . $rows['address3'] .' '.$name. '-' .
              $rows['account_code']; ?>"><?= $rows['account_name']; ?>
          </option>
     <?php } ?>
 </select>

  <div class="wrapper1" id='business1'>
       <input type="submit" id="myBtn"  value="New Order" style="height:55px; width:170px; margin-left: -50px;" class="btn btn-success" />
  </div>

<!-- JQUERY -->

 $(document).ready(function () {
      $("#myBtn").click(function () {
         if ($("#account_name").val() === NULL){
            alert('Please select an option');
         }
         else
         {
            $('#myModal').modal('show');
         }
      });
  });

With this code, the modal doesn't get displayed on any selection, and neither the alert box is displayed.
I also tried doing this
 <select  class="form-control" id="account_name" name="account_name"
 required>

Although the validation gets applied here, still the modal is opened on submit if no option is selected.

A: javascript is case-sensitive, so NULL isn't null. Javascript also tries to be helpful and converts variables (like your NULL) to a string if they don't exist, so your code is saying if ($(...).val() === 'NULL') which is never true, hence the modal appearing. Javascript also converts any falsey value to false... so null, '', 0, and undefined are all false, and I assume you aren't using 0 or '' as one of your options so you can simply if (!$(...).val()), instead


text:
Q: sed multiline recursive pattern substitution From the following input:
serial0/0
SSL disabled
eth0/0
SSL enabled
SSL only
eth0/1
SSL disabled
bgroup0
SSL enabled
eth0/2
SSL disabled
eth0/3
SSL disabled
eth0/4
SSL disabled
bgroup1
SSL disabled
bgroup2
SSL disabled
bgroup3
SSL disabled
vlan1
SSL enabled
null
SSL disabled

I am trying to obtain a colon separated list in which if the next line of the input begins with "SSL", it gets appended to the previous line, so the output would be like so:
serial0/0:SSL disabled
eth0/0:SSL enabled:SSL only
eth0/1:SSL disabled
bgroup0:SSL enabled
eth0/2:SSL disabled
eth0/3:SSL disabled
eth0/4:SSL disabled
bgroup1:SSL disabled
bgroup2:SSL disabled
bgroup3:SSL disabled
vlan1:SSL enabled
null:SSL disabled

As you can see in the second line of this ideal output, the case when more than one line starts with "SSL" should be considered. Based on this classic sed guide, I came up with the following sed script:
sed -r '/^SSL/! {
        :again
        N
        s/(.*)\n(SSL.*)/\1:\2/
        t again
    }'

Which makes sense to me but returns the following output:
serial0/0:SSL disabled
eth0/0
SSL enabled
SSL only
eth0/1:SSL disabled
bgroup0
SSL enabled
eth0/2:SSL disabled
eth0/3
SSL disabled
eth0/4:SSL disabled
bgroup1
SSL disabled
bgroup2:SSL disabled
bgroup3
SSL disabled
vlan1:SSL enabled
null
SSL disabled

Any idea of what I could be doing wrong?

A: A much easier solution:
sed -z 's/\nSSL/:SSL/g'

The -z says to use NUL as a line separator - effectively making the entire stream appear as one line to sed. It then simple replaces a \nSSL sequence with a :SSL sequence, effectively combining lines the way you wish.

A: You can do this with any sed flavor, no need to slurp the whole file into memory just use a classic N;P;D cycle and a branch:
sed ':b;$!N;s/\nSSL/:SSL/;tb;P;D' infile

This pulls in the Next line, attempts to substitute - if successful it branches back to :b else it Prints and then Deletes up to the newline character, restarting the cycle.


text:
Q: Git push fatal: repository not found I'm not sure what is going on. But every time I try to push or pull now with git I get this message "fatal: repository 'https://....' not found". I usually use source tree with bitbucket but am receiving the same error when I try from the command line.
The reason I'm so confused is I haven't done anything that should change the repository. This repository has had hundreds of commits from me and other team members and nothing has changed since we created it. We rarely use any advance features not even branching, just pull, push, commit, and merge. Any what could have happened and how to fix it?
I've already tried removing and re-adding the origin but no luck.

A: I think, my answer can save someone a few minutes and some nerves.
I ran into the same issue. Solved the problem by running the following Git command:
git push --set-upstream origin master

The reason: When you initialize git repository to local working directory, Git only initializes "origin", and has no upstream set to commit your changes.

A: As mentioned above this happens when the repository, team name or username changes. The solution is to set the new remote url, as shown below.
git remote set-url origin https://______________.git

A: This kind of thing happens when the repo, team name or username changes.
Happened to me when I changed the team name and all of the repos lost their origin.

A: This usually occurs when you try to add Mercurial Repo to git. Check

A: I have also faced that problem, and this was because I have renamed the repository on my bitbucket account.
The solution is to adding a new remote url to your local repository using below command:
List all old Remote URL
git remote -v

Removing old Repository URL
git remote remove <old name>

Adding new URL
git remote add <new url>

Final Step
git pull <new url>
git push

The final step when you pull it may ask for merged changes on your local repository. Please pay attention with this step before you pull. And last of all you can push your latest changes.
Hope it helps :)

A: In my case, I have to log in my git account in the terminal. I follow the steps in the following link and then after it worked
https://kbroman.org/github_tutorial/pages/first_time.html

A: this type problem casually is from ssh url is cloned withow ssh promt and you give ssh url, if you give url by url : https://......git   ...all ok
example by @Mario Shtika

A: I got this error when I changed the directory name.
I solved the problem by editing the file config, setting the remote url to the new one. This file is inside .git directory of your project.
obs: I know that the problem related to this question has already been solved but I would like to register my solution here.

A:
Make sure the user with whom you generated Github Personal Access Token (PAT) has the administrator access on the github repository.

We were trying to migrate the BitBucket repo along with all branches and commit history to Github enterprise but kept getting the error.
# Cloning the Bitbucket:
git clone --mirror http://bitbucket_admin@10.24.0.1:7990/my-bb-repo.git

# Changing the origin:
git remote add GOrigin https://github.mycompany.com/MyCompanyOrg/destination.git

# Push to new origin:
git push --mirror https://github.mycompany.com/MyCompanyOrg/destination.git
remote: Repository not found.
fatal: repository 'https://github.mycompany.com/MyCompanyOrg/destination.git' not found

As soon as we switched the PAT created by repo admin user the issue was resolved.


text:
Q: Creating routers for multiple database in Django I am developing a Django application in which I need several databases, one for each user of the system. For this I defined the databases like this:

DATABASES = {
    'default': {},
    'primary': {
        'NAME': 'primary',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'pass',
    },
    'user1': {
        'NAME': 'user1',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'pass',
    },
    'user2': {
        'NAME': 'user2',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'pass',
    },
}

In which the database user1 and user2 are replicas of the structure of primary.
Let's say I created two superusers, with the logins 'superuser1' and 'superuser2'. How do I define that when 'superuser1' is logged the data is changed in the database 'user1' and when 'superuser2' is logged the data in the database 'user2' is changed?

A: This logic is likely going to span across your application. Effectively you will need to create a function that would take a user instance and then return a string that will map to a database:
DATABASE_USER_MAP = {
    'username1': 'user1',
}

def get_database(user):
    return settings.DATABASE_USER_MAP.get(user.username, 'default')

def some_view(request):
    data = Data.objects.using(get_database(request.user)).all()
    ...

Once you get something like that working, you could move the database determining logic into a middleware and set it on request so that you could do:
def some_view(request):
    data = Data.objects.using(request.db).all()
    ...

The main concern with this is that it would default to primary rather than error out forcing you to be meticulous when writing queries.
Another avenue you may want to pursue is diving into Django's codebase to see how the database router works and if you could get the request sent as a hint to the router. I don't know anything about it, so I don't know if it's possible. However, if that were possible it'd eliminate the concern I raised.


text:
Q: Not able to start network on Hyperledger Fabric network V 0.19. Error: REQUEST_TIMEOUT Command failed I am trying to setup my first Hyperledger Fabric network on my Windows 10 Pro PC.
I did follow below steps to create network.

*

*./startFabric.sh - Success

*./createPeerAdminCard.sh  - Success

*composer archive create -t dir -n .   - .bna file created successfully on project root folder

*composer network install --card PeerAdmin@hlfv1 --archiveFile sample-test-network@0.0.1.bna

Now I got error in next step when executing below command for start network.

composer network start --networkName diam-test-network --networkVersion 0.0.1 --networkAdmin admin --networkAdminEnrollSecret adminpw --card PeerAdmin@hlfv1 --file sample-testkAdmin.card

It take sometime for execution and then it gave error mention below :

**Processing these Network Admins:
          userName: admin
× Starting business network definition. This may take a minute...
  Error: Error trying to start business network. Error: No valid
  responses from any peers. Response from attempted peer comms was an
  error: Error: REQUEST_TIMEOUT Command failed**

When I seen log using below command :

peer0.org1.example.com .

I attached log error in image file.Log Image File
Can anyone suggest to me how I can proceed next step for start my first Hyper Fabric network?

A: I did the following modification in "docker-compose.yaml" file and restart Docker-compose by using docker-compose stop & docker-compose -start command then I repeat all procedure for create Network mentioned above and  issue has been resolved.
- CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=compose_default
To
- CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=tutorial-network_default
Here "tutorial-network_default" is the network name. You can find your network name by using "docker network ls" command


text:
Q: unable to tick all the check box under a single page I am facing problem to apply loop and tick all the check box under a page.
Kindly suggest me to tick all the check box in page.
Please follow the below steps
1. Go to Url "http://kesdee.com/buyOnline.html"
2. Go to dropdown'Course Groups' and select "Bank Branch Management"
3. tick all the check box under 'View Less' link
4. click all the 'View More' links one by one and tick all the check box
Working on selenium Web Driver using java.
I have tried it by using xpath, id's and classname, but unsuccessful.

A: Try to use selenium.support library.
https://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/support/ui/Select.html
after you can easy do selection of any option from this select. By id, value or index


text:
Q: Computing average on a list of values for each value I have a huge file (50k lines) with the following format:
52370581 2116
17996781 4314
47818829 2584
61421045 2158
...
25145813 2274

The first value can be present multiple times and I want to compute the average of the 2nd value for each 1st value, using the terminal. Ideally, I'd want the median, the min and max too. I can to it on all the values quite easily with awk but I was wondering how to get that done for each value.

A: awk '{c[$1]++;s[$1]+=$2}END{for(i in c)print i,(s[i]/c[i])}' test.in

More readably:
awk '
{ # Every line
    # Increment the key, add value to its sum
    count[$1]++
    sum[$1] += $2
}
END {
    # Go through all the numbers we saw
    for(number in count) {
        # Print the number followed by the average (sum/count) of its values
        print number, (sum[number]/count[number])
    }
}
' test.in

Note that the numbers will be output in a more-or-less random order (some hash of the keys). Getting min and max isn't so bad, just add them after count and sum in the first block. Median requires tracking every number. You can do it with a 2d array (or awk's emulation thereof), but I'll leave it as an exercise to the reader.

A: For avarage
awk '{if(NR==1){i=$1;}} {if($1~i){j+=$2;k++}} END{print "Average is " (j/k)}' <filename>
this will provide you in case you want to do it only for the value in first line. Instead of NR==0, if you pass a variable, you can do it for any line specific case. Now if you want to do it for each line, then below awk will do it in one pass
awk '{value[$1]+=$2;count[$1]++} END{for(indx in value)print "Avarage of " indx " is " (value[indx]/count[indx])}' <filename>
awk has two dimensional array, but i'm not familiar with that, so using 2 arrays to keep sum of the elements and count. Any other operation, we need to change the script based on the operation


text:
Q: how to replace spaces to underscores in java I have a text file named read.txt that says "JAVA PROGRAMMING" and i want to copy it to another file named write.txt and replace the space into underscore like this: "JAVA_PROGRAMMING". Big thanks to anyone who would help :)
My code:
import java.io.*;
import java.util.*;
class Main {
 public static void main(String arg[]) throws Exception {
  FileReader fin = new FileReader("read.txt");
  FileWriter fout = new FileWriter("write.txt");
  int i;
  while ((i = fin.read()) != -1) {
   fout.write(i);
  }
  System.out.println("Successfully copied!");
  fin.close();
  fout.close();
 }
}

A: Revised code with the correct answer:
import java.io.*;
import java.util.*;
class Main {
 public static void main(String arg[]) throws Exception {
  FileReader fin = new FileReader("read.txt");
  FileWriter fout = new FileWriter("write.txt");
  int i;
   while ((i = fin.read()) != -1) {
    if(i!=' '){
       fout.write(i);}
    else{
       fout.write("_");}
    }
   System.out.println("Successfully copied!");
   fin.close();
   fout.close();
   }
  }


text:
Q: Change number of reducers/mappers in DataStax Enterprise How can I change the number of mappers/reducers in Hadoop? For some odd reason, mapred.tasttracker.map.tasks.maximum and mapred.tasttracker.reduce.tasks.maximum are not present in the mapred-site.xml. I did manage to find these settings in dse-mapred-default.xml but once the xml is opened, there's a note which indicates that the settings shouldn't be edited in this file and that the properties should be overridden in mapred-site.xml.
I have tried adding the two settings to the mapred-site.xml and restarting Hadoop and i was expecting the numbers to also be updated in dse-mapred-default.xml but with no luck.
Could someone please shed some light on this?
Thanks
Majd

A: It's not mapred.tasttracker.map.tasks.maximum, but mapred.tasktracker.map.tasks.maximum. I hope it is only a typo and you used correct names in your config.
On startup DSE creates dse-mapred-default.xml and dse-core-default.xml files and fills them with defaults adapted to your local OS configuration and hardware. This is mostly for Hadoop autotuning feature and for simplifying configuring of security-enabled Hadoop. Then Hadoop loads config files in the following order:

*

*Hadoop internal defaults (the defaults you can find in the Hadoop docs)

*DSE defaults from dse-core-default.xml and dse-mapred-default.xml

*User files: core-site.xml and mapred-site.xml.

Settings from files loaded later override settings loaded earlier. The final state of configuration is not written back to the files with defaults. You should not expect settings from mapred-site.xml to be copied into dse-mapred-default.xml files.
If you're unsure what is the final configuration and whether your settings are properly set - just run a job and look into hadoop log directory and search for files matching pattern job_xxxxxxxxxxxx_xxxx_conf.xml, where x is a digit. You can also view the final config in the jobtracker HTTP console.


text:
Q: How to search for source packages? I can use aptitude to search for packages using a search term. For example, to search for all packages whose name begins with Foo:
$ aptitude search Foo*

However, this listing does not include source packages (package with source code).
How do I search and list source packages using a search term?

A: Searching: I don't know how to perform a regex search over source package names using apt on the target machine, but one can perform a regex search over source package names by selecting "Source package names" under "Search package directories" at http://packages.ubuntu.com
Listing: Once you know the source package name 'foo', apt-cache showsrc foo shows the source package records for foo.

A: this is what I do (besides what is listed) using unity as a example
apt-cache policy unity*

or
This is a much larger list that shows you  the control files of packages
   apt-cache show unity*
Or you can use 'dump' to dump everything (not recommended)
apt-cache dump unity*

Or you can use dpkg also like
dpkg-query -l | grep unity*

Or you could use
apt-cache showpkg unity*

Hope this helps


text:
Q: Converting JavaScript Function to XSLT     var epcSum = 0;
    var labourSum = 0;
    var bvatSum = 0;
    var avatSum = 0;
    var vatSum = 0;
    var discount = 0;

    function addToSum(type, amount) {
        try {
            if(type=='A') epcSum += new Number(amount);
            if(type=='B') labourSum += new Number(amount);
            if(type=='C') vatSum += new Number(amount);
            if(type=='D') discount += new Number(amount);
        } catch (e) {}

        return '';
    }

I am not finding the way how to implement "+=" operator and using the global variable inside function . Please anybody help me to convert this javascript function to XSLT template or function.

A: We need to understand the problem you are trying to solve at a higher level. You've shown us some very procedural code that relies on a function having side-effects by updating global variables. That's simply not the way a declarative, functional language like XSLT works. The XSLT code for this problem is probably easier to derive from a high-level requirements statement that from an existing low-level implementation.


text:
Q: The name of ethernet interface for my network Why no enp1s0 ethernet interface in my os?
ip -brief link |cut -d" "  -f1
lo
enp6s0

Why can't get the result ?
ip -brief link |cut -d" "  -f1
lo
enp1s0

A: The ethernet interface name enp6s0 means the PCI bus location (as indicated by e.g. the lspci command) of that NIC is 06:00.0.
If you don't have a network card at PCI bus location 01:00.0, you won't get interface name enp1s0. On many desktop motherboards, the PCI bus location 01:00.0 refers to the first long (16x) PCIe slot, which is the recommended installation location of the first add-on GPU card.
Of course, if you set custom names for your network interfaces, you can name them anything you like, but if you deliberately break the relationship between the enp* names and the corresponding PCI bus locations without a very good reason, you would just cause confusion for yourself (and potentially other administrators of the system) in the future.

A: The naming convention for ethernet interfaces has been changed in some recent distributions of Linux. The interface names are now decided dynamically based on it's drivers.
For an in-depth explanation, see this article.


text:
Q: how to recieve mail using maven javax? I want to receive mail from any specified email id  using javafx but getting an exception that is   MojoExecutionException.
 my pom.xml dependencies and whole source code provided below please help me to solve this problem.
<dependencies>

    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.5.0-b01</version>
        <type>jar</type>
    </dependency>
    <dependency>
<groupId>org.jvnet.mock-javamail</groupId>
<artifactId>mock-javamail</artifactId>
<version>1.9</version>

And my Javax code is
 try {

 Properties properties = new Properties();
 properties.put("mail.pop3.host", pop3Host);
 Session emailSession = Session.getDefaultInstance(properties);

POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
emailStore.connect(user, password);

 //3) create the folder object and open it
 Folder emailFolder = emailStore.getFolder("INBOX");
 emailFolder.open(Folder.READ_ONLY);

 //4) retrieve the messages from the folder in an array and print it
  Message[] messages = emailFolder.getMessages();
 for (int i = 0; i < messages.length; i++) {
 Message message = messages[i];
 System.out.println("---------------------------------");
 System.out.println("Email Number " + (i + 1));
 System.out.println("Subject: " + message.getSubject());
 System.out.println("From: " + message.getFrom()[0]);
 System.out.println("Text: " + message.getContent().toString());
 }

 //5) close the store and folder objects
 emailFolder.close(false);
 emailStore.close();

  } catch (NoSuchProviderException e) {e.printStackTrace();}
  catch (MessagingException e) {e.printStackTrace();}
 catch (IOException e) {e.printStackTrace();}
}

public  void excute() throws MessagingException {

 String host = "xyz.com";//change accordingly
 String mailStoreType = "pop3";
 String username= "xyz@pqr.com";
  String password= "cccccc";

 receiveEmail(host, mailStoreType, username, password);

 }
public void start(Stage stage) throws Exception {

Parent root=FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));

    Scene scene = new Scene(root);
    scene.getStylesheets().add("/styles/Styles.css");

    stage.setTitle("JavaFX and Maven");
    stage.setScene(scene);
    stage.show();
  }
  public static void main(String[] args) throws MessagingException {
     receiveEmail obj=new receiveEmail();
     obj.excute();
     launch(args);
  }


text:
Q: how to know speed of processor fan? i want to detect processors fan speed  is there any Java library to do so.

A: Use sensors. use smbus/i2c/gpio lib.

A: Not sure what platform you're interested in, but on Windows you can use WMI, which provides a class for fan information.  The exact location of the fan information in the WMI repository will depend on your motherboard manufacturer (if they provide it at all), so there is no easy way to get the information without coding specifically for different motherboards.  You can use this tool to browse the repository and see what's available.

A: In pure Java - No. So your options are - Write JNI wrappers for all interested platforms. Search for a command line application that provides this for each platform, and use them.
I would normally add "google to see if anyone else has done this". But I'd guess you have already done this and not found anything. I am not surprised - Java is not normally used for low level stuff like this.

A: You'll have to use JNI or JNA to manipulate the right library on each platform (Windows, Mac, Linux...). For Linux:

Lm-sensors is a hardware health
  monitoring package for Linux. It
  allows you to access information from
  temperature, voltage, and fan speed
  sensors. It works with most newer
  systems.
Homepage: http://www.lm-sensors.org


text:
Q: Why does the FileField in the models need a default? I am using Django and I am trying to create a file uploader and have various FileField in the models. When I try to do,
python manage.py makemigrations

It prompts to set a default for the FileFields, why is it important? It says it is a non-nullable field, but why can't it be null?

A: It's because you did not set null=True in your model. As stated in the documentation, every model field in Django can be null.

A: Bacause the default is both false for null and blank.Check here.


text:
Q: Посчитать площадь под кривой на python Собственно, имеем подобную ломанную кривую хочется найти апроксимирующую функцию, и посчитать площадь под ней. Хочется не наводящие ответы, вроде, посмотри есть math или scipy, а ссылки на то где есть подобная реализация, или хотя бы. Схожее, я новичок, и реализовать самостоятельно подобное не получается.

A: Можно воспользоваться numpy.trapz()
Пример с использованием Numpy:
import numpy as np
from scipy.integrate import simps
from numpy import trapz

x = np.linspace(0, 5, 21)

y = np.pi / np.exp(x)

# dx - растояние между соседними X координатами
area = trapz(y, dx=5/20)

Результат:
In [19]: simps(y, dx=5/20)
Out[19]: 3.1204919857832971

In [20]: trapz(y, dx=5/20)
Out[20]: 3.1366600769000623

График:
In [21]: plt.grid()

In [22]: plt.plot(x, y)
Out[22]: [<matplotlib.lines.Line2D at 0xd5a5c50>]

In [23]: plt.grid()

In [24]: plt.savefig('c:/temp/a.png')


text:
Q: Partial match search of an array in PHP I'm trying to search a multidimensional array for a partial string.  My array looks like this:
$data = array(
    "United Kingdom" => array(
        "AFXX0001" => "Nottingham",
        "AFXX0002" => "Notting Hill",
    ),
    "Germany" => array(
        "ALXX0001" => "Garnottheinem",
        "ALXX0002" => "Tirane",
    ),
);

I'm trying to build a search function that will display all results which meet the partial match requirement.  So far my function looks like this:
function array_find( $needle, $haystack )
{
    foreach ($haystack as $key => $array) {
        foreach ( $array as $key2 => $value ) {
            if (false !== stripos($needle, $value)) {
                $result = $key . ' ' . $value . ' ' . $key2;
                return $result;
            }
        }
    }
    return false;
}

It works, but only if I enter the actual value, eg array_find( 'Nottingham', $data );.
If I do array_find( 'nott', $data ); I would want it to return Nottingham, Notting Hill and Garnottheinem, but instead it returns bool(false).

A: In your stripos() call, you had the needle and haystack reversed.
Then concatenate the result list.
Try this:
function array_find( $needle, $haystack )
{

    $result = '';  //set default value

    foreach ($haystack as $key => $array) {
        foreach ( $array as $key2 => $value ) {
            if (false !== stripos($value,$needle))   // hasstack comes before needle
                {
                $result .= $key . ' ' . $value . ' ' . $key2 . '<br>';  // concat results
                //return $result;
            }
        }
    }

    return $result;
}

A: Error in line:
if (false !== stripos($needle, $value)) {

Solution:
if (false !== stripos($value, $needle)) {

A: $data = array(
    "United Kingdom" => array(
        "AFXX0001" => "Nottingham",
        "AFXX0002" => "Notting Hill",
    ),
    "Germany" => array(
        "ALXX0001" => "Garnottheinem",
        "ALXX0002" => "Tirane",
    ),
);
$search = 'not';

$result = array();
array_walk_recursive(
    $data,
    function($item, $key) use ($search, &$result){
        $result[$key] = (stripos($item, $search) !== false) ? $item : null;
    }
);
$result = array_filter(
    $result
);
var_dump($result);

The equivalent using SPL Iterators rather than array_walk_recursive()
$result = array();
foreach (new RecursiveIteratorIterator(
             new RecursiveArrayIterator($data),
             RecursiveIteratorIterator::LEAVES_ONLY
         ) as $key => $value) {
         echo $key,PHP_EOL;
    $result[$key] = (stripos($item, $search) !== false) ? $item : null;
}


text:
Q: Where are wp's add_rewrite_rule rules saved? Where are Wordpress's add_rewrite_rule rules saved?
I cannot see them in .htaccess file.  Are they in mySql?  If so, which table?
Thanks

A: They are stored in the {your_prefix}options table (wp_options by default) under rewrite_rules.


text:
Q: Is there a better (smoother) transition I can use? I am currently making an 'animated' background for a website where the background image scrolls through after an hour and then resets to its original position to start again. I am currently making the image to appear to be a 360 degree image through some photoshop trickery. Though when testing the scrolling image, I noticed that the image "jerks" into position for each part of the transition. Im looking for something that will be much smoother than the image 'jumping' from pixel to pixel but still remaining very slow. If there is a better option through javascript I am definetly all ears.
Here is what I am currently using for my CSS (div background image sizing will change once the picture Im actually using is finished):
*{
    margin:0;
    padding:0;
    border: 0;
    line-height: 100%;
    font-size: 100%;
}

#container {
    position: relative;
    width: 100%;
    height: 100%;
    background-color: black;
}
#center {
    background-image:url(http://farm4.staticflickr.com/3768/11633218256_30a04f01c3_o.png);
    background-size: contain;
    width: 100%;
    height: 100%;
    position:absolute;
    animation: scroll 3600s;
    animation-timing-function:linear;
    animation-fill-mode:forwards;
    animation-iteration-count:infinite;
}
@keyframes scroll {
0% {right:0%;}
100%{right:100%;}
}

A: You could use jQuery. This gives a nice smooth animation and would also be cross browser compatible.
<!DOCTYPE html>

    <title>Animate</title>

*

*Edit: at such a slow moving speed it appears jerky as well, but not as jerky. If you slow the speed down it will look much better.


text:
Q: Azure ARM Template variable: Get Subscription name property Is there a way to get the current subscriptions name into a variable?
Something like this:
  "variables": {
     "Purpose":  "[subscription().SubscriptionName]"
  },

Visual Studio says "A property of 'subscription' must be one of the following: id, subscriptionId, tenantId." So the above won't work.
I've also found some examples of the "reference" function and tried to use it thus:
"variables": {
   "SubName": "[reference('/subscriptions/subscription().subscriptionId','2015-01-01').outputs.name.value]"
},

But when calling the template it errors with:
function 'reference' is not expected at this location

I'm not sure where I should put it and how I get it into a variable.
In PowerShell, I could do this:
(Get-AzureRmSubscription).subscriptionname
For the sack of interest, we have several subscriptions. The subscription name contains a 3 digit "short code" that is used in the naming of resource groups within the given subscription. It serves no purpose other than make it easier to pinpoint what belongs to what. It is part of our naming convention to help admins (who aren't particularly familiar with Azure) easily see what resources are where.  I know there are other ways like RBAC etc, but Microsoft's incessant credential cookie capture doesn't lend itself to logging in with different credentials to different subscriptions.
Thanks
W.

A: At the time of writing this answer (2016 Oct 16) I'm afraid you can't.
According to the docs, this is what subsbscription() returns:
{
   "id": "/subscriptions/#####",
   "subscriptionId": "#####",
   "tenantId": "#####"
}

So you should expect failing on subscription().SubscriptionName.
In the same doc I linked,  there is a discussion around this in the comments section, see comment #2694777590 where a Microsoftie say:

Ok - I've added a bug to add the name attribute to the subcription() expression.

this was 2016 June 6, So I guess it's on the way.
As a workaround, you could inject the subscription name from the thing that is executing the template. For example if it's PowerShell you could do
$subName = (Get-AzureRmSubscription).subscriptionname
New-AzureRmResourceGroupDeployment ... -SecscriptionName $subName

Also, I don't know what's the purpose of that string manipulation based on subscription name you talked about, but if is to create subscription scoped unique names, a good practice is to use uniqueString(subscription().subscriptionId) as part of the name.

A: The subscription() now does have an additional attribute displayName, according to documentation.
The following should work for you:
"variables": {
    "Purpose": "[subscription().displayName]"
}

A: You should be able to use:
subscription().displayName

(I'll get a bug filed on the VS behavior)

A: I was able to get subscription().subscriptionId to work in a variable my template.
I think this error you are seeing is a result of how Azure reads the template. Based on Microsoft's reference documentation, references cannot be used in variables:

Remarks
The reference function derives its value from a runtime state, and therefore cannot be used in the variables section.

I got the same function 'reference' is not expected at this location until I moved my actual reference call into the body of the template.


text:
Q: Is it possible to add an SSD module to an iMac 27" Late 2012 model to create a fusion drive on that? I have this old iMac 27", model iMac 13,2 (Late 2012).
This computer has a regular hard disk.
I wonder if it is possible to add a SSD disk module to it, to convert the main disk into a fusion drive?

*

*Is that possible? Is that internal space and connector that can be used?

*What SSD disk, adapters or so, I should buy to do that?

A: The Fusion drive was an option for the 2012 27" iMac, so there may be space. The iFixit tear-down for your model shows a caddy that holds both a hard drive and SSD: you'll need to read through it to see whether you're comfortable with taking it all apart -- and more importantly, getting it back together.
If you're not comfortable with the task, then you may want to run an external SSD via USB3 or a Thunderbolt dock of some kind. That should still be faster than the internal hard drive.
I concur with the comment that really, SSDs are cheap enough to buy sufficiently large volumes, making Fusion drives an unnecessary complication.

A: Are you replacing the HDD side of an existing fusion setup? I.e. you already have an apple SSD/NVMe card in the machine already? (E.g. in my Late 2012 iMac 13,2 I had 128GB NVme + 1 TB HDD). If not simple to replace the HDD with SSD for all the speed benefits people have said.
However, if it's already in a fusion setup then you need to decide whether to keep it that way or split / unfuse the drives.
I replaced my HDD with 1TB SSD, did a High Sierra install to fusion config then upgraded to Mojave and then it all went to hell. Maybe if I unfused first it may have gone better... Good luck!


text:
Q: Reverse LinkedList issue in Java Reverse second half of linked list
Suppose we have 1-2-3-4
Output: 1-2-4-3
Suppose we have 1-2-3-4-5
Output: 1-2-3-5-4    // however I want the output to be 1-2-5-4-3 in the odd condition, how to modify the code below?
public static ListNode reverseSecondHalfList(ListNode head) {
    if (head == null || head.next == null)      return head;
    ListNode fast = head;
    ListNode slow = head;
    while (fast.next != null && fast.next.next != null) {
        fast = fast.next.next;
        slow = slow.next;
    }
    ListNode pre = slow.next;
    ListNode cur = pre.next;
    while (cur != null) {
        pre.next = cur.next;
        cur.next = slow.next;
        slow.next = cur;
        cur = pre.next;
    }
    return head;
}

My method: Firstly find the start position to be swapped, then swap "pre" node and "cur" each time until cur.next!=null

A: Try this
    public static ListNode reverseSecondHalfList(ListNode head) {
    if (head == null || head.next == null)      return head;

    // Add one more node before head, it will help us find the node which before mid note.
    ListNode newHead  = new ListNode(0);
    newHead.next= head;
    ListNode fast = newHead;
    ListNode slow = newHead;
    while (fast.next != null && fast.next.next != null) {
        fast = fast.next.next;
        slow = slow.next;
    }
    ListNode pre = slow.next;
    ListNode cur = pre.next;
    while (cur != null) {
        pre.next = cur.next;
        cur.next = slow.next;
        slow.next = cur;
        cur = pre.next;
    }
    return head;
}

And I extract some code from one method make code cleaner
  public static ListNode reverseSecondHalfList2(ListNode head) {
    if (head == null || head.next == null)      return head;

    ListNode preMid = getPreMidListNode(head);
    reverse(preMid);
    return head;
}

private static void reverse(ListNode preMid) {
    ListNode pre = preMid.next;
    ListNode cur = pre.next;
    while (cur != null) {
        pre.next = cur.next;
        cur.next = preMid.next;
        preMid.next = cur;
        cur = pre.next;
    }
}

private static ListNode getPreMidListNode(ListNode head) {
    // Add one more node before head, it will help us find the node which before mid note.
    ListNode newHead  = new ListNode(0);
    newHead.next= head;
    ListNode fast = newHead;
    ListNode slow = newHead;
    while (fast.next != null && fast.next.next != null) {
        fast = fast.next.next;
        slow = slow.next;
    }
    return slow;
}


text:
Q: Determining all $f : \Bbb R \to\Bbb R$ satisfying $f\bigl(f(x)f(y)\bigr)+f(x+y)=f(xy)$
Let $\Bbb R$ be the set of real numbers. Determine all functions $f : \Bbb R \to\Bbb R$ such that, for all real numbers $x$ and $y$,
$$f\bigl(f(x)f(y)\bigr)+f(x+y)=f(xy)\text.$$

My attempt: Let's first find some partial answers. If this equation has some polynomial answers of degree $d$ then the coefficient of $x^d$ must be equal at both sides i.e. we must have
$$\max\left\{d^2,d\right\}=d$$
which leads to
$$d=0,1$$
now let's take the general answer of polynomial kind as
$$f(x)=ax+b$$
for some $a$ and $b$. Substituting this in the equation leads to
$$f\left(a^2xy+b^2+abx+aby\right)+ax+ay+b=axy+b$$
which leads to
$$a^3xy+ab^2+a^2bx+a^2by+b+ax+ay=axy$$
finally we obtain one trivial answer $a=b=0$ and two non-trivial answers
$$a=-b=1\\a=-b=-1$$
therefore the only non-trivial polynomials satisfying the equation above are
$$f(x)=x-1\\f(x)=-x+1$$
I believe these are the only answers of the question. Here turns out two questions:

*

*Are there any other answers except those I found?

*If so, what are they?

A: If $f$ is continuous, then $0,-x+1$, and $x-1$ are the only possible functions.
Assume $b \in \mathbb{R}$ is such that $f(b) = 0$. Then $y=b \implies f(0)+f(x+b) = f(xb)$ for all $x \in \mathbb{R}$. Now unless $b=1$, we can let $x = \frac{b}{b-1}$ so that $x+b = xb$ and thus $f(0)=0$. But then $y=0 \implies f(0)+f(x) = f(0)$ for all $x \in \mathbb{R}$, i.e. $f \equiv 0$. Hence, we may assume $f(b) = 0 \implies b=1$.
Now $x=y=0$ implies $f(0)^2 = 1$. Assume $f(0) = 1$. [The case $f(0) = -1$ follows from replacing $f$ by $-f$, which is a symmetry the main functional equation respects]. Then, $y=1 \implies f(x+1) = f(x)-1$ for each $x \in \mathbb{R}$. Then $f(0) = 1 \implies f(x) = -x+1$ for all $x \in \mathbb{Z}$.
Also, for each $x \not = 1$, letting $y = \frac{x}{x-1}$ gives that $f(f(x)f(\frac{x}{x-1})) = 0 \implies f(x)f(\frac{x}{x-1}) = 1$. Letting $x = \frac{1}{2}$ shows $f(\frac{1}{2}) = \frac{1}{2}$ and $f(x+1) = f(x)-1$ gives that $f(\frac{k}{2}) = -\frac{k}{2}+1$ for each $k \in \mathbb{Z}$. It's then an easy induction (on the size of denominator), using $f(x)f(\frac{x}{x-1}) = 1$, to conclude that $f(\frac{p}{q}) = -\frac{p}{q}+1$ for each $p,q \in \mathbb{Z}, q \not = 0$. [The point is that $\frac{x}{x-1}$ at $x = \frac{p}{q}$ is $\frac{p}{p-q}$ which has denominator smaller than $q$ in absolute value.]
Hence, $f(x) = -x+1$ for each $x \in \mathbb{Q}$, and if $f$ is continuous, this extends to all $x \in \mathbb{R}$.


text:
Q: XMPPFramework: Sending a message with timeout I'm using XMPPFramework in my iOS app to send and receive command messages between client and server. The server would answer to different command messages immediately.
Sometime the connection is very slow, the message sent from client would have no response for a long time. So I want to know how can I send an XMPP message with timeout or I have to implement this myself.
Anyway:

*

*This goes to - (void)xmppStream:(XMPPStream *)sender didSendMessage:(XMPPMessage *)message.

*Using Reachability, the internet is still reachable via [[Reachability reachabilityForInternetConnection] isReachable].

A: Why not just set a timer when you send the message, override the response callback on the XMPPStream, and see which is called first?


text:
Q: d3js v4: Add nodes to force-directed graph I would like to render a force-directed graph in d3js v4 and provide a function for dynamically adding new nodes and links to the simulation. My first attempt (see below) still has some major issues:

*

*Already existing nodes and links seem to be ignored by the force
simulation after adding a link

*The bindings between simulation nodes and links and their SVG counterparts somehow doesn't work

I think I know all the examples (e.g., [1,2]) demonstrating similar functionality for v3, but I would like to do it with v4.
Thanks for your help!
index.html
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>D3 Test</title>

        <button class="expand">Expand graph</button>

graph.js
var Graph = function(targetElement, graph) {

    var self = this,

        width = targetElement.offsetWidth,

        height = width / 2,

        svg = d3.select(targetElement).append('svg')
            .attr("width", width)
            .attr("height", height),

        simulation = d3.forceSimulation()
                       .force("link", d3.forceLink().id(function(d) { return d.id; }))
                       .force("charge", d3.forceManyBody())
                       .force("center", d3.forceCenter(width / 2, height / 2)),

        link = svg.append("g")
                  .attr("class", "links")
                  .selectAll("line"),

        node = svg.append("g")
                  .attr("class", "nodes")
                  .selectAll("circle"),

        update = function() {

            // Redefine and restart simulation
            simulation.nodes(graph.nodes)
                      .on("tick", ticked);

            simulation.force("link")
                      .links(graph.links);

            // Update links
            link = link.data(graph.links);

            // Enter links
            link = link.enter().append("line");

            // Exit any old links
            link.exit().remove();

            // Update the nodes
            node = node.data(graph.nodes);

            // Enter any new nodes
            node = node.enter().append("circle")
                       .attr("r", 5)
                       .call(d3.drag()
                            .on("start", dragstarted)
                            .on("drag", dragged)
                            .on("end", dragended));

            // Exit any old nodes
            node.exit().remove();

            function ticked() {
                link
                    .attr("x1", function(d) { return d.source.x; })
                    .attr("y1", function(d) { return d.source.y; })
                    .attr("x2", function(d) { return d.target.x; })
                    .attr("y2", function(d) { return d.target.y; });

                node
                    .attr("cx", function(d) { return d.x; })
                    .attr("cy", function(d) { return d.y; });
            }

        },

        dragstarted = function(d) {
            if (!d3.event.active) simulation.alphaTarget(0.3).restart();
            d.fx = d.x;
            d.fy = d.y;
        },

        dragged = function(d) {
            d.fx = d3.event.x;
            d.fy = d3.event.y;
        },

        dragended = function(d) {
            if (!d3.event.active) simulation.alphaTarget(0);
            d.fx = null;
            d.fy = null;
        },

        expandGraph = function(links, nodes) {

            for (var i=0; i < nodes.length; i++) {
                console.log('adding node', nodes[i]);
                graph.nodes.push(nodes[i]);
            }

            for (var i=0; i < links.length; i++) {
                console.log('adding link', links[i]);
                graph.links.push(links[i]);
            }

            update();

        };

        // Public functions
        this.expandGraph = expandGraph;

    update();

};

A: You forgot to merge() your nodes. I have updated your code quickly:
graph.js
var Graph = function(targetElement, graph) {

var self = this,

    width = targetElement.offsetWidth,

    height = width / 2,

    svg = d3.select(targetElement).append('svg')
        .attr("width", width)
        .attr("height", height),

    simulation = d3.forceSimulation()
                   .force("link", d3.forceLink().id(function(d) { return d.id; }))
                   .force("charge", d3.forceManyBody())
                   .force("center", d3.forceCenter(width / 2, height / 2)),

    linkGroup = svg.append("g")
              .attr("class", "links"),

    nodeGroup = svg.append("g")
              .attr("class", "nodes"),

    update = function() {

        // Redefine and restart simulation
        simulation.nodes(graph.nodes)
                  .on("tick", ticked);

        simulation.force("link")
                  .links(graph.links);

        // Update links
        link = linkGroup
            .selectAll("line")
            .data(graph.links);

        // Enter links
        linkEnter = link
            .enter().append("line");

        link = linkEnter
            .merge(link);

        // Exit any old links
        link.exit().remove();

        // Update the nodes
        node = nodeGroup.selectAll("circle").data(graph.nodes);

        // Enter any new nodes
        nodeEnter = node.enter().append("circle")
                   .attr("r", 5)
                   .call(d3.drag()
                        .on("start", dragstarted)
                        .on("drag", dragged)
                        .on("end", dragended));

        node = nodeEnter.merge(node);

        // Exit any old nodes
        node.exit().remove();

        function ticked() {
            link
                .attr("x1", function(d) { return d.source.x; })
                .attr("y1", function(d) { return d.source.y; })
                .attr("x2", function(d) { return d.target.x; })
                .attr("y2", function(d) { return d.target.y; });

            node
                .attr("cx", function(d) { return d.x; })
                .attr("cy", function(d) { return d.y; });
        }

    },

    dragstarted = function(d) {
        if (!d3.event.active) simulation.alphaTarget(0.3).restart();
        d.fx = d.x;
        d.fy = d.y;
    },

    dragged = function(d) {
        d.fx = d3.event.x;
        d.fy = d3.event.y;
    },

    dragended = function(d) {
        if (!d3.event.active) simulation.alphaTarget(0);
        d.fx = null;
        d.fy = null;
    },

    expandGraph = function(links, nodes) {

        for (var i=0; i < nodes.length; i++) {
            console.log('adding node', nodes[i]);
            graph.nodes.push(nodes[i]);
        }

        for (var i=0; i < links.length; i++) {
            console.log('adding link', links[i]);
            graph.links.push(links[i]);
        }

        update();

    };

    // Public functions
    this.expandGraph = expandGraph;

update();

};

Actually I don't understand this new function 100%, but you always need to merge your new links and nodes (i.e. linkEnter and nodeEnter) with your existing graph. If you don't do this, your old Graph kind of dies...
Mike Bostock made an example how to use merge here:
https://bl.ocks.org/mbostock/3808218


text:
Q: MongoDB $switch case match with $regex I want use $addFields based on regex match in switch case.
Logic is if title match regex then return title or if firstName and lastName match regex then return firstName and lastName with $concat.
I have some more case here is two for example.
I tried below way but not sure how to achieve this.
Playground for Test: Link
{
    $addFields: {
        text: {
            $switch: {
                branches: [
                {
                    case: { title: { $regex: "search", $options: 'i' } }, then: '$title' },
                {
                    case: {
                        $or: [
                            { 'user.firstName': { $regex: "search", $options: 'i' } },
                            { 'user.lastName': { $regex: "search", $options: 'i' } },
                        ],
                    },
                    then: { $concat: ['$user.firstName', ' ', '$user.lastName'] },
                },
                ],
            },
        },
    },
},

OR
{ case: { $eq: ['$title', { $regex: search, $options: 'i' }] }, then: '$title' },

Sample Data for Try
[
  {
    "_id": "628c774c0ffe2cd088654ddd",
    "title": "project 1 test",
    "user": {
      "firstName": "cust",
      "lastName": "cust"
    }
  },
  {
    "_id": "628e08bbc92d4b969cf4c92e",
    "title": "test 3",
    "user": {
      "firstName": "test",
      "lastName": "cust"
    }
  },
  {
    "_id": "62971ae1d4e0df6adade2998",
    "title": "test new project optimise",
    "user": {
      "firstName": "cust",
      "lastName": "cust"
    }
  },
  {
    "_id": "629ed780d1e6eabef7b82c70",
    "title": "test 1 project",
    "user": {
      "firstName": "test",
      "lastName": "test"
    }
  },
  {
    "_id": "629776b5d4e0df6adade3283",
    "title": "test pro",
    "user": {
      "firstName": "cust",
      "lastName": "cust"
    }
  },
  {
    "_id": "62971d80d4e0df6adade2b96",
    "title": "new project invite",
    "user": {
      "firstName": "cust",
      "lastName": "cust"
    }
  },
  {
    "_id": "6294b28b045eeaa3a8db88b5",
    "title": "final test",
    "user": {
      "firstName": "cust",
      "lastName": "cust"
    }
  }
]

A: Finally i got some solution.
Still i will look forward for better suggestions.
{
    $addFields: {
      text: {
        $switch: {
          branches: [
            {
              case: { $eq: [true, { $regexMatch: { input: '$title', regex: search, options: 'i' } }] },
              then: '$title',
            },
            {
              case: {
                $eq: [
                  true,
                  {
                    $or: [
                      { $regexMatch: { input: '$user.firstName', regex: search, options: 'i' } },
                      { $regexMatch: { input: '$user.lastName', regex: search, options: 'i' } },
                    ],
                  },
                ],
              },
              then: { $concat: ['$user.firstName', ' ', '$user.lastName'] },
            },
          ],
        },
      },
    },
},


text:
Q: Foursquare API get venue longitude and latitude Can I use the foursquare API to get the venue coordinates ( longitude and latitude ) based on the venue name (or maybe address)?
I'm new in this, so any help and tips will be appreciated.
Thanks

A: Generally the Foursquare API excels at translating from a given lat/lon to venues that are nearby. However, if you have the Foursquare venue ID of the venue in question, you can very easily grab the lat/lon of this place from a venue detail response.
If you don't have the ID and still want to go from name => lat/lon, you can always use venues/search and pass in the venue name as the query param. Supplying intent=match will also give you better results for exact name matches.


text:
Q: path string wise match redirection in htaccess How to redirect the path using string compare.
For example: We have path like (1000+ redirections)
www.example.com/kb-123
www.example.com/kb-555
www.example.com/kb-666

Now using single rule how to redirect all above path's into below path's?
www.example.com/article/kb-123
www.example.com/article/kb-555
www.example.com/article/kb-666

A: Try with below rule,
RewriteEngine On
RewriteCond %{REQUEST_URI} ^(.+)
RewriteRule ^ /article/%1 [R=301,L]


text:
Q: How to set more that one node property using Cypher in Memgraph? When I want to set a node property value, I use
MATCH (c:City)
WHERE c.name = 'London'
SET c.population = 8900000
RETURN c;

How can I set more than one property within code block?

A: To set more than one property divide the properties with coma, like this:
MATCH (c:City)
WHERE c.name = 'London'
SET c.population = 8900000, c.country = 'United Kingdom'
RETURN c;


text:
Q: vue wrap another component, passing props and events How can I write my component to wrap another vue component, while my wrapper component get some extra props? My wrapper template component should be:
<wrapper-component>
   <v-table></v-table>
</wrapper-component>

and the wrapper props:
props: {
  prop1: String,
  prop2: String
}

Here I want to wrap a table component, and pass to the table component all the props and events that were passed to the wrapper, beside two extra props prop1 and prop2. What is the correct way of doing this in vue?
 And is there a solution for events too?

A: Place the component you wish to wrap into the template of the wrapper component, add v-bind="$attrs" v-on="$listeners" to that component tag, then add the inner component (and, optionally, inheritAttrs: false) to the wrapper component's config object.
Vue's documentation doesn't seem to cover this in a guide or anything, but docs for $attrs, $listeners, and inheritAttrs can be found in Vue's API documentation. Also, a term that may help you when searching for this topic in the future is "Higher-Order Component" (HOC) - which is basically the same as your use of "wrapper component". (This term is how I originally found $attrs)
For example...

<template>

        <v-table v-bind="$attrs" v-on="$listeners"></v-table>

</template>

Edit: Alternatively, you may want to use dynamic components via the is attribute so you can pass in the component to be wrapped as a prop (closer to the higher-order component idea) instead of it always being the same inner component. For example:

<template>

        <component :is="wraps" v-bind="$attrs" v-on="$listeners"></component>

</template>

Edit 2: The part of OP's original question that I missed was passing all props EXCEPT one or two. This is handled by explicitly defining the prop on the wrapper. To quote the documentation for $attrs:

Contains parent-scope attribute bindings (except for class and style) that are not recognized (and extracted) as props

For example, example1 is recognized and extracted as a prop in the snippet below, so it doesn't get included as part of the $attrs being passed down.

Vue.component('wrapper-component', {
  template: `

        <component :is="wraps" v-bind="$attrs" v-on="$listeners"></component>

  `,
  // NOTE: "example1" is explicitly defined on wrapper, not passed down to nested component via $attrs
  props: ['wraps', 'example1']
})

Vue.component('posts', {
  template: `

Posts component

  `,
  props: ['example1', 'example2', 'example3'],
})

new Vue({
  el: '#app',
  template: `
    <wrapper-component wraps="posts"
      example1="example1"
      example2="example2"
      example3="example3"
    ></wrapper-component>
  `,
})


text:
Q: ADMM Heuristic or rather stick to Branch and Bound? I'm intending on giving  a solution to this MIQP, which should be faster than the one of solving the exact problem with GUROBI or CPLEX.(It muss not give always the global solution!)
The main problem is about optimization of a localization problem with a grid map, where $dx_m$, $dy_m$ and $dp_m$ are the displacement for the next iteration.
The constraint (2) guarantees that transmit power stays in the admissible range [$\overline{P}$, $\underline{P}$], while the constraints (3) and (4) assure that the update points stay in the range [$-w$,$w$], i.e in the observation area ($q_m$ and $r_m$ are respectively $dx_m$ and $dy_m$ from the previous iteration). The constraints (5) and (6) allow an update of maximal $\delta_i$. N and M are given integer numbers.
\begin{align}
&\quad\min_{s_m,dx_m,dy_m,dp_m} \ \sum_{k=1..K} (f_k+\sum_{m=1..M}a_{km}dx_m+b_{km}dy_m+c_{km}dp_m)^2 \\
&\quad \text{s.t} \ dx_m,dy_m,dp_m \in \mathbb{R} \ (1)\\
&\quad s_m\underline{P} \leq dp_m \leq s_m \overline{P} \  (2)\\
&\quad -s_m(w+q_m) \leq dx_m \leq-s_m(w-q_m) \ (3)\\
&\quad -s_m(w+r_m) \leq dy_m \leq-s_m(w-r_m) \ (4)\\
&\quad -s_m \delta_i \leq dx_m \leq s_m \delta_i  (5)\\
&\quad -s_m \delta_i \leq dy_m \leq s_m \delta_i \ (6)\\
&\quad s_m \in \text{{0,1}}     \ \ \ \ \ (7)\\
&\quad \sum_{m=1..M} s_m = N \ (8)
 \end{align}
I tried the ADMM  heuristic presented in the paper below. Since i couldn' transform the problem in the exact form presented there, I simpliefied the problem to a BIQP and tryed out the algorithm, which unfortunately gave very often no solution(or a very bad one).
Should I keep trying to find an ADMM heuristic which possibly offers a faster solution given a big number of grid points(equations) or stick to the branch and bound algorithms?

1.Reza Takapoui, Nicholas Moehle, Stephen Boyd and Alberto Bemporad :
   A simple effective heuristic for embedded mixed-integer quadratic programming


text:
Q: Why (1.1-1.0)*10 isn't 1.0? Why result of this code is false? I can't solve this problem.
#include <stdio.h>
int main(int argc, char **argv)
{
if ( (1.1 - 1.0)*10.0 - 1.0 == 0.0 )
    printf("True");
else
    printf("False");
return 0;
}

A: Chasing equality in floating point is mostly a fools game.
Best you can do is decide upon a delta that's 'close enough' and compare with that.
google told me to read this for more information:  http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

A: But this works as you wanted:
int main(int argc, char **argv)
{
    float x,y;
    x=0.0;
    y=0.0;

    x=1.1 - 1.0;
    x=x*10.0;
    x=x-1.0;

    if (   x==y )
        printf("True");
    else
        printf("False");
    return 0;
}

A: Most double math uses a binary floating point representation.  So 1.1 is not exactly representable - just something close to it.  Consider the following which uses volatile to prevent compiler optimizations.
#include <stdio.h>
int main(void) {
  volatile double wpw = 1.1;
  volatile double one = 1.0;
  volatile double ten = 10.0;
  printf("%.20e\n", wpw);
  printf("%.20e\n", wpw - one);
  printf("%.20e\n", (wpw - one) * ten);
  printf("%.20e\n", (wpw - one) * ten - one);
  return 0;
}

And it output below.  1.1 - 1.0 is only approximately 0.1.
1.10000000000000008882e+00
1.00000000000000088818e-01
1.00000000000000088818e+00
8.88178419700125232339e-16


text:
Q: Xamarin Forms Login page is not connecting to my web service Hello I am working on a Xamarin forms app that has a login screen when the user puts in the username and password and clicks the login button its supposed to validate with my web service. however it's not doing that I just get the login failed message
EDIT: Now I get a crash on iOS with the following error:

The certificate for this server is invalid. You might be connecting to
  a server that is pretending to be "service.brainstorminstruments.com"
  which could put your confidential information at risk.

heres my xaml code:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="LoginNavigation.LoginPage" Title="Login">
    <ContentPage.ToolbarItems>
        <ToolbarItem Text="Sign Up" Clicked="OnSignUpButtonClicked" />
    </ContentPage.ToolbarItems>
    <ContentPage.Content>
        <StackLayout VerticalOptions="StartAndExpand">
            <Label Text="Username" />
            <Entry x:Name="usernameEntry" Placeholder="username" />
            <Label Text="Password" />
            <Entry x:Name="passwordEntry" IsPassword="true" />
            <Button Text="Login" Clicked="OnLoginButtonClicked" />
            <Label x:Name="messageLabel" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

EDIT I was using the wrong class
heres the code behind:
using System;
using System.Collections.Generic;
using System.Net.Http;
using Newtonsoft.Json;
using Xamarin.Forms;

namespace LoginNavigation
{
    public partial class LoginPage : ContentPage
    {
        public LoginPage ()
        {
            InitializeComponent ();
        }

        async void OnSignUpButtonClicked (object sender, EventArgs e)
        {
            await Navigation.PushAsync (new SignUpPage ());
        }

        async void OnLoginButtonClicked (object sender, EventArgs e)
        {

var postContent = new FormUrlEncodedContent(new[] {
                        new KeyValuePair<string, string>("username","usernameEntry"),
                        new KeyValuePair<string, string>("password","passwordEntry")
                    });

var httpClient = new HttpClient();
var serverResponse = await httpClient.PostAsync("https://service.brainstorminstruments.com/api/login", postContent);
var serverResponseString = await serverResponse.Content.ReadAsStringAsync();

//theEditor.Text = serverResponseString;

Response theResponseObject = JsonConvert.DeserializeObject<Response>(serverResponseString);

                if (theResponseObject.status == "success") {
                App.IsUserLoggedIn = true;
                Navigation.InsertPageBefore (new MainPage (), this);
                await Navigation.PopAsync ();
            } else {
                messageLabel.Text = "Login failed";
                passwordEntry.Text = string.Empty;
                theEditor.Text += theResponseObject.status + "\n";
                theEditor.Text += theResponseObject.message + "\n";

            }
        }

    }
}

i'm new to http client so any help would be amazing!
Thanks in advance!

A:
The certificate for this server is invalid. You might be connecting to a server that is pretending to be "service.brainstorminstruments.com" which could put your confidential information at risk.

Out of all the items list below, without the full error being produced or knowing what iOS version you are working on (assuming it is iOS10), I am going to assume that date/time on your device or macOS is incorrect.
This can also be caused by multiple issues:

*

*Is the device date/time wrong, or if running on a simulator is the date/time on your macOS correct

*Using a self-signed cert signed

*No valid root certificate for the certificate chain.
List of available trusted root certificates in iOS 10

*

*https://support.apple.com/en-us/HT207177
Apple's HTTPS Server Trust Evaluation:

*

*https://developer.apple.com/library/content/technotes/tn2232/_index.html
Note: Your service does fail the ssllabs.com evaluation in a number of areas for supporting insecure ciphers but that will not cause iOS to fail.

*

*https://www.ssllabs.com/ssltest/analyze.html?d=service.brainstorminstruments.com&hideResults=on


text:
Q: Search Multidimensional Array (Flash As3) using another array for search criteria Long story short: I want to search a multidimensional array in AS3 for (in this example) the location of 6 strings - all of which are stored in another unrelared array.
Long story long:
Once I get the locations (in the multidimensional array) of each string, i then know where it's located, and can access other atributes of that object - so if i found the string "box3" is located in element [5] of my multidimensional array, i can now target:
multiArray[5][3] to return the 4th item stored (keeping in mind we're starting from 0, so 3 is the 4th position).
I can get this to work once, but I'm trying to set up a for loop based on the length of my basic string storage array - this array holds (in this example) 6 instance name strings - each time my for loop loops, i need to run a search in my multdimensional array for the next consecutive instance name.
Then, once I've located all of them (and store the results in a new temporary array) I can dig around in each location for the info I need.
The only thing I can find is the post here:
http://exoboy.wordpress.com/2010/07/15/successfully-searching-multidimensional-arrays-in-as3/
which works GREAT if I'm only searching for one elements in my array - but soon as I need to find multiple elements in a for loop using their code it falls apart. You can see my question/their response on that page as well for some more info.
I need a simple to run function in the end that can be re-used over and over as I'll be doing a lot of searching in that array for the simulation i'm building. Thanks everyone,
-Eric

A: I guess you need two for loops then.
use one loop for the searching in the array (that's the loop code you already have), and wrap it in another for loop which executes that searchloop.
Makes sense?

A: Here is the base function you could use.
Obviously you will need to loop all your arrays calling this function for the test.
function arrayContains( haystack:Array, needle:String ):Boolean{
  for( var i:Number = 0;i < haystack.length; i++ ) {
    if( needle == haystack[i] ) {
      return true;
    }
  }
  return false;
}

// sample code
var myArray:Array = new Array();
myArray.push(["granola","people... are great"," 4 ","10"]);
myArray.push(["bill","orangutan","buster","keaton"]);
myArray.push(["steve","gates","24","yes, sometimes"]);
myArray.push(["help","dave","jobs","hal"]);

var searchArray:Array = ["granola","orangutan","24","hal"];

for each( var arr:Array in myArray ){
  for each( var searchString:String in searchArray ){
    if( arrayContains( arr, searchString ) ){
      trace( 'found ' + searchString + 'in myArray at ' + myArray.indexOf(arr)  )
    }
  }
}

A: This version loops using the method itself, searchArray(), and keeps track of the position in the tree. Once it finds a match, it outputs the position to searchResults. Then you can use getNestedItem() with each array of uints to retrieve the value.
package
{
    import flash.utils.getQualifiedClassName;

    public class NestedSearch
    {
        private var _multidimensionalArray :Array =
            [
                //[0]
                [
                    // [0]
                    // [0],  [1],    [2]
                    ["one", "two", "three" ],
                    // [1]
                    // [0],  [1],    [2]
                    ["eleven", "twelve", "thirteen" ]
                ],
                //[1]
                [
                    // [0]
                    // [0],  [1],    [2]
                    ["hyena", "iguana", "jackal" ],
                    // [1]
                    "koala"
                ]
            ];

        private var queries :Array = new Array( "three", "twelve", "hyena", "koala" );

        private var searchResults :Array = [];

        public function NestedSearch()
        {
            // Make multiple queries
            for ( var q in queries)
            {
                searchArray( queries[ q ], _multidimensionalArray, [] );
            }

            // Use the results
            for ( var i in searchResults )
            {
                trace( 'Found "' + searchResults[ i ].query +
                      '" at _multidimensionalArray[' + searchResults[ i ].position + ']');
                trace( "Test value: " + getNestedItem( _multidimensionalArray, searchResults[ i ].position ));
            }
        }

        // Searches any array for an exact String value.
        // Returns the found string as an Array of uints representing its position in the tree.
        public function searchArray ( s:String, a:Array, positionPath:Array )
        {
            // Duplicate array to save it before going back out
            var _origPosPath = positionPath.concat();

            for ( var i in a )
            {
                if ( getQualifiedClassName( a[ i ] ) === "Array")
                {
                    positionPath.push(i);
                    searchArray( s, a[ i ], positionPath );
                    positionPath = _origPosPath;
                }
                else
                {
                    if ( a[ i ] === s)
                        searchResults.push( {query: s, position: positionPath.concat( i )} );
                }
            }
        }

        private function getNestedItem ( arr:Array, pos:Array ) :*
        {
            var nestedItem;
            var p = pos.shift();
            if ( pos.length === 0 )
            {
                nestedItem = arr[ p ];
            }
            else
            {
                nestedItem = getNestedItem( arr[ p ], pos );
            }
            return nestedItem;
        }

    }
}


text:
Q: How can DateObject handle calender weeks I have dates given for a TimeLinePlot. These dates are in {year,week} format.
DateObject does not take this with DateObject[{2014,26},DateFormat->{"Year","Week"}]. DateFormat should handle DateString format. There the week is given as option.
Does anyone have an idea how to make it work?

A: Note This answer exposed a bug in DateList's handling of the "Week" (or "WeekShort") element for week one when it begins in the previous year.  This was spotted by @ChrisDegnen (see the comments) and has been acknowledged by Wolfram who suggested the workaround.

I don't believe DateObject has a concept of a week as a period of time in the same way that it seems to for a year, month or day, so I think the best you can do is a DateObject for the first day of the week.
And since the DateFormat option for DateObject is the display format rather than an interpretation format we use DateList to do the conversion...
fromYearWeek[{y_Integer, w_Integer}] :=
 DateObject[
  DatePlus[DateList[{ToString[y] <> "-" <> ToString[w], {"Year",
      "Week"}}], 1], DateFormat -> {"ISOWeekDate"}]
fromYearWeek[{y_Integer, 1}] :=
 DateObject[
  DatePlus[DateList[{ToString[y] <> "-2", {"Year",
      "Week"}}], -6], DateFormat -> {"ISOWeekDate"}]

Note that I have added a day to convert to ISO weeks which begin on a Monday and changed the DateObject display format to indicate the week number.
It includes a special case for week one - calculating the date list for week two and subtracting 6 days.

A: You could use DateList to work out the date.  For example, (naïvely assuming week 1 begins on January 1st).
{year, week} = {2014, 26};

date = DateList[{year, 1, (week - 1)*7 + 1}]

{2014, 6, 25, 0, 0, 0.}

For example:
dates = {{2014, 2}, {2014, 8}, {2014, 16}, {2014, 26}};
values = {4, 6, 3, 8};
newdates = DateList[{#1, 1, (#2 - 1)*7 + 1}] & @@@ dates;
DateListPlot[Transpose[{newdates, values}]]

Edit
Using ISO weeks and adjusting accordingly.  (ISO week is taken to be "the week with the year's first Thursday in it ", so week 1 of 2014 begins on December 30th 2013.)

isodate[{year_, week_}] := Module[{isoAdjust },
  isoAdjust = Cases[Map[{#, DateString[{year, 1, #},
          "DayNameShort"]} &, Range[7]], {_, "Thu"}][[1, 1]] - 3;
  DateList[{year, 1, (week - 1)*7 + isoAdjust}]]

isodate[{2014, 1}]

{2013, 12, 30, 0, 0, 0.}

isodate[{2014, 26}]

{2014, 6, 23, 0, 0, 0.}

newdates = isodate /@ dates;
DateListPlot[Transpose[{newdates, values}]]


text:
Q: Error while build ffmpeg for iOS I'm trying to build fmmpeg for iOS with the following config:

./configure --prefix=build/armv7 --disable-ffmpeg --disable-ffplay --disable-ffprobe --disable-ffserver --enable-avutil --enable-avresample --enable-cross-compile --sysroot="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk" --target-os=darwin --cc=gcc  --extra-cflags="-arch armv7 -mfpu=neon -miphoneos-version-min=6.0" --extra-ldflags="-arch armv7 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk -miphoneos-version-min=6.0" --arch=arm --cpu=cortex-a9 --enable-pic

when i try to make it i'm receiving the follow error:

AS  libavcodec/arm/vc1dsp_neon.o
libavcodec/arm/vc1dsp_neon.S:751:10: error: unexpected token in argument list
  ra .dn d28.i8
         ^
libavcodec/arm/vc1dsp_neon.S:752:10: error: unexpected token in argument list
  rb .dn d29.i8
         ^
libavcodec/arm/vc1dsp_neon.S:753:10: error: unexpected token in argument list
  rc .dn d30.i8
         ^
libavcodec/arm/vc1dsp_neon.S:754:10: error: unexpected token in argument list
  rd .dn d31.i8
         ^
libavcodec/arm/vc1dsp_neon.S:757:14: error: invalid operand for instruction
        vmov ra, #4
             ^
libavcodec/arm/vc1dsp_neon.S:758:14: error: invalid operand for instruction
        vmov rb, #53
             ^
libavcodec/arm/vc1dsp_neon.S:759:14: error: invalid operand for instruction
        vmov rc, #18
             ^
libavcodec/arm/vc1dsp_neon.S:760:14: error: invalid operand for instruction
        vmov rd, #3
             ^
libavcodec/arm/vc1dsp_neon.S:864:10: error: unexpected token in argument list
  ra .dn d28.i16
         ^
libavcodec/arm/vc1dsp_neon.S:865:10: error: unexpected token in argument list
  rb .dn d29.i16
         ^

what could be the error?

A: Try adding the flags --disable-neon and --disable-armv5te.
BTW, the following set of flags does the trick for AMRv7:
'--arch=arm',
'--enable-pic',
"--extra-cflags='-arch armv7 -miphoneos-version-min=6.0'",
"--extra-ldflags='-arch armv7 -miphoneos-version-min=6.0'",
'--disable-neon',
'--enable-optimizations',
'--disable-debug',
'--disable-armv5te',
'--disable-armv6',
'--disable-armv6t2',

'--disable-ffmpeg',
'--disable-ffplay',
'--disable-ffserver',
'--disable-ffprobe',
'--disable-doc',
'--disable-bzlib',
'--target-os=darwin',
'--enable-cross-compile',
'--enable-version3',

Or, event better, you change the version of gas-preprocessor you have to the libAV maintained version: https://github.com/libav/gas-preprocessor
Hope this helps.


text:
Q: JSON parsing in its own separate function is not working All the tutorials that I have seen or read about Swift 3 JSON parsing include placing JSON parsing code inside viewDidLoad() func/method and it works great. I want to place JSON parsing code in its own function and call it from viewDidLoad(). Check below example:
class ViewController: UIViewController {
    var ArrayImages = [String]();

    override func viewDidLoad() {
        super.viewDidLoad()

        var json = ParseJson();
        print("My Array = \(ArrayImages)");

    }

    // NEW FUNCTION
    func ParseJson() {
        let url = URL(string: "http://etasawoq.com/go_categories.php")!

        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if (error != nil){
                print("Error Found Creating URLSession : \(error)")
            } else {
                if let ParsedJson = data {
                    do {
                        let json = try JSONSerialization.jsonObject(with: ParsedJson, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray

                        for x in json {
                            let row = x as! NSDictionary;
                            let imageUrl = row["image_url"] as! String
                            self.ArrayImages.append(imageUrl);
                        }
                    } catch {
                        print("Json Processing failed \(error)");
                    }
                }
            }
        }.resume() // start session
    }
}

Unfortunately, the "ArrayImages" is not being populated when calling the ParseJson function. The print output is "My Array = []". Why is that? How can I solve this problem while keeping JSON parsing code in a separate function?

A: Your response getting through block so you need to print array in side the block not outside  as below .
do {

                        let json = try JSONSerialization.jsonObject(with: ParsedJson, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray

                        for x in json {
                            let row = x as! NSDictionary;
                            let imageUrl = row["image_url"] as! String
                            self.ArrayImages.append(imageUrl);
                        }
                      print("My Array = \(ArrayImages)");
                    }


text:
Q: Divergence of a vector field in an orthogonal curvilinear coordinate system How would one go about proving the following result in $\mathbb R^3$ for the divergence of vector field $\vec F = F_i \hat e^i$
$$ \nabla \cdot {\mathbf  F} = \frac{1}{h_1 h_2 h_3} \left[\frac \partial {\partial q^1} (F_1 h_2 h_3) + \frac \partial {\partial q^2} (F_2 h_3 h_1) + \frac  {\partial }{\partial q^3} (F_3 h_1 h_2)\right]$$

A: Here is a heuristic argument.
The flux across an area element perpendicular to $\hat{e}^{1}$ is
\begin{align*}
F_{1}\left(h_{2}dq_{2}\right)\left(h_{3}dq_{3}\right) & =\left(F_{1}h_{2}h_{3}\right)dq_{2}dq_{3}.
\end{align*}
Thus, the differential of this flux, along $\hat{e}^{1}$-direction,
is
\begin{align*}
\frac{\partial}{\partial q^{1}}\left(F_{1}h_{2}h_{3}\right)dq_{1}dq_{2}dq_{3},
\end{align*}
and so the volume density is
\begin{align*}
 & \frac{1}{\left(h_{1}dq_{1}\right)\left(h_{2}dq_{2}\right)\left(h_{3}dq_{3}\right)}\frac{\partial}{\partial q_{1}}\left(F_{1}h_{2}h_{3}\right)dq_{1}dq_{2}dq_{3}\\
= & \frac{1}{h_{1}h_{2}h_{3}}\frac{\partial}{\partial q^{1}}\left(F_{1}h_{2}h_{3}\right).
\end{align*}


text:
Q: Read file starting at second line LabView Using the Read from Text File Function I am able to easily read the first line of my file. However I now want it to read the second line. It would be great to just a for loop or something if I could specify the line number somewhere. Is there a way to do so? Thanks!

A: First, you can read the entire file as lines by right-clicking on the Read From Text File node and selecting "Read Lines".  One read will return an array containing one element for each line and you can work with the lines with regular array handling methods.  If you want to read each line individually, you can by wiring a 1 into the Count input and looping.  Each iteration will return an array with one element (the current line read).  You can get/set the offset (in bytes) to specify where in the file you want to read, but that's not necessary if I read your question correctly.


text:
Q: Django "500 internal server error" on login attempt in production I'm new to django and web design in general but I have a small apache2 webserver running on a raspberry pi, I have successfuly set up the server to work with django 2.2 and I can access the site via a dataplicity wormhole and the site will load correctly. However, when I attempt to login through dataplicity hosted site (admin page or the website) I get an "500- internal server error".
There is nothing in the apache error log and if I run the server via python manage.py runserver login works as expected only when running it through apache do I get the problem.
This is my apache2.conf:

DefaultRuntimeDir ${APACHE_RUN_DIR}

PidFile ${APACHE_PID_FILE}

Timeout 300

KeepAlive On

MaxKeepAliveRequests 100

KeepAliveTimeout 5

User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

HostnameLookups Off

ErrorLog ${APACHE_LOG_DIR}/error.log

LogLevel warn

IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

Include ports.conf

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Require all denied
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

WSGIScriptAlias / /home/pi/pi_site/pi_website/wsgi.py
WSGIPythonHome /home/pi/pi_site/myvenv
WSGIPythonPath /home/pi/pi_site

<Directory /home/pi/pi_site/pi_website>
    <Files wsgi.py>
        Require all granted
    </Files>
</Directory>

Alias /static/ /home/pi/pi_site/static/

<Directory /home/pi/pi_site/static>
    Require all granted
</Directory>

AccessFileName .htaccess

<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>

LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

IncludeOptional conf-enabled/*.conf

IncludeOptional sites-enabled/*.conf

And my settings.py:
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = '*******'

DEBUG = True

ALLOWED_HOSTS = [".dataplicity.io", "127.0.0.1"]

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'main_site',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'pi_website.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'pi_website.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LOGIN_REDIRECT_URL = '/'

LANGUAGE_CODE = 'en-uk'

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

Edit:
I've attempted setting ALLOWED_HOSTS = ["*"] but this didn't effect the 500 message. I also tried deleting and re-migrating the database creating a new superuser but again with no impact
Edit- 2:
I only get the 500 message on login and only with correct credencials, if I use the wrong login/password the page responds correctly

A: Check file permissions for your database file.  Maybe Apache doesn't have permission to write to it.  That would allow pages where only a read is needed, but a login needs to write to the database.  When running it though runserver it will access that file as your user, so permissions could be OK for that.