text:
Q: count how many tasks is open or onhold for logged in user I want to create Sql script to see how many task open or on-hold only for logged in user who assigned
to task
result
HelloWorld1(0)
HelloWorld2(2)
HelloWorld3(1)
HelloWorld4(5)
SELECT Projects.projectID,
    Projects.projectName + ' ' + '(' + CONVERT(NVARCHAR, COUNT(Projects_tasks.taskID)) + ')' AS Project
  FROM Projects
  LEFT JOIN Projects_tasks ON Projects.projectID = Projects_tasks.projectID
 INNER JOIN Users_projects ON Projects.projectID = Users_projects.projectID
 INNER JOIN Tasks ON Projects_tasks.taskID = Tasks.taskID
 INNER JOIN Users_Tasks ON Tasks.taskID = Users_Tasks.TaskID
 WHERE Users_Tasks.userID = @userID
   AND Tasks.status = 'Open'
   AND Tasks.status = 'Onhold'
 GROUP BY Users_projects.userID,
          Projects.projectName,
          Projects.projectID,
          Users_Tasks.userID

A: You have:
AND (Tasks.status = 'Open' AND Tasks.status = 'Onhold')

Which can't be true; a Task can't have both values at the same time.  You want:
AND (Tasks.status = 'Open' OR Tasks.status = 'Onhold')

Better yet, use IN:
AND (Tasks.status IN ('Open', 'Onhold') )

A: No row will be able to match:
(Tasks.status = 'Open' AND Tasks.status = 'Onhold')

Try
(Tasks.status = 'Open' OR Tasks.status = 'Onhold')

Or:
Tasks.status in ('Open', 'Onhold')

A: As already commented, the AND clause can not be satisfied as Task.Status can be only either Open or OnHold. Use the following code:
SELECT Projects.projectID,
    Projects.projectName + ' ' + '(' + CONVERT(NVARCHAR, COUNT(Projects_tasks.taskID)) + ')' AS Project
  FROM Projects
  LEFT JOIN Projects_tasks ON Projects.projectID = Projects_tasks.projectID
 INNER JOIN Users_projects ON Projects.projectID = Users_projects.projectID
 INNER JOIN Tasks ON Projects_tasks.taskID = Tasks.taskID
 INNER JOIN Users_Tasks ON Tasks.taskID = Users_Tasks.TaskID
 WHERE Users_Tasks.userID = @userID
   AND (Tasks.status = 'Open' OR Tasks.status = 'Onhold')
 --also this code can be used:
 --AND Tasks.status in ('Open', 'Onhold')
 GROUP BY Users_projects.userID,
          Projects.projectName,
          Projects.projectID,
          Users_Tasks.userID


text:
Q: Is there any SMS/MMS server for LAN environment I am looking for a solution to send SMS/MMS message to mobile device from desktop or browser in LAN environment.  As such, it is most probably using TCP/IP protocol to transmit request/response.
The server may attach to a GSM device with SIM card attached.  An server application would then start accept the request from any LAN client and convey the SMS/MMS to one or more recipients.  The server may log all requests for further traffic analysis in later stage.
Is there any solution that able to perform what I describe here.  Please advice.

A: There is an app on the android market that I think does what you want.
https://play.google.com/store/apps/details?id=com.shroomyCorp.PeerChat
It works on lan to, but I'm not sure if you can connect it with a desktop. Perhaps you should mail the dev, it might be possible.

A: You say "may attach" to a GSM device. Do you have to do it this way?
The way I do this is to have an account with a bulk SMS provider out in the "cloud" and then applications running on our systems use this provider to send SMS.
SMS recipient can be anywhere.
Provider gives us HTTP (or HTTPS) APIs to send the messages ...
Of course it means that you need a connection to the internet to be able to send SMS messages.

A: I did this for SMS alerts through Nagios it's a fairly simple setup and used quite often with server monitoring. Alot of guides are available but I would suggest start atTux mobile. That link has just about everything you need to get running. However you do have a few choices:

*

*you can setup desktop with your preferred flavor of Linux (I used ubuntu 8.10) and connect to a sms gateway on the web like Liam mentions. The version of linux you install may vary based on the SMS client, look over the solutions in the above link and find the one you feel most comfortable with: check  out the UI, the community, pricing.

*You can setup a linux box and hook a mobile phone to it check here for a list of linux compatible phones. Again clients are listed on the link provided above.

*Get yourself a hardware sms gateway like Fox Box. They will provide tech support and documentation to get it setup.

A: You could just send an email.
* AT&T: number@txt.att.net
* Qwest: number@qwestmp.com
* T-Mobile: number@tmomail.net
* Verizon: number@vtext.com
* Sprint: number@messaging.sprintpcs.com or number@pm.sprint.com
* Virgin Mobile: number@vmobl.com
* Nextel: number@messaging.nextel.com
* Alltel: number@message.alltel.com
* Metro PCS: number@mymetropcs.com
* Powertel: number@ptel.com
* Suncom: number@tms.suncom.com
* U.S. Cellular: number@email.uscc.net

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does an exception occur if captured image >= 3264x2448 Why does an exception occur if captured image is equal to, or larger than (3264x2448)? Images < 3264x2448 are ok.
public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the
        // preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d("DEBUG", "Error setting camera preview: " + e.getMessage());
        }

    }

Error at function:
public void surfaceDestroyed(SurfaceHolder holder) {
        try {
            // Non camera related code

            // Start of camera related code
            // Only clean up what you need to
            if (mCamera != null) {

                mCamera.cancelAutoFocus();

                mCamera.stopPreview();
            }

        } catch (RuntimeException e) {

            e.printStackTrace();
        } finally {
            // Make sure that at least these two calls are made
            mCamera.release();
            mCamera = null;
        }
    }

Exception:
 03-12 15:16:50.490: W/System.err(14817): java.lang.RuntimeException: Method called after release()
    03-12 15:16:50.492: W/System.err(14817):    at android.hardware.Camera.native_cancelAutoFocus(Native Method)
    03-12 15:16:50.494: W/System.err(14817):    at android.hardware.Camera.cancelAutoFocus(Camera.java:1024)
    03-12 15:16:50.496: W/System.err(14817):    at jp.osaka.CameraPreview.surfaceDestroyed(CameraPreview.java:47)
    03-12 15:16:50.498: W/System.err(14817):    at android.view.SurfaceView.updateWindow(SurfaceView.java:522)
    03-12 15:16:50.509: W/System.err(14817):    at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:226)
    03-12 15:16:50.511: W/System.err(14817):    at android.view.View.dispatchWindowVisibilityChanged(View.java:5851)
    03-12 15:16:50.513: W/System.err(14817):    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:951)
    03-12 15:16:50.516: W/System.err(14817):    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:951)
    03-12 15:16:50.518: W/System.err(14817):    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:951)
    03-12 15:16:50.520: W/System.err(14817):    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:951)
    03-12 15:16:50.522: W/System.err(14817):    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:951)
    03-12 15:16:50.524: W/System.err(14817):    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:951)
    03-12 15:16:50.526: W/System.err(14817):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1038)
    03-12 15:16:50.536: W/System.err(14817):    at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2583)
    03-12 15:16:50.539: W/System.err(14817):    at android.os.Handler.dispatchMessage(Handler.java:99)
    03-12 15:16:50.541: W/System.err(14817):    at android.os.Looper.loop(Looper.java:137)
    03-12 15:16:50.543: W/System.err(14817):    at android.app.ActivityThread.main(ActivityThread.java:4503)
    03-12 15:16:50.545: W/System.err(14817):    at java.lang.reflect.Method.invokeNative(Native Method)
    03-12 15:16:50.548: W/System.err(14817):    at java.lang.reflect.Method.invoke(Method.java:511)
    03-12 15:16:50.550: W/System.err(14817):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
    03-12 15:16:50.552: W/System.err(14817):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
    03-12 15:16:50.554: W/System.err(14817):    at dalvik.system.NativeStart.main(Native Method)

Function capture image:
                                      mCamera.lock();
                            // System.gc();
                            mCamera.takePicture(null, null, mPicture);
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }


text:
Q: Generate a list of maps from myBatis with null values my question is very related with this other Is that possible to generate a list of maps from myBatis,
but i find a problem when a column has null value.
I have this query:
<select id="executeQuery"  resultType="map">
select name,age from customer</select>

I woud like this result:
list{
  map{
    ("name","john"),
    ("age",33)
  }
  map{
    ("name","james"),
    ("age",)
  }
}

But like age in the second one is null, i am having this:
list{
  map{
    ("name","john"),
    ("age",33)
  }
  map{
    ("name","james"),
  }
}

It is posible directly with mybatis?
Thanks


text:
Q: How do I hide a div on some platforms but not all ok so I am trying to make a div have the attribute hidden when on a phone but not when on other platforms and would like to know how to do this?
    <div id="content-desktop">
        <button onclick="ChangeDefault()">switch theme to default</button>
        <button onclick="ChangeOrigin()">switch theme to origin</button>
        <button onclick="ChangeDark()">switch theme to dark</button>
        <button onclick="ChangeLight()">switch theme to light</button>
    </div>

A: You likely want to show/hide select elements based on the screen width.
This way, you can detect whether the devices display is large enough for your "desktop", rather than retermining it based on device type. (Consider a 13" iPad; that has a bigger screen than some laptops but could still be considered "mobile".)
You can use CSS Breakpoints like so:
.hideOnMobile {
  visibility: hidden;
}

@media only screen (min-width: 900px) {
  // this CSS will only be applied if the screen is wider than 899px
  .hideOnMobile {
    visibility: visible;
  }
}

If you really want to detect if the browser is on a mobile device, you can check the navigator.userAgent object to get the User Agent string for the browser. Since there's no standard way of writing a User Agent string, you'll likely need to collect a list of User Agents you want to respond to, or use a library that has some common ones included already.


text:
Q: how to add button in gridview dynamically i am creating gridview dynamically... Now i want to add some buttons in that and also add their relative rowCommand Events. please help me to do this. this is how I create GridView's dynamically in my code
for (int i = 0; i < dtEmployees.Rows.Count; i++)
            {
                TableRow tr = new TableRow();
                TableCell tc = new TableCell();

                GridView gv = new GridView();
                gv.ID = "gv" + dtTasks.Rows[i]["TaskID"].ToString() + dtEmployees.Rows[i]["EmpID"].ToString();

                DataTable dt = dtTasks.Clone();

                foreach (DataRow dr in dtTasks.Rows)
                {
                    if (dr["EmpID"].ToString() == dtEmployees.Rows[i]["EmpID"].ToString())
                    {
                        dt.Rows.Add(dr.ItemArray);
                    }
                }
                gv.DataSource = dt;
                gv.DataBind();
                tc.Controls.Add(gv);
                tr.Cells.Add(tc);
                tblMain.Rows.Add(tr);
            }

A: Though i don't test it but logically it would be like below:
if(e.Row.RowIndex > -1)
{
    Button button = new Button();
    button.CommandArgument = dt.Rows[e.Row.RowIndex][i].ToString();
    button.Attributes.Add("OnClick", "button_Clicked");

    e.Row.Cells[i].Controls.Add(button);
}

Where e would be GridViewRowEventArgs .And those code would be placed in your for/foreach loop.Probably like..
for (int i = 0; i < gv.Rows.Count; i++)

Then make an button event handler:
protected void button_Clicked(object sender, EventAgrs e)
{
   if (sender is Button)
   {
     try
     {
        String value = ((Button)sender).CommandArgument;
     }
     catch
     {
       //Check for exception
     }
   }
}

Also can view..

*

*http://forums.asp.net/t/1234622.aspx

A: I know you did it because you asked before a few months, but I just answered for the others who research about this point.
just do this at the function to displayed:
        DataGridViewButtonColumn col = new DataGridViewButtonColumn();
        col.UseColumnTextForButtonValue = true;
        col.Text = "ADD";
        col.Name = "MyButton";
        dataGridView1.Columns.Add(col);


text:
Q: APNS € and ¢ and $ signs I'm trying to send a push notification containing a special character (like €, ¢ or $). But the message eventually appears like: € => Û. What is the script doing:
$this->message = "Test special sign €";
$message = utf8_encode($this->message);
// Create the payload body
$body['aps'] = array(
        'alert' => $message,
        'badge' => '1',
        'sound' => 'default'
);
$body['e'] = $this->event;
$body['i'] = $this->eventId;

$this->payload  = json_encode($body);
var_dump($this->payload);

OUTPUT: var_dump($this->payload)
string(118) "{"aps":{"alert":"Test special sign \u00db","badge":"1","sound":"default"},"e":"order","i":"12"}"
Packing the message and send it.
$msg = chr(0) . pack('n', 32) . pack('H*', trim($RegisterIds[$key]['registerId'])) . pack('n', strlen($this->payload)) . $this->payload;

It is possible to send the euro sign? And if so... How? (Or what am I doing wrong?)

A:
"All files are properly UTF-8 encoded saved."

Then you do not need/must not use utf8_encode. This function interprets the input as ISO-8859-1 encoded and converts the bytes to their UTF-8 equivalents. You're screwing up your string yourself.


text:
Q: SetWindowRgn в Delphi. Что обозначает пeременная bRedraw в функции SetWindowRgn(hWnd: HWND; hRgn: HRGN; bRedraw: Boolean);
A: int SetWindowRgn(
    HWND hWnd,  // handle to window whose window region is to be set
    HRGN hRgn,  // handle to region
    BOOL bRedraw    // window redraw flag
);

Parameters
hWnd
Handle to the window whose window
region is to be set.
hRgn
Handle to a region. The function sets
the window region of the window to
this region.  If hRgn is NULL, the
function sets the window region to
NULL.
bRedraw Boolean value that specifies whether the operating system redraws
the window after setting the window
region. If bRedraw is TRUE, the
operating system does so; otherwise,
it does not.  Typically, you set
bRedraw to TRUE if the window is
visible.

Всего лишь нажал F1


text:
Q: Escaping double questionmark in if statement I am trying to make a function that counts changed, added, new, etc files in the local git repo. I am using git status -s for this and it returns ?? somefile if a file is untracked. The ?? part is the part I check to determine what type of entry it is.
However when checking with
if [ "${lPrefix}" == '??' ]; then ...

All changes uu, m, a, d are counted as untracked.
How can I make sure that the check works as intended and only triggers on untracked files.
I have tried replacing ?? with:

*

*"??" -> did not work, guessing it is because ? is a wildcard

*"\?\?" -> did not work, expected it to work

*'\?\?' -> did not expect it to work as ' means literal

EDIT: As requested by Jack Bracken
The lPrefix is set as follows(it is also all code where the problem lies)
while IFS='' read -r line || [[ -n "$line" ]]; do
    arr=($line)
    lPrefix="${arr[0]}"
    if [ "${lPrefix}" == '??' ]; then lPrefix="N"; fi
    ...
done < <(git status -s)

A: You have two problems here:

*

*you're dangerously using an antipattern to split a string (and here it's actually a dangerous move since your string does contain the glob characters ?),

*you're parsing the high level command (aka porcelain command in git's terminology) status.

First, fix the second problem: use git status --porcelain or, rather git status -z (which implies --porcelain), to have entries separated by a null byte (which makes parsing safe). We'll then parse using read with the null delimiter: -d ''
To fix the first problem, I'll try to understand what you want to do: each line given by git status -s (or, rather git status --porcelain) starts with a code; if this code is ?? then set lPrefix to N, otherwise set lPrefix to the code found.
This should then do:
while IFS= read -r -d '' line; do
    lPrefix=${line:0:2}
    filename=${line:3}
    if [[ $lPrefix = '??' ]]; then lPrefix=N; fi
    # other stuff...
done < <(git status -z)

Why did your command fail?
It's difficult to tell exactly, but it's probably related to the antipattern you used to split the string:
arr=($line)
lPrefix="${arr[0]}"

This is very bad! it's a (sadly) very common antipattern, given by people who don't really understand (or overlook) how the shell performs word splitting and filename expansion: if the expansion $line contains glob characters (i.e., *, ?, [...] and extended globs if extglob is on), then the shell will not only perform word splitting, but also perform filename expansion, that is, it will match every glob with found files.
In your case, if you happen to have filenames with 2 characters (e.g., a file named ab) in the current directory, then ${arr[0]} will be this file! Look:
$ mkdir test
$ git init
$ touch a ab abc xy
$ ls
a  ab  abc xy
$ git status -s
?? a
?? ab
?? abc
?? xy
$ while IFS='' read -r line; do arr=($line); declare -p arr; done < <(git status -s)
declare -a arr='([0]="ab" [1]="xy" [2]="a")'
declare -a arr='([0]="ab" [1]="xy" [2]="ab")'
declare -a arr='([0]="ab" [1]="xy" [2]="abc")'
declare -a arr='([0]="ab" [1]="xy" [2]="xy")'
$ # see the filename expansion?

Note also that I didn't use
while read state file; do ... ; done < <(git status -s)

or something similar (like in the accepted answer) to get the state and the file name, because that would trim leading and trailing newlines in both state and file.

A: The ?? should not be a problem here. I guess your variable ${lPrefix} isn't properly set. I tried the following code and it worked:
git status -s | while read state file ; do
    [ "${state}" = '??' ] && echo "${state} new"
done

However using bash for this is not really efficient. I strongly recommend to use awk like this:
git status -s | awk '{c[$1]++}END{for(i in c){print i, c[i]}}'

Explanation in multiline version:
#!/usr/bin/awk -f

# c(ount) is an associative array, indexed by the values of the first column
# like '??', 'u', 'm' and so on. Each time they appear we
# increment their count by 1
{ c[$1]++ }

# Once the end of input has been reached we iterate trough
# c and print each index along with it's count.
END {
    for(i in c) {
        print i, c[i]
    }
}

A: Whenever scripting with the output of git, it's best to use -z to work with null-separators.
I would recommend changing your script to this:
git status -z | while read -r -d '' status file; do
    [ "$status" = '??' ] && printf '%s\n' "$file"
done

As mentioned in the comments (thanks), if left unquoted, the ?? will expand to the name of any files with exactly two characters in their name. Adding quotes ensures that the question marks are treated as literal characters. Adding quotes results in consistent behaviour, whether using [ or the bash-specific [[.
When you want simple string matching, my advice would be to use [ with = (and don't forget to quote your variables, as always!).
I'm assuming that you plan on executing some shell command for every file with ?? status. Otherwise, remember that the shell isn't designed for text processing, so you should be using a tool such as awk/sed.

A: You can try :
cat 1.txt | grep -Po "(?<=\?\?\ ).*"

1.txt is:
?? aaa
!! bb
?? vv
~~ xx

Break-down:
grep -Po Perl expression, show only matching lines
("?<=" Starts with
\?\?\ Escaped question marks and a space
).* Anything coming after that initial match


text:
Q: Number of flagged posts for a user in the user profile shown in a meta site If I look at a user profile shown in a meta site where I am a moderator, should I see a link to the page listing the questions/answers posted by the user and that have been flagged (in the case there are any), as I see it in the main site?
The reason is I am asking is that I saw the overlay that it is shown when a question has been flagged, but the user profile for the OP doesn't show the link that reports the number of flagged questions/answers for that user.


text:
Q: Style an input textbox like jQuery Redmond theme I am using jQuery in my web page with Redmond theme from jQuery-ui team. The problem is that the input textboxes remain unstyled by Redmond theme. This creates a not-too-impressive look-and-feel. Is there any way to create an appropriate style for input textbox elements so they blend with Redmond theme in jQuery?

A: As I mentioned in my comment there is no built in way to accomplish this.  What you can do is take some of the colors used in the theme and apply then to the textbox to get something that looks similar.
Here's a couple options that I made that are based off the look and feel of the datepicker.
/* Option 1 */
input[type=text] {
    background: #5C9CCC url(http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/redmond/images/ui-bg_gloss-wave_55_5c9ccc_500x100.png) 50% 50% repeat-x;
    border: 1px solid #4297D7;
    font-weight: bold;
    color: white;
    padding: 5px;
    border-radius: 5px;
}

/* Option 2 */
input[type=text] {
    background: #DFEFFC url(http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/redmond/images/ui-bg_glass_85_dfeffc_1x400.png) 50% 50% repeat-x;
    color: #2E6E9E;
    font-weight: bold;
    border: 1px solid #C5DBEC;
    padding: 5px;
    border-radius: 5px;
}

Example - http://jsfiddle.net/XjCjR/1


text:
Q: How to get matching data from other table? Using Postgres, I have 2 tables:

*

*The first called territories with columns sid, agent and postcode.

*The second called postcodes, with columns id, postcode and geometry.
How can I put the geometry column data from the table postcodes into the table territories with the matching postcode?

A: In a query:
select t.*, p.geometry
  from territories as t left join postcodes p on t.postcode=p.postcode

Thats works only if there are not duplicateds postcodes in postcodes table.
If you want to update the table territories, first add the column and then update it:
update territories t set geometry = p.geometry
  from postcodes p
  where t.postcode=p.postcode


text:
Q: What classes may require *_ACCOUNTS, and related permissions? I'm cleaning up the code of an app that requests the following in its manifest:
android.permission.GET_ACCOUNTS
android.permission.AUTHENTICATE_ACCOUNTS
android.permission.MANAGE_ACCOUNTS
android.permission.USE_CREDENTIALS
android.permission.INTERACT_ACROSS_USERS_FULL
The question is: what classes/packages imports should I look for when searching for what might possibly be asking for these?
I've already searched for AccountManager - no hits. It is possible that they are no longer needed, but I wish to know the point at which I can be certain.
[EDIT] Lint settings to help find this would be even better. Here are mine:

I see no "missing permissions" option.
If I remove all permissions including all network, READ_PHONE_STATE and READ_EXTERNAL_STORAGE, app builds, starts, then WifiManager.getWifiState crashes with a ACCESS_WIFI_STATE-related SecurityException.
[EDIT2] The "type mismatches" check is enabled. Not every version of Android used the @RequiresPermission annotation.

My config: compile SDK version 23, min 14, target 22, build tools version 25.0.1

A: I just made a try, and you should indeed get a warning for missing permissions. Actually it's not even a warning but an error. The option is in Settings -> Editor -> Inspections -> Android -> Constant and Resource Type Mismatches, if you read the description you will see something like

Calling a method that requires a permission without having declared
  that permission in the manifest

This on AS 2.2.3
UPDATE:
I just checked on a project with compile sdk 23, and in the source code of AccountManager there actually is @RequiresPermission


text:
Q: Recreating the effect by using replace color in photoshop I adjusted my image by using photoshop's replace color tool and changing the hue, saturation, and lightness sliders. Unfortunately I forgot the individual settings for each and I need to recreate the effect. I tried eye balling it and can't seem to do it...
Original:

Adjusted:

A: Found a better method;
Select -> colour range
then
edit -> fill -> colour


text:
Q: Using Credit memo in magento community edition I have issued a credit memo in Magento Admin panel for an order, but I do not see how a customer can use this credit on the website? He cannot see it in the frontend either. How can this credit be managed by admin and/or by the customer?
Magento 1.8.0

A: When credit memo raised from admin, there is 2 option.

*

*Online

*Offline

If your integrated payment gateway support online, then that amount will credited into customer account.
If you integrated payment gateway doesn't support online, then Admin will go to Payment Gateway merchant account and manually transfer the fund to customer account.
Hope will help!


text:
Q: "Cat" into multiple files using brace expansion I am quite new to bash and trying to type some text into multiple files with a single command using brace expansion.
I tried: cat > file_{1..100} to write into 100 files some text that I will type in the terminal. I get the following error:
bash: file_{1..100}: ambiguous redirect
I also tried: cat > "file_{1..100}" but that creates a singe file named: file_{1..100}.
I tried: cat > `file_{1..100}` but that gives the error:
file_1: command not found
How can I achieve this using brace expansion? Maybe there are other ways using other utilities and/or pipelines. But I want to know if that is possible using only simple brace expansion or not.

A: You can't do this with cat alone.  It only writes its output to its standard output, and that single file descriptor can only be associated with a single file.
You can however do it with tee file_{1..100}.
You may wish to consider using tee file_{01..100} instead, so that the filenames are zero-padded to all have the same width: file_001, file_002, ...  This has the advantage that lexicographic order will agree with numerical order, and so ls, *, etc, will process them in numerical order.  Without this, you have the situation that file_2 comes after file_10 in lexicographic order.

A: target could be only a pipe, not a multiple files.
If you want redirect output to multiple files, use tee
cat | tee file_{1..100}

Don't forget to check man tee, for example if you want to append to the files, you should add -a option (tee -a file_{1..100})

A: This types the string or text into file{1..4}
echo "hello you just knew me by kruz" > file{1..4}

Use to remove them
rm file*


text:
Q: In Vim/Vi, how do you move the cursor to the end of the previous word? In Vim's normal mode:

*

*e goes to the end of the next word

*w goes to the beginning of the next word

*b goes to the beginning of the previous word

How do you move the cursor to the end of the previous word?

A: Try ge:
ge                      Backward to the end of word [count] |inclusive|.

                                                        *gE*
gE                      Backward to the end of WORD [count] |inclusive|.

A: as seen on VIM manual (section 03.1), you can use ge to go to the end of previous word

A: You may also want to do these to go to the space preceding a word (one character after ge: (both are only 2 keys)

*

*FSpace will take you to the space after the previous word

*Bh will also do that, in most cases.

The exception is when you are at the beginning of a line, in which case

*k$ does something similar, in 3 keypresses

A: Unfortunately it's not a single key... but ge is what you're looking for, I think.


text:
Q: The ring of germs of functions $C^\infty (M)$ Define $C^\infty (M)_x := \{ (U,f) | x \in U $ open $ , f \in C^\infty (U) \} / \sim $ where $M$ is a manifold and $(U,f) \sim (V,g)$ if $\exists W$ open, $x \in W$ such that $W \subset V \cap U$ and $f|_W = g|_W$.
This is a ring with the following operations: $[(U,f)] + [(V,g)] := [(U \cap V, f  + g)]$ and $[(U,f)]\cdot [(V,g)]:= [(U \cap V, fg)]$.
I'm trying to understand what multiplicative inverses look like, i.e. if I have $[(U, f)]$ then I want to show that there exists an open set $V$ containing $x$ such that $\frac{1}{f}$ is smooth on $V$.
Is this right? And can someone explain to me how I can show this? Many thanks for your help.

A: There are two rings involved in your question:
1) The ring you described, which should actually be denoted $\mathcal C^\infty_{M,x}$
2)  The ring $\mathcal C^\infty(M)_{\frak m}$, described as follows. Call $\frak m$ the ideal in $\mathcal C^\infty(M)$ consisting of global functions zero at $x$, that is ${\frak m}=\lbrace f\in  \mathcal C^\infty(M): f(x)=0\rbrace$. This is a maximal ideal in $\mathcal C^\infty(M)$, and you can localize $\mathcal C^\infty(M)$ at this ideal to get $\mathcal C^\infty(M)_{\frak m}$. The elements of this localized ring are formal fractions
$f/g$ with $f,g\in C^\infty(M)$
and $g(x)\neq 0$ . Beware that these formal fractions are by no stretch of the imagination interpretable as functions on $M$
, since $g$ might very well vanish outside, say, the interval $(x-1,x+1)$ !
There is a canonical  ring morphism $\mathcal C^\infty(M)_{\frak m} \to \mathcal C^\infty_{M,x}$ and the strange, perhaps underappreciated, result is that it is an isomorphism.
To answer your question:
1) In the first incarnation an invertible element is a germ $[(U,h)]$ with $h(x)\neq o$ and its inverse is $[(U',1/h)]$, where $U'\subset U$ is a neighbourhood  of $x$ on which $h$ has no zero.
2) In the second  incarnation an invertible element of $\mathcal C^\infty(M)_{\frak m}$ is a   fraction of the form $f/g$ with $f(x)\neq 0$ (in addition to $g(x)\neq 0$, of course), and its inverse is   $g/f$.


text:
Q: Forge DWG Pack and Go Translation I'm having some issues when translating the IDW to a DWG. I'm using the created configuration file from Inventor which works fine when translating one file and is saved as *.dwg which becomes available for download. The problem occurs when changing the transmittal value to "yes" in the config file to handle multiple sheets and create a zip.
[12/02/2021 17:12:20] Start upload phase.
[12/02/2021 17:12:20] Error: Non-optional output [exportDWG.zip] is missing.
[12/02/2021 17:12:20] Error: An unexpected error happened during phase Publishing of job.
[12/02/2021 17:12:20] Job finished with result FailedMissingOutput

This fails during the upload phase as per the log info above and returns an error due to the missing zip file even after updating the code to reference the zip file. The zip file is created when debugging locally with the AppBundle.
I would like to have the created zip file available for download instead of the single dwg.


text:
Q: Replacing text in Text Files I created a text file that contains different sections. I need to pull the information at a later time.
I split each line of the txt file to have each variable.
Example:
[Title]The Maps[TitleEnd]
[Name]Smith,John[NameEnd]
[Subject]Mythical Creatures[SubjectEnd]
[Text]Today i learned about this information and blah blah blah[TextEnd]
etc.

I need to open the txt file, find the correct brackets i.e. [Text] to [TextEnd] then replace it.
Example:
[Text]Today i learned about this information and blah blah blah[TextEnd]

to
[Text]Today i learned about this information and  i learned more things and blah blah blah[TextEnd]

I looked at a couple of examples. One has gotten me close but instead of replacing 1 line, it puts everything on 1 line.
Private Sub SavePro_Click()

    IRBNum = ThisDocument.IRBNetID
    FilePath = "Abstract.txt"
    TextFile = FreeFile
    Open FilePath For Input As #1
    StrFinal = "[Text]*"
    While EOF(1) = False
        Line Input #1, strline
        StrFinal = StrFinal + ModifyText(strline)
    Wend
    StrFinal = Left(StrFinal, Len(StrFinal) - 2)
    Close 1
    Open FilePath For Output As #1
    Print #1, StrFinal
    Close #1

End Sub

Function ModifyText(ByVal strInput As String) As String
    Dim arrString() As String
    Dim strOutput As String

    arrString = Split(strInput, " ")
    strOutput = arrString(0) + " " + SubText.Text
    ModifyText = strOutput

End Function

A: If you use an XML format
<xml>
 <Title>The Maps</Title>
 <Name>Smith,John</Name>
 <Subject>Mythical Creatures</Subject>
 <Text>Today i learned about this information and blah blah blah</Text>
</xml>

most of the code has been written for you.
Option Explicit

Sub update()

    Dim xDoc, oNode
    Set xDoc = CreateObject("MSXML2.DOMDocument.6.0")
    xDoc.Load Path & "\Abstract.xml"

    Set oNode = xDoc.SelectSingleNode("xml/Text")
    MsgBox "Text: " & oNode.nodeTypedValue
    oNode.nodeTypedValue = "Today i learned about this information " & vbCrLf & _
           "and  i learned more things and blah blah blah"

    xDoc.Save Path & "\Abstract.xml"

End Sub


text:
Q: How do I change the return format of Slate queries from column to row? The results of my query look like:
{
  col1: [values],
  col2: [values]
}

Is there a way to get my query to return as a list of rows objects?

A: The best way is to write a function to convert your query response.
One example:
function transformColumnSchemaToRowSchema(data) {
    var keys   = _.keys(data);
    var arrays = _.values(data);

    var arrayOfPropertyLists = _.zip.apply(_, arrays);

    var arrayOfObjects = _.map(arrayOfPropertyLists, function(list) {
    var obj = {};

    _.each(keys, function(key, i) {
    obj[key] = list[i];
    });

    return obj;
    });

    return arrayOfObjects;
}

Or a more compact version:
var data = {{q_some_query}};
delete data['_response']
var newdata = _.zip.apply(_, _.values(data)).map((val) => _.zipObject(_.keys(data), val));

After you convert to this format, you might want to convert back to the original format (for example, if you want to put the data into a table widget in Slate). This is how that can be done:
var original_fmt = {};
_.forEach(_.keys(newdata[0]), function(k) {
original_fmt[k] = _.map(newdata, k);
});
// use original_fmt


text:
Q: Specifying in and out along with controls in tikz Considering the following code:
\documentclass{beamer}
\usepackage{tikz}

\usetikzlibrary{calc}

\begin{document}
    \begin{frame}
      \begin{tikzpicture}[overlay,remember picture]
        \node at (1,0) [rectangle,draw,minimum height=.6cm] (a1) {A};
        \node at (4.2,-3.5) [rectangle,draw,minimum height=.6cm] (e3) {B};

        \draw[->,thick,out=200] (e3) .. controls ($(a1)+(-2,-2)$) .. (a1);
      \end{tikzpicture}
    \end{frame}
    \end{document}

How can one specify the in and out angles for the starting and the final nodes?

A: The keys in,out are for to paths for example you can write
\draw[->,thick] (e3) to[in=200,out=200] (a1);

However if you still want to use angle arguments and Bezier curves then you can add a polar coordinate
\draw[->,thick] (e3) .. controls ++(200:1) and ++(200:2) .. (a1);

Here the first control point is taken as relative to the start point and the second is relative to the final point.
The Bezier curve with single control point is taken to both start and the final points.


text:
Q: unwanted "NUL" characters string after reading bytes of a mjpg TCP stream I'm trying to record a jpeg image sent by an Ethernet camera in a mjpg stream.
The images I obtain with my Borland C++ application (VSPCIP) are sometimes "corrupted" :
I have the example of a "corrupted jpeg frame" :
it has 21690 characters (for a 640x480 jpeg image) and among them there is a string of 5045 following characters which have the value "NUL" (displayed as NUL in Notepad++).
And because I stop reading bytes when I reach the "content-length" specified in the mjpg header, the following bytes are cut off.
Two things :
- I would first like to remove these corrupted frame : how may I detect (quickly) a string of let's say more than 50 (or directly 5000 or 5045) following "NUL" characters) ?
- I have to find why my application adds this string of following "NUL" characters.


text:
Q: HTTP Caching with Authorization Given a response from a web server that contains an Authorization header as per the OAuth spec does HTTP caching fail to be useful?
Request1 Authorization : AUTHTOKEN
Request2 Authorization : ANOTHERAUTOTOKEN

In this case given HTTP caching the second request would return the cached response for the first user. This isn't a problem for content that is generic across users, but this feels wrong for a shared cache to be providing responses for other users.
Likewise if we were to use a Vary header and vary by Authorization, this means our cache would store a cached copy per token which surely defeats the purpose of HTTP caching. The browsers local cache (private) would work fine, but this would still mean an origin request from each user at least once per session.
Edit
The service in question requires Authorization for all requests, however based on what I've read, serving responses from a Shared cache that include Authorization headers shouldn't be done unless must-revalidate, public, and s-maxage are present.
My question therefore is, given an API that has both generic (responses the same across all users) and user specific responses, is caching even possible? Having s-maxage and public headers but an authorization header would mean that the cache would resolve UserA's response to UserB, UserC and so on if I'm following the RFC correctly.

A: See http://greenbytes.de/tech/webdav/rfc7234.html#response.cacheability:
"A cache MUST NOT store a response to any request, unless:
The request method is understood by the cache and defined as being cacheable, and
 ... the Authorization header field (see Section 4.2 of [RFC7235]) does not appear in the request, if the cache is shared, unless the response explicitly allows it, ..."

A: I'm not sure but what do you think about vary on custom header with unique-per-user checksum value:
x-login-checksum: john_903243482
Vary: x-login-checksum

As it seems to me in this case we can cache responses per user between his sessions. Wouldn't that work?


text:
Q: Is it safe to load coreml models (uncompiled and compiled) from untrusted sources? ML models stored in Python pickle files can run arbitrary code when loaded. Do the formats used by CoreML suffer from similar security issues?
The uncompiled format appears to be based on protobuf while a compiled model consists of several different files.
Is it safe to load .mlmodel or .mlmodelc files from untrusted sources?


text:
Q: Setting 2 equations equal in modular arithmetic Let us say that I have some m, say $5z+25$ (where $z$ is some random integer), and $n$ is say $3z+9$ (same $z$). I want to find an equation that correlates $m$ and $n$ in some $\text{mod} \,O$. Normally in algebra, I would have $m = \frac 53 n+10$. But, since we don't have fractions in modular arithmetic, what would this equation be?
In other words, is there an equation mod O that expresses m in terms of n, or n in terms of m for all values of z?

A: You are trying to solve
$$5z+25\equiv3z+9\pmod O\ .$$
This can be written as
$$2z\equiv-16\pmod O\ .$$
If $O$ is odd you can cancel $2$ to give
$$z\equiv-8\pmod O\ ,$$
if $O$ is even, say $O=2P$, then
$$z\equiv-8\pmod P\ .$$
If you are just looking for one solution, then $z=-8$ will do in any case.
If you want to know how to do this sort of thing with different numbers, Google "solving linear congruences" - there are heaps of resources available online.


text:
Q: How to change the element name in .asmx response? The webservice returns xml like below. The consuming client is expecting < MyMethodResult > to be < Response >.
Code:
[WebMethod]
public MyResponseObj MyMethod(MyRequestObj Request)
{
    try
    {
        MyResponseObj response = new MyResponseObj();
        response.Message = "test";
        response.Status = Status.success;
        return response;
    }
    catch(Exception ex)
    {
        throw;
    }
}

Actual Response:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <MyMethodResponse xmlns="MyNameSpace">
      <MyMethodResult>
        <Status>success or failure</Status>
        <Message>string</Message>
      </MyMethodResult>
    </MyMethodResponse>
  </soap:Body>
</soap:Envelope>

Expected Response
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <MyMethodResponse xmlns="MyNameSpace">
      **<Response>**
        <Status>success or failure</Status>
        <Message>string</Message>
      **</Response>**
    </MyMethodResponse>
  </soap:Body>
</soap:Envelope>

A: I got it to work by decorating the MyResponseObj class with [XmlRoot("Response")]
[XmlRoot("Response")]
public partial class MyResponseObj
{

}


text:
Q: Increase width for fixed height HTML table data cell? A similar question like Fixed Height and Changing Width for Header (HTML Table) - except I'd like to ask: is there a different way to achieve this, other than using   instead of space? Basically, I'd like increasing text content in the table data cell to keep the cell height fixed, and instead increase the cell width..
Below is a minimal HTML example, which behaves like this upon changing the browser (Firefox 43) width:

As you can see, regardless of height/max-height specification in CSS, the table td fields increase their height, while decreasing the width.
What I'd like to happen is in this case, the specified height - and the corresponding width - of td cells remains the same upon change of browser width, and what changes instead is the bottom scrollbar.
Is there any way I could achieve this with CSS, or even JS?

In response to @tgallimore's questions:

*

*Are you able to give a fixed width to the table? - no, I'd like it to resize width depending on content

*Do you know how wide you would like each cell to remain? - no, I'd like it to have a fixed width, then if it's enough for two rows of text, these should be adjusted for optimal width (i.e. each row has approximately the same amount of text)

*Can this width be given to each cell? - no, cells would have differing text contents, as in the example

In response to  @Leothelion's post: I wanted to specify a fixed height of 2em (or let's say, 2.5em), is because I'd expect it to allow enough vertical space for max two lines of text. So what I want to achieve is:
* If the text in the cell is short (i.e. one word), then there's no line breaking, text is in single line, and cell height is 2.5em
* If the text in the cell is long (a whole sentence), then I'd want the layout to figure out that the in a cell height of 2.5em it can fit max two lines of text; thereafter it would try to break the text such that there are approximately the same amount of characters in both lines (so now we have a "paragraph"; and finally it would set the width of the cell to the width of this newly line-broken "paragraph".
In other words, I would like this layout:

... regardless of how I scale the browser width; if the browser width is too small, then only the horizontal scrollbar adjusts.

The sample HTML code:

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

Hello World!

          Dendrologist
          Iciness
          JoyfulDistortion
          Suburbicarian
          Ecballium
          AbulicNonviolence
          GrowlerTheocracy
          Necessitattion

          A1
          Just testing some longer content here, so long that it might not fit on a single line
          Molybdenum
          D1
          Scanty Distensibility
          Arithmetical
          G1
          Hypallelomorph

A: Are you able to give a fixed width to the table?
Do you know how wide you would like each cell to remain? Can this width be given to each cell?
A table-cell will ALWAYS expand its height if it's content doesn't fit, regardless of wether you set a height or not (so a height in this case would work as a min-height).
Also, you will probably need to use .mytbl { table-layout: fixed; }. This tells the table to use the widths that you have defined, rather than try to fix it's content in each cell. See this for more info: https://css-tricks.com/fixing-tables-long-strings/

A: What you need is  Media query
See my UPDATED FIDDLE
On different resolution(i just took 1, adjust according to your need ), fixed the width and table-layout: fixed; and you will get your solution.


text:
Q: Split text between multiple delimiters I have a rather tricky problem with my ongoing project.
I pretty much need to extract ceritain Strings between muliple delimiters out of a bigger String.
To give you a better understanding, what I mean, here is an example:
Some Text that wont be needed
Some Text that wont be needed
Some Text that wont be needed
Some Text that wont be needed
Some Text that wont be needed
Textstart (Start-Delimiter)
Text I want
Text I want
Text I want
Text I want
Text I want
Textend (End-Delimiter)

So far, so easy. But now comes a messy part in. The End-delimiters change sometimes like this
Textstart
Text I want
Text I want
Text I want
Text I want
Textend2 (another end delimiter)

I also solved that Problem, but now since I discovered, that the start delimiter can also occur twice before the next endpart.
Like this:
Textstart (Start-Delimiter)
Text I want
Text I want
Textstart
Text I want
Text I want
Textend (End-Delimiter)

This really is confusing to me. This is the function right now. It works but only if the start delimiter does not occur twice.
I could split the text first by the end strings and after that by the start string, but I don't know hot to split a text by multiple delimiters.
Function NewTextGet(ByVal Text As String, ByVal StartString As String, ByVal EndStrings() As String)
    Dim AllBlocks As New List(Of String)
    Dim FirstSplit() As String = Strings.Split(Text, StartString)                    ' Splits Text at Start delimiter
    For Each splt In FirstSplit.Skip(1)
        Dim EndSplit1 = splt.Split({EndStrings(0)}, StringSplitOptions.None)         ' First end delimiter Split
        Dim EndSplit2 = EndSplit1(0).Split({EndStrings(1)}, StringSplitOptions.None) ' Second delimiter Split
        Dim EndSplit3 = EndSplit2(0).Split({EndStrings(2)}, StringSplitOptions.None) ' Third delimiter Split
        If EndSplit3.Length > 1 Then
            AllBlocks.Add(EndSplit3(0))
        ElseIf EndSplit2.Length > 1 Then
            AllBlocks.Add(EndSplit2(0))
        Else
            AllBlocks.Add(EndSplit1(0))
        End If
    Next
    Return AllBlocks
End Function`

I hope I explained this well enough, and thank you for any help :)

A: This version produces a List(Of List(OF String)).  So each set of lines will be in a different list:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim fileName As String = "C:\Users\mikes\Downloads\gYeziPRE.txt"
    Dim blocks As List(Of List(Of String)) = NewTextGet(My.Computer.FileSystem.ReadAllText(fileName), "ctxt", New String() {"done", "sdone", "prompt"})
    For i As Integer = 0 To blocks.Count - 1
        Debug.Print("Block: " & i)
        For Each line As String In blocks(i)
            Debug.Print(line)
        Next
        Debug.Print("")
    Next
End Sub

Function NewTextGet(ByVal Text As String, ByVal StartString As String, ByVal EndStrings() As String) As List(Of List(Of String))
    Dim started As Boolean = False
    Dim curBlock As List(Of String)
    Dim AllBlocks As New List(Of List(Of String))
    Dim lines() As String = Text.Split(Environment.NewLine)
    For Each line As String In lines
        If line.Contains(StartString) Then
            If Not started Then
                started = True
                curBlock = New List(Of String)
            End If
            Dim i As Integer = line.IndexOf(StartString)
            curBlock.Add(line.Substring(i + StartString.Length).Trim())
        ElseIf EndStrings.Contains(line.Trim()) Then
            started = False
            If Not IsNothing(curBlock) Then
                AllBlocks.Add(curBlock)
            End If
            curBlock = Nothing
        ElseIf started = True AndAlso Not IsNothing(curblock) Then
            curBlock.Add(line.Trim())
        End If
    Next
    If Not IsNothing(curBlock) Then
        AllBlocks.Add(curBlock)
    End If
    Return AllBlocks
End Function

Output:
Block: 0
"What's up?"
para "All these Trainers"
line "look the same, but"
para "only one is the"
line "leader!"

Block: 1
"Am I Koji?"
para "Why, yes, I am!"

Block: 2
"Well done!"
para "Here!"
para "The Fist Badge!"

Block: 3
"<PLAYER> received"
line "Fist Badge."

Block: 4
"Here!"
para "Take this TM!"

Block: 5
"Hah!"
para "That was joyful"
line "sparring!"

Block: 6
"Japanese"
line "onomatopoeia"
cont "are so kawaii!"

Block: 7
"Hiri hiri!"

Block: 8
"Uwaaaa!"

Block: 9
"Well, you chose"
line "unwisely."

Block: 10
"You have more"
line "chances."

Block: 11
"Koji is hot."
para "Dressing like him"
line "is<...>"
para "wonderful!"

Block: 12
"Wasn't supposed"
line "to happen!"

Block: 13
"Can't wait for"
line "Halloween!"

Block: 14
"Ninjas are so"
line "cool!"

Block: 15
"Not skilled"
line "enough!"

Block: 16
"Time to study"
line "ninjutsu instead"
cont "of pretending."

A: Try this
Function NewTextGet(ByVal RawText As String, ByVal StartString As String, ByVal EndStrings() As String) As List(Of String)
        Dim bEnd As List(Of String) = EndStrings.ToList
        bEnd.Insert(0, StartString)

        Dim Blocks As New List(Of String)
        Dim Splits() As String = Split(RawText, vbNewLine, , CompareMethod.Text)

        For x As Integer = 0 To Splits.Length - 1
1:
            Dim block As String = ""
            If Splits(x).Contains(StartString) Then
                block = Splits(x)
                For y As Integer = x + 1 To Splits.Length - 1
                    Dim BlockEnd As Boolean = False
                    For Each s As String In bEnd
                        If Splits(y).Contains(s) Then BlockEnd = True
                    Next
                    block &= vbNewLine
                    If BlockEnd Then
                        If Splits(y).Contains(StartString) Then
                            Blocks.Add(block & vbNewLine)
                            x = y - 1
                            GoTo 1
                        End If
                        x = y + 1
                        block &= Splits(y)
                        Blocks.Add(block & vbNewLine)
                        Exit For
                    End If
                    block &= Splits(y)
                Next
            End If
        Next

        Return Blocks
    End Function

usage
For Each s As String In NewTextGet(Raw, "ctxt", New String() {"sdone", "done", "prompt"})
    TextBox2.Text &= s & "=======" & vbNewLine
Next

use this order {"sdone", "done", "prompt"} to avoid conflection while spliting


text:
Q: Reset UIView's frame with a pan gesture without hardcoding start values I have a UIPanGestureRecognizer that is attached to a UIView.  What I am trying to do is essentially drag and drop into a bucket.  If the user lets go of the UIView and it's not in the bucket, I want it to animate back to its original start location.  My selector that gets called for my UIPanGestureRecognizer is:
- (void)handleDragDescriptionView:(UIPanGestureRecognizer *)gestureRecognizer {
    UIView *panViewPiece = [gestureRecognizer view];
    CGRect originalFrame = CGRectMake(946, 20, 58, 30);

    CGPoint translation = [gestureRecognizer translationInView:panViewPiece];
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan || gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        panViewPiece.center = CGPointMake(panViewPiece.center.x + translation.x, panViewPiece.center.y + translation.y);

        [gestureRecognizer setTranslation:CGPointZero inView:panViewPiece.superview];
    }
    else if (gestureRecognizer.state == UIGestureRecognizerStateCancelled) {
        [UIView animateWithDuration:0.25 animations:^{
            self.dragDescriptionView.frame = originalFrame;
        }];
    }
    else {
        [UIView animateWithDuration:0.25 animations:^{
            self.dragDescriptionView.frame = originalFrame;
        }];
    }

}

I was wondering if I could do this without the originalFrame at the top of the method.  I originally had
CGRect originalFrame = _dragDescriptionView.frame;

instead of the hardcoding, but it doesn't snap back.  Probably because I'm updating that value as I am dragging.  I don't particularly like hardcoding values, but I wasn't sure if there was a way around this.  Thanks!

A: You really only need to track the view's original center.  Make originalCenter an instance variable and only set it when the gesture begins:
@implementation MyViewController {
    CGPoint _originalCenter;
}

- (void)handleDragDescriptionView:(UIPanGestureRecognizer *)gestureRecognizer {
    UIView *panViewPiece = [gestureRecognizer view];

    switch (gestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:
            _originalCenter = panViewPiece.center;
            break;

        case UIGestureRecognizerStateChanged: {
            CGPoint translation = [gestureRecognizer translationInView:panViewPiece.superview];
            panViewPiece.center = CGPointMake(panViewPiece.center.x + translation.x, panViewPiece.center.y + translation.y);
            [gestureRecognizer setTranslation:CGPointZero inView:panViewPiece.superview];
            break;
        }

        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled: {
            [UIView animateWithDuration:0.25 animations:^{
                panViewPiece.center = _originalCenter;
            }];
            break;
        }

        default:
            break;
    }
}


text:
Q: How to make each child in a list should have a unique "key" prop in React Gather data →
    const gatherComps = (data) => {
        let competencyList = []
        let i = 1
        while (i < 6) {
          if (data && data.hasOwnProperty(`competency${i}`)) {
            competencyList.push(data[`competency${i}`])
          }
          i++
        }
        return competencyList
      }

Prep Data →
    const displayInfo = (singleCC, i) => {
        const result = singleCC.length
          ? singleCC.map((cc, ind) => {
              return ind < 1 ? (

                  {cc}

              ) : (

                  {cc}

              )
            })
          : ""
        return (

            <>{result}</>

        )
      }

Return Data →

            {gatherComps(data).map((cc, i) => displayInfo(cc, i))}

I've tried:
key={i}
key={`custom-name-title-` + i.toString()}
key={ind}
key={`custom-name-desc-` + ind.toString()}
and some other simular things and can't get this warning to go away.
I've even included the same values for an id={} to make sure it continued to render a unique id, which it does, but I still get the warning...

A: You are missing key value for
. You have that one at first iteration of .map.
Just add custom key the same way you did:
const displayInfo = (singleCC, i) => {
  const result = singleCC.length
    ? singleCC.map((cc, ind) => {
        return ind < 1 ? (

 <------------ HERE
            {cc}

        ) : (

            {cc}

        );
      })
    : '';
  return (

      <>{result}</>

  );
};


text:
Q: Groovy - Create a 2-dimentional array I have a function
def workTheList (List data, cutIndex){...}

The function should get the list and cutIndex as integer.
i want to create a 2nd dimensional array from this data.
example:
list = '1.1.1.1','2.2.2.2','3.3.3.3' .. (for example lets say 40 ips)
cutIndex = 5
so 40 / 5  = 8
I would like to get an Array.size = 8  and
Array[0] = '1.1.1.1','2.2.2.2','3.3.3.3'...  (Each array item need to hold 5 ips)
def workTheList (List data, cutIndex){
    def arraySize = Math.round(Math.ceil(data.size / cutIndex))

    println("array size will be " + arraySize)

    def myArray = new String[arraySize][cutIndex]
    //myArray[0] = (items in data from 0 to cutIndex )
    //myArray[1] = (items in data from cutIndex to (cutIndex*2))
    //myArray[2] = (items in data from (cutIndex*2) to (cutIndex*3))
    //.
    //.
    //.
}

Disregard the fact that i will loop it but this is the main logic that i need.
id be happy for some help with this im very new to groovy

A: collate() is here to help:
def workTheList (List data, cutIndex){
  def list2d = data.collate cutIndex
  ( cutIndex - list2d.last().size() ).times{ list2d.last() << 0 } // fill the last element with some defaults
  list2d
}

def res = workTheList 1..20, 4
assert res == [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]

res = workTheList 1..20, 3
assert res == [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 0]]

res = workTheList 1..23, 7
assert res == [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21], [22, 23, 0, 0, 0, 0, 0]]


text:
Q: Undefined index when passing variable to another page from a form I'm trying to pass a value from one page to the other but I can't for the life of me understand why I keep getting the undefined index error message.
This is the PHP code to the first page:
    <?php
    include 'database_connection.php';

    $id = $_GET['id'];

    $sql="select engineer.id, engineer.team_id, engineer.first_name, engineer.active, engineer.last_name, engineer.role, engineer.region, engineer.phone, to_date, team.team_name, team.manager_name, team.description, team.type, engineer.email from engineer inner join team on engineer.team_id=team.id where active=0 and engineer.team_id > 0 and engineer.id = '".$id."'";

    $results = mysqli_query($connection, $sql);

    while($row = mysqli_fetch_array($results)) {
        $id=$row['id'];
        $first_name=$row['first_name'];
        $last_name=$row['last_name'];
        $role=$row['role'];
        $email=$row['email'];
        $phone=$row['phone'];
        $region=$row['region'];
        $type=$row['type'];
    ?>

    <form class="form-horizontal col-sm-12" role="form" method="post" action="../admin/update.php">

    <fieldset disabled>

          SSO ID

            <input type="text" id="id" name="id" class="form-control" value="<?php echo $id; ?>">

    </fieldset>

          Name

            <input type="text" class="form-control" id="name" name="first_name" placeholder="First Name" value="<?php echo $first_name; ?>">

          Surname

            <input type="text" class="form-control" id="name" name="last_name" placeholder="Last Name" value="<?php echo $last_name; ?>">

      Team

        <select style="width:auto;" class="btn btn-default dropdown-toggle form-control" type="button" name="team_name" value="" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
         <?php
            //connect  to the database
            include 'database_connection.php';

            //query the database
            $sql_team = "SELECT DISTINCT id, team_name FROM team";

            //uses $sql_team variable to make a specific query
            $query = mysqli_query($connection, $sql_team);
        ?>

        <option value="<?php echo $team_name; ?>"><?php echo $team_name; ?></option>

        <?php
            //initilises a while loop to retrieve all the rows
            while ($row = mysqli_fetch_array($query) )
            {
               //echos all the distinct catDesc rows into a list
               echo "<option value='" . $row['id'] . "' >".htmlspecialchars($row["team_name"])."</option>";
            }
        ?>
        </select>

        Role

            <input type="role" class="form-control" id="role" name="role" placeholder="Role" value="<?php echo $role; ?>">

        Email

            <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com" value="<?php echo $email; ?>">

        Phone Number

            <input type="phone" class="form-control" id="phone" name="phone" placeholder="Business number" value="<?php echo $phone; ?>">

        Region

            <input type="region" class="form-control" id="region" name="region" placeholder="Region e.g. South" value="<?php echo $region; ?>">

            <input type="submit" value="Save" class="btn btn-primary">

            <! Will be used to display an alert to the user>

</form>
    <?php
        //closes and stops the loop
        }
    ?>

This is the code to the second page, where the error message appears:
<?php
include 'database_connection.php';

    $id = mysqli_real_escape_string($connection, $_GET['id']);
    $first_name = mysqli_real_escape_string($connection, $_POST['first_name']);
    $last_name = mysqli_real_escape_string($connection, $_POST['last_name']);
    $team_name = mysqli_real_escape_string($connection, $_POST['team_name']);
    $role = mysqli_real_escape_string($connection, $_POST['role']);
    $email = mysqli_real_escape_string($connection, $_POST['email']);
    $phone = mysqli_real_escape_string($connection, $_POST['phone']);
    $region = mysqli_real_escape_string($connection, $_POST['region']);

    if ($role == ''){
        $role = NULL;
    }

    if ($email == ''){
        $email = NULL;
    }

    if ($phone == ''){
        $phone = NULL;
    }

    if ($region == ''){
        $region = NULL;
    }

    $sql = "UPDATE people SET id='$id', first_name='$first_name', last_name='$last_name', team_id='$team_name', role='$role', email='$email', phone=$phone', region='$region' where id='$id')";

?>

So the error appears when I try to retrieve the ID onto the second page from the first page. What am I missing?

A: if you want to pass a variable as get method you can pass it inside action attribute of form
eg: action="xyz.php?id="
on line 3 you have assigned a $_GET[] variable you cannot assign there since those values only sets after submitting form so if you want to remove error please script it like this
if(isset($GET['id']){
$id = $_GET['id'];
}

A: use an
<input id="id" type="hidden" value=$id>
in your form and read it as
$_POST['id']
in the second page


text:
Q: How to clear / refresh the cache in EclipseLink I'm using following settings in persistence.xml (I use Eclipselink 2.6.4) from my web application:
<properties>
    <property name="eclipselink.jdbc.cache-statements" value="true" />
    <property name="eclipselink.cache.query-results" value="true" />
    <property name="eclipselink.ddl-generation.index-foreign-keys" value="true" />
    <property name="eclipselink.logging.level" value="OFF" />
    <property name="eclipselink.persistence-context.close-on-commit" value="true" />
    <property name="eclipselink.persistence-context.flush-mode" value="commit" />
    <property name="eclipselink.persistence-context.persist-on-commit" value="false" />
</properties>

I'm using the @Cacheable(false) annotation to prevent some entities from being cached.
The @Cache annotation doesn't work any more in version 2.6.4.
My question is, is there a possibility to clear the cache globally? Let say every 3 hours?
Thanks

A: First level cache is enabled by default and you can not disable it. i.e. no settings in your persistence.xml file will disable first level cache.
You can only clear out all the entity manager objects by calling
entityManager.clear()

this will make subsequent queries go to the database (the first time) and then objects are again stored in the cache
In your case you would need to store your entitymanager objects in a register somewhere and have a loop through it every 3 hours to call the clear() function.
You can force each query to go to the database directly by calling
query.setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH);


text:
Q: Spring jdbc templates : What is the best way to keep sql statement out of code There doesn't seem to be a named query support in Spring JDBC Templates. By named query I mean the facility to reference sql statement by name in java code and keep the actual statements in some configuration file.
In the absence of out-of-box support, I'm researching the best approach to keep the sql statements outside java code.
Here are the alternatives:

*

*properties file

*xml properties file

*spring context xml (dependency inject)

comments?

A: Java - Storing SQL statements in an external file
I did one system where queries were stored in the DB, too, which for what we needed was absolutely perfect, but very entertaining. The query to do query lookups was in the DB as well, which caused great hilarity when it broke (don't ask).

A: All the approaches you've considered as alternative will work, yet you are adding additional layer to your design if you move the statements out of Java classes which to me is unnecessary. Consider the overhead of keeping the statements outside Java class.

*

*Properties and XML will have be loaded to fetch a single statement.

*Inject will inject unnecessary statements into classes.

If I were you, I will create a class and have the statement listed in static final. This makes it transparent, avoid unnecessary layers and makes it flexible for whoever is going to maintain your code in the future.
Example:
//This does the job
public class SQLStatements
{
  static public final String GET_NAME="SELECT Name FROM some_table WHERE ID=?";
}

A: I would prefer to store all the SQL queries in properties or xml file.
Then fetch all the queries and store them in Map or Properties object at the program boot up.
This provides the feasibility to change the query even after code deployment.
We can change the query in property file and then restart the application.


text:
Q: What is the different between "?attr/xyz", "?android:xyz" and "?android:attr/xyz" in a layout? Both seem to work in most cases but ?attr/ seems to have compatibility problems. I understand that ? means we are referring to the current theme value, but what's that doesn't answer my question.
Can someone explain and also mention the best practices?
I am using a theme which inherits from Material theme for v21 and from AppCompat for lower versions. What are the complications I should look out for?
Thanks.

A: ?attr/xyz
Defines and refers to the value of an attribute which you have defined on your own in your application.
 ?android:attr/xyz
Refers to the values of an attribute which are already available in android built-in.
More specifically, the ? implies an extra level of indirection. Think of it as dereferencing an attribute to fetch the resource it points to rather than referring to the attribute itself. You see this with ?android:attr/foo
Which is the best practice to use is depends on what properties you are using and if it is available in built-in android system then you can use it otherwise you can define on your own.
What's the difference between @android: and ?android?
@android: -- This is a reference to existing resource or previously declared style (or drawable or dimension, etc).
?android: -- Is a reference to an item declared in the current Theme*. An example can show this best.  I like to think of these as style 'variables', or global attributes that can are set in the main Theme declaration.
From the article which explain about an attributes referencing in android HERE
Let's say we've got a style that's currently being applied to a stock Widget, the ExpandableListView style. For our app, we want to override the groupIndicator and the childDivider styles.
<style name="Widget.Holo.ExpandableListView" parent="Widget.Holo.ListView">
  <item name="groupIndicator">@android:drawable/expander_group_holo_dark</item>
  ...
  <item name="android:childDivider">?android:attr/listDivider</item>
</style>

groupIndicator is using an @android reference to a stock drawable.  To override this, we'll need have create a new style (that has a parent of Widget.Holo.ExpandableListView) and override the groupIndicator with a new drawable.  We'll then need to set the style on our ExpandableListView, or set the style for ExpandableListViews to use the new style or pass it to the style to the view directly via the constructor.
childDivider is using a ?android attribute reference.  This is a lot easier to override.  In the main app Theme, add an item that sets this property.
For more details check Referencing attributes


text:
Q: Arduino in car: capacitor for extra 3 sec of power I want to install an Arduino Uno in a car, powered by a consumer 12V->5V car voltage regulator plugged into the lighter socket. The socket is switched, i.e, there's no power when the motor's off. When I turn off the engine I'd like to keep the Uno powered for extra ~3 secs. Can I use a capacitor in parallel to the Uno to get the extra 3 secs of power once the motor's off? How would i determine the capacitance? Should the cap be placed before the volt. regulator (i.e. directly on car's 12V) or after volt. regulation (on the regulated 5V)? Would I need some diodes to go with it? I don't want to put the Uno on the car's unswitched circuit, because it seems wasteful to run the Uno 24/7 off the battery just so it can be used for extra 3 secs when the motor's off. Thanks.

A: An alternative to using a capacitor is to connect to the permanent supply but to use a timer to power down or disconnect after a suitable delay.
The circuit can be arranged to repower the Arduino via the switched circuit when power is next switched on.
Current drain when off can be essentially zero.
When power is switched on supply to the Arduino can be from switched or permanent supply as required.

As Clabacchio notes, if a capacitor is used, the holdup time =
t = C x V / I  or
 C = t x I / V
where t = holdup time. V = allowed drop in Volts and C = capacitance in Farads.
eg for 3 seconds, 50 mA, 5 Volt allow droop
C = t x I / V = 3 x 0.05 / 5 = 0.03F = 30 mF = 30,000 uF.

A: You can use a capacitor, but you need quite a big one depending on how much your Arduino consumes. 3 seconds at - let's say - 25 mA is 75 mC (Q=I*t), that at 12 V are stored in a 6.25 mF capacitor.
$$\left( C = \dfrac{Q}{V} \right) $$
The problem is that the voltage will decrease linearly if you drain a constant current, and below a certain voltage your Arduino will turn off. If you put the capacitor before the voltage regulator it will store more charge for the same capacity value, and - more important - the regulator will allow a wider voltage range, so you'll be able to use better the capacitor.
Since the Arduino accepts 7-12 V supply, you have a 5 V range to have the capacitor discharge. Again, 75 mC over 5 V means 15 mF, so with a 20 mF capacitor you should be able to keep it alive.

Note: I don't know what your Arduino should do, so the power that it will consume; size your capacitor accordingly.

About how to connect it, I'd suggest a resistor and a diode in the lighter socket side, to prevent too fast charge of the capacitor and to avoid its discharge towards the lighter socket.
So, summarizing, if I is the average current absorbed by your Arduino, 7-12 V is its supply voltage range, the minimum capacitor size you need will be approximately:
$$ C = \frac{Q}{\Delta V} = \frac{I \cdot t}{\Delta V} = \frac{I \cdot 3s}{12V-7V} = \frac{3s}{5V}I $$

A: Don't use the 12V\$\rightarrow\$5V regulator, the Arduino needs at least 7V in. Use the battery's 12V directly instead.
The capacitor's value will depend on the Arduino's power consumption. The Arduino webpage doesn't say what the Uno consumes, so you can't say right away what capacitor value it needs. In any case it's not designed for low power. I checked the datasheet for the voltage regulator, and that alone already uses 6mA. On the schematic I can see two microntrollers: an ATMega16U2 running at 16MHz, and an AtMega328P, also at 16MHz. The former may consume up to 21mA, the latter says 9mA at 8MHz, so it's safe to say 18mA at 16MHz. We already have 45mA, let's round it to 50mA for the other components.
If a capacitor is discharged at a constant current, then
\$ \Delta V = \dfrac{I \cdot t}{C} \$
You start at 12V, and the Arduino needs a minimum of 7V, so \$\Delta V\$ = 5V, I was 50mA and t = 3s. Then
\$ C = \dfrac{I \cdot t}{\Delta V} = \dfrac{50mA \cdot 3s}{5V} = 30 000\mu F \$
That's the minimum, I would pick a 47 000\$\mu\$F/25V capacitor. Add detection for power off, so that you can switch off all unnecessary outputs which also may consume current, a relay for instance.
If you want to know exact what the power consumption is, add a 1\$\Omega\$ resistor in series with the power supply and measure the voltage drop. A 50mV drop means 50mA consumption.
Also add a TVS (Transient Voltage Suppressor) at the Arduino's power input; a car's 12V is extremely dirty.
Add the diode clabacchio mentions. A series resistor of 10\$\Omega\$/5W will charge the capacitor in 1.5s when applying power.


text:
Q: Can I call a .mp3 or .wav file from a Java package in NetBeans? My friend asked me to create an app that he can use in conjunction with the game Plague Inc, and he wants the soundtrack from the game to play in the application. Upon doing web research I have tried everything and nothing works. Is it possible to call the soundtrack from a java package (like with an image) instead of specifying folder directories and URLs? There was some promising information I found online but when I ran the code after trying it, the AudioInputStream keeps on giving me errors. I have tried using the clauses exceptions but that severely conflicted with the main method and the application would not even run. I have tried putting the coding in the constructor, a new method and even in the main method itself but all of them just throw out errors when I run the application (I don't even know where to put it so that it will work). Please help as this is getting seriously frustrating.
My package is called Sound and the file is called plague.wav
And although the game is an Android game, my application runs off Windows PC
Here is the coding I have so far:
File sound = new File("/Sound/plague.wav");
            AudioInputStream audioIn = AudioSystem.getAudioInputStream(sound);
            Clip clip = AudioSystem.getClip();
            clip.open(audioIn);
            clip.loop(Clip.LOOP_CONTINUOUSLY);
        } catch (LineUnavailableException ex) {
            Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedAudioFileException ex) {
            Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
        }

A: You can get it as a resource stream
Check this:
       InputStream input = getClass().getResourceAsStream("/Sound/plague.wav");
       AudioInputStream audioIn = AudioSystem.getAudioInputStream(input);
            Clip clip = AudioSystem.getClip();
            clip.open(audioIn);
            clip.loop(Clip.LOOP_CONTINUOUSLY);
        } catch (LineUnavailableException ex) {
            Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedAudioFileException ex) {
            Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
        }

Here's a sample class:
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class Snippet {

    public static void main(String[] args) throws Exception {
        try {

            InputStream input = Snippet.class.getResource("/Sound/sound.wav")
                    .openStream();
            AudioInputStream audioIn = AudioSystem.getAudioInputStream(input);
            Clip clip = AudioSystem.getClip();
            clip.open(audioIn);
            clip.loop(Clip.LOOP_CONTINUOUSLY);

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    // A GUI element to prevent the Clip's daemon Thread
                    // from terminating at the end of the main()
                    JOptionPane.showMessageDialog(null, "Close to exit!");
                }
            });
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


text:
Q: NextJS load react component at runtime I want to create a react based theme engine for NextJS, in summary, the user can upload a set of .js files that contains React components, and I want to inject them inside my app on some specific parts.
The question is: It is possible to compile react component and inject them in my app after build and at runtime?
I also open to suggestions, still looking for an alternative of this.


text:
Q: Peticiones de eliminación de usuarios duplicada(actualizada) estoy haciendo un CRUD con Laravel, AJAX y MySQL. El problema es que, a la hora de eliminar los registros, me pasa algo que no consigo entender. Cuando refresco la pagina, elimino un registro y todo va perfecto, sin embargo, al borrar el segundo, me vuelve a intentar borrar el primero (lo cual obviamente da un error 500) y el segundo lo hace bien, y asi sucesivamente con el tercer registro, cuarto, etc... Me intenta borrar todos los anteriores antes de ese.
Esta es la ventana modal del botón que llama a la función que elimina los registros:

Eliminar Usuario

      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        ×
      </button>

        <form>
        @csrf

      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      <button type="submit" id="remove_btn" class="btn btn-danger">Delete</button>

</form>

Petición AJAX que muestra la ventana modal y elimina los registros:
    function show_delete_form(id) {

        $.get('/admin/show-delete-form/' + id, function (user) {
        $("#delete-user-txt").html('¿Desea eliminar el usuario ' + user + '?');
        $('#delete-user').modal('toggle');
        })
        const token = $("input[name=_token]").val();
        $('#remove_btn').click(function(e){
            e.preventDefault();
            let id_empty= id;
            console.log(id_empty);
            console.log('/admin/show-delete-form/' + id);
            $.ajax({
                url: "/admin/delete-register",
                method: "POST",
                data: {
                    id: id,
                    _token: token
                },
                success: function (res) {
                    if (res == true) {
                        console.log(res);
                        id_empty= "";
                        $('#delete-user').modal('hide');
                        toastr.info('El registro fue eliminado correctamente',
                            'Eliminar Registro', {
                                timeout: 3000
                            });

                            $('#users_table').DataTable().ajax.reload();

                    }
                    if (res == "same_admin") {
                        toastr.warning('No puedes eliminarte a ti mismo', 'Eliminar Registro', {
                            timeout: 3000
                        });
                    }
                    if (res == false) {
                        toastr.warning('Ha ocurrido un error', 'Eliminar Registro', {
                            timeout: 3000
                        });
                    }
                }
            })
})
    }

La ruta control_panel que muestra la datatable:
   function control_panel(Request $request)
{
    if ($request->ajax()) {
        # code...

        $users = DB::table('users')->get('*');

        return DataTables::of($users)
            ->addColumn('edit', function ($edit) {
                $edit = 'id . ')">Editar	';
                return $edit;
            })
            ->addColumn('delete', function ($delete) {
                $delete = 'id . ')">Borrar	';
                return $delete;
            })
            ->rawColumns(['edit', 'delete'])
            ->make(true);
    }
    return view('admin.controlpanel');
}

La ruta delete_register que muestra la datatable:
   function delete_register(Request $request)
{
    $id = $request->id;
    $user = DB::table('users')->where('id', $id)->first();

    if ($user->id == Auth::user()->id) {
        return response()->json("same_admin");
    } else {
        $user_delete = DB::delete('delete from users where id = ?', [$id]);

        if ($user_delete == 1) {
            return response()->json(true);
        } else {
            return response()->json(false);
        }
    }
}

Gracias de antemano

A: tienes un problema con los eventos amarrados al DOM y tratas de hacer triger a un elemento agregado por jquery, eso no funciona y debes implementar la limpieza de eventos y la delegacion de eventos de jquery, tambien recomiendo agregarle un namespace al evento para diferenciarlos de otros.
puedes remplazar esto:
$('#remove_btn').click(function(e){

por esto:
$(document).off('click.req', '#remove_btn'); // limpieza de eventos con off
$(document).unbind('click.req', '#remove_btn'); // limpieza de eventos con unbind

$(document).on('click.req', '#remove_btn', function(e, xhr, settings){ // delegacion de eventos a document y uso de namespace de evento click.req


text:
Q: IPython3 on SL (RHEL) I am running IPython (and especially a notebook server) on Scientific Linux 6.3 (thus RHEL). I tried to use python3 to run setup and use ipython and also the ipython3 command. However this fails all the time. Before I go into detail with error messages and such - I read somewhere that IPython3 is currently not supported for RHEL derivates (I think the post was relating to Fedora), is this true?
Cheers
Phil

A: I understand that this is a fairly old question. However, given that Fedora 20 (the current version) comes with IPython 0.13 which lacks some functionality of IPython 2, I decided to write down how I installed it, in hopes that someone might find it useful. My focus was on the newest version of IPython Notebook.

Edit: I was just made aware of this IPython backport repo.

All yum and pip* commands here are to be run as the root. Those disliking such approach can prepend sudo do all yum and pip* commands and run the rest of them without sudo.
Remove RPMs of IPython (to avoid collisions):
yum remove python-ipython\* python3-ipython\*

Install pip:
yum install python-pip python3-pip

Install additional Python dependencies (it did work for me without these, but I didn't test much, so something might break down without these):
yum install python-jinja2 python-markupsafe python3-jinja2 python3-markupsafe python-devel python3-devel

Install IPython for both Python 2 and Python 3:
pip install ipython[all]
pip-python3 install ipython[all]

I've read somewhere that on Ubuntu, pip-python3 is called pip3.
To run IPython Notebook for Python 2 (do this as an ordinary user, not the root):
ipython notebook

To run IPython Notebook for Python 3 (do this as an ordinary user, not the root):
ipython3 notebook

To test your installation, call iptest or iptest3 (again, as an ordinary user, not the root). These tests may fail, so you might need additional packages for them to pass. For me, PyZMQ failed. This was fixed by installing two more packages:
yum install python-zmq-tests python3-zmq-tests

Many thanks to IPython-dev mailing list members Zoltán Vörös, for pointing me in the right direction, and Roberto Colistete Jr., for additional Python dependencies.


text:
Q: Is The Magnitude of Gyro XYZ Meaningful? Say I have a gyro that outputs degrees/second, and I take the euclidean magnitude of the x,y, and z rotations:
$$
\text{magnitude} = \sqrt{x^2 + y^2 + z^2}
$$
Is this actually useful? Is magnitude now "total degrees/second"? Or does the weirdness surrounding non-commutative addition of rotations come into play?

A: Think back to basic geometry and what the individual X, Y, and Z output values of the gyro actually mean.
One way to look at them is as the components of the rotation vector.  This vector is parallel to the axis of rotatation with the magnitude being the speed of rotation.  The square root of the sum of the squares of the individual components of this vector is its magnitude.  So yes, your magnitude value is the speed of rotation.  Draw a picture and this really should be obvious.

A: The gyroscope sensor reports instantaneous angular velocity - the tiny rotation occuring from t to t+dt.  This is a vector.  Actually, pseudovector - it misbehaves around mirrors but that's not relevent here.   You add angular velocities like normal.  Pythagoras give the magnitude of this - how many radians per second the sensor is turning, without regard for in what direction.
It is the orientation of the object - the accumulation of all the instantaneous angular velocities over time - that shows noncommutative behaviour.


text:
Q: Find an equivalence relation on $\mathbb{N}$ with exactly 3 classes and such that one class hase size 30, another 50. My answer is: Let $X=${$1,2,3,4,5,...,147$} and let for all $x,y\in\mathbb{N}$, $x=y\Leftrightarrow x-y\in 3X$. There are threee classes and such that one class hase size 30, onether 50.
Can you check my answer?

A: Let $X_1=\{1,2,\cdots,50\},X_2=\{51,52,\cdots,80\}$ and $X_3=\{81,82,\ldots\}$. If we can make an equivalence relation with these three sets as the equivalence classes, then we're done. And we can: let the relation $\sim$ be defined by $x\sim y$ iff $x$ and $y$ belong to the same $X_i$.


text:
Q: How to check for Empty Bitmap while capturing Signature in Android I am using com.github.gcacace.signaturepad.views.SignaturePad for capturing signature in my android app. The getSignatureBitmap() returns a Bitmap object even for a blank screen. How do i check for a blank bitmap(blank screen) ?

A: Bitmap will always return an empty object. You can use the below trick to handle empty signature on signature-pad.
val isSinged = false
binding.signaturePad.setOnSignedListener(object: SignaturePad.OnSignedListener {
        override fun onStartSigning() {
            isSigned = true
        }

        override fun onSigned() {
            isSigned = true
        }

        override fun onClear() {
            isSigned = false
        }})

Use setOnSingedLister to check if user signed.


text:
Q: Looking for a way to get team public keys to EC2 instance autonomously I am administering a single (now) ec2 instance which will provide some tools to our users. I am using Ansible to manage it. I have it set to create users using a mix of a Cron-job and Ansible (by creating a list of users and having a playbook ensure they are present).
My main question is this;
I am trying to create a way for each user (new and old) to be able to access the instance with their key that they uploaded to EC2 AWS. I have been hitting a dead end in my thoughts on this.. Is there a way to make a call to the AWS api that would return the text of each public key (since they are public I don't see a reason why this shouldn't exist..?) so that I can ensure that a copy of it exists in their respective "~/.ssh/authorized_keys" file?
Other than that I have thought that uploading the keys to an S3 bucket would work for having Ansible read them. The only problem with this is that the users would have to upload their keys to S3.
Any feedback is appreciated-
And if I am attacking this the wrong way please let me know.

A: My reading of your question is that once a user has imported a key in the AWS console, you'd like a way to import that new key into the actual instances automatically. Unfortunately, the describe-key-pairs API calls return the private key's fingerprint, not the full public key.
If you've got a technically savvy team using this, having them upload to an S3 bucket or a server somewhere may be your best option.


text:
Q: Attach file in live agent and send to customer I am using salesforce live agent in service cloud. During chat with customer I want to attach record or files from my desktop and send to customer. Right now there is option to attach a record and send to customer . When I select a record and click on send button..following things happen.
 File transfer request sent for Contact: External Page
But It never goes to customer and status remain like this untill we end chat.
Can anybody help on this..?

A: As of now Salesforce allows supports only transfer of Files from Visitors to the Agents.
Please take a look at link::
https://help.salesforce.com/articleView?id=live_agent_transfer_files.htm&language=en_US&type=0
The option you clicked initiated the transfer of file. On click of it, the visitor's livechat window shows  a additional box where in visitor can upload files. So the functionality that you tried out is the functionality to transfer files FROM visitor TO agent.
Salesforce does this file request initiation from Agents(rather than providing visitors direct option) to ensure that files reach salesforce only with consent of the Agent and avoid unwanted files,spamming by customers.

A: it seems to be a known issue (i.e. BUG) on firefox:
https://success.salesforce.com/issues_view?id=a1p30000000T5ilAAC

A: I came across same issue and found that Agent File Transfer Enabled was not checked in Live agent configuration.


text:
Q: Only Single Color Visible in Matplotlib 3D surface plot I am trying to use the 3D surface plot feature in matplotlib. I always get a single color in the main 3D plot even though the colorbar has the correct color distribution. I have tried adjusting the vmin and vmax values. It changes the displayed color, but it is still a single color.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
import matplotlib.colors as colors

plt.rc('font', size=20)          # controls default text sizes
plt.rc('axes', titlesize=20)     # fontsize of the axes title
plt.rc('axes', labelsize=20)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=20)    # fontsize of the tick labels
plt.rc('ytick', labelsize=20)    # fontsize of the tick labels
plt.rc('legend', fontsize=20)    # legend fontsize
plt.rc('figure', titlesize=20)  # fontsize of the figure title

fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')

X = np.linspace(1, 9, 9)
Y = np.linspace(0.1, 0.9, 9)
X, Y = np.meshgrid(X, Y)

y14=[0.4452739,0.30183285,0.25813195,0.22200696,0.19410882,0.17159065,0.15946234,0.1454833,0.13729666]
y24=[0.36556191,0.26622398,0.20779134,0.17347617,0.15454879,0.13959851,0.12783846,0.1125244,0.0991787]
y34=[0.28298545,0.20158779,0.15011216,0.13871456,0.12187855,0.1108228,0.09260828,0.09191485,0.08405019]
y44=[0.23466043,0.1570963,0.12579934,0.11918668,0.0973392,0.08328725,0.08287371,0.07223769,0.06703042]
y54=[0.20135427,0.14908527,0.11954249,0.09954416,0.08083851,0.07613027,0.06216689,0.06148425,0.05450287]
y64=[0.18790923,0.13138967,0.09762079,0.08155587,0.06951088,0.06225487,0.05563515,0.05375833,0.04966462]
y74=[0.1646632,0.11620533,0.08697924,0.06734929,0.06212874,0.05564317,0.05146634,0.05027161,0.04692116]
y84=[0.15172702,0.09854979,0.07125092,0.06229793,0.05398641,0.05226622,0.05084956,0.0496555,0.05421488]
y94=[0.13190896,0.07993282,0.06037859,0.05867347,0.0576491,0.05695472,0.05695472,0.05876029,0.05545337]
Z=[y14,y24,y34,y44,y54,y64,y74,y84,y94]
Z=np.array(Z)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)

# Customize the z axis.
ax.set_zlim(0, 0.45)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()

Please find the attached image for the result I get: output image

A: It seems you are using an old version of matplotlib. In this case the rstride and cstride arguments are set to 10. However you have less than 10 points along each dimension in your plot, hence only a single point is used for the color information.
Use
ax.plot_surface(..., rstride=1, cstride=1, ...)

to have every point's color information visualized in the plot.
In general, always refer to the examples of your matplotlib version. E.g. if you were using matplotlib 1.4.1, look at
https://matplotlib.org/1.4.1/examples/mplot3d/surface3d_demo.html