text:
Q: How to call list of package methods dynamically in PL/SQL I have a scenario that I want to execute dynamically fetched methods from a cursor with different arguments. Those argument values are replaced (using Get_Parameter_Value___(head_rec_.objkey,parameter_); ) with values in a loop as you can see in the following example.
PROCEDURE Dynamic_exe(
    keyvalue_ IN VARCHAR2)
IS
param_str_        VARCHAR2(2000);
temp_param_str_   VARCHAR2(2000);
method_stmt_      VARCHAR2(100);

CURSOR get_method IS
  SELECT exe_method
  FROM method_tab

BEGIN

param_str_        := Substr(rec_.exe_method,Instr(rec_.exe_method,'(')+1,(Instr(rec_.exe_method,')')-1)-Instr(rec_.exe_method,'('));
temp_param_str_   := param_str_;
method_stmt_      := rec_.exe_method;

WHILE temp_param_str_ IS NOT NULL LOOP
   IF (Instr(temp_param_str_,',') > 0 )THEN
       parameter_          := trim(Substr(temp_param_str_,1,Instr(temp_param_str_,',')-1));
       temp_param_str_     := Substr(temp_param_str_,Instr(temp_param_str_,',')+1);
   ELSE
      parameter_          := trim(temp_param_str_);
      temp_param_str_     := NULL;
   END IF;
   parameter_value_  := Get_Parameter_Value___(head_rec_.objkey,parameter_);
   method_stmt_      := REPLACE(method_stmt_,parameter_,''''||parameter_value_||'''');
END LOOP;

FOR rec_ IN get_method LOOP
   EXECUTE IMMEDIATE 'BEGIN '||method_stmt_||'; END;';
END LOOP;

END Dynamic_exe;

This is not safe, SQL injection can be done for this, I need a solution, associated with bind variables, Does anyone have a solution for this?

A: You can eliminate the possibility of SQL injection by using DBMS_ASSERT.SQL_OBJECT_NAME to protect the method name, and use DBMS_SQL and bind variables to protect the arguments.
DBMS_ASSERT.SQL_OBJECT_NAME throws an error if the value is not the same as an existing object.  (Although for packages it only checks that the package name exists, not the procedure name.  But the procedure name must still be a realistic name.)
For example, if the package name exists, the function will simply return the name:
SQL> select dbms_assert.SQL_OBJECT_NAME('test_package.test_procedure') name from dual;

NAME
--------------------------------------------------------------------------------
test_package.test_procedure

But any SQL injection shenanigans will raise an exception (which you can catch and handle if necessary):
SQL> select dbms_assert.sql_object_name('; delete from employees;') from dual;
select dbms_assert.sql_object_name('; delete from employees;') from dual
       *
ERROR at line 1:
ORA-44002: invalid object name
ORA-06512: at "SYS.DBMS_ASSERT", line 401

Instead of building the entire statement as a string, add :bind_variable_n and DBMS_SQL to run it.
So the final string will look something like this (add the bind variable numbers in the loop):
method_stmt_ := 'begin '||method_name||'(:1, :2); end;';

Executing a dynamic number of bind variables requires DBMS_SQL.BIND_VARIABLE.  Switching from native dynamic SQL to DBMS_SQL is going to be annoying, but it will let you pass in the bind variables without any injection concerns.


text:
Q: Using IPython console along side IPython notebook While working on an IPython notebook, I'm increasingly finding myself wishing that the notebook would have a console attached to it, for interactive programming. I find myself adding lines to test snippets of code and then deleting them and that's the good usage. In the worse usage I'm changing the commands in the same line, evaluating the line over and over, changing entirely the purpose of the line until I get it right, and then I'm Ctrl-Zing all the way back to the original cell content.
If I could have an interactive interpreter at the bottom of the notebook, that would definitely increase my productivity. I know that a notebook has a kernel, but I wasn't able to attach a new ipython console to it. So my wonders are:

*

*Is there a more efficient way to work with the notebook?

*Assuming there isn't, how can I attach an ipython console to a notebook kernel?

Thanks!

A: Just do %qtconsole in one cell, and it will start a qtconsole attached to the same kernel.
Of course your kernel need to be local.
you can of course use the long method :
In [1]: %connect_info
{
  "stdin_port": 50845,
  "ip": "127.0.0.1",
  "control_port": 50846,
  "hb_port": 50847,
  "signature_scheme": "hmac-sha256",
  "key": "c68e7f64-f764-4417-ba3c-613a5bf99095",
  "shell_port": 50843,
  "transport": "tcp",
  "iopub_port": 50844
}

Paste the above JSON into a file, and connect with:
    $> ipython <app> --existing <file>
or, if you are local, you can connect with just:
    $> ipython <app> --existing kernel-45781.json
or even just:
    $> ipython <app> --existing
if this is the most recent IPython session you have started.

then
 ipython qtconsole --existing kernel-45781.json

A: When you start the ipython notebook in the terminal, it will output something like this:
 2015-03-26 13:05:52.772 [NotebookApp] Kernel started: 4604c4c3-523b-4373-bfdd-222eb1260156

Then start the ipython console like this:
ipython console --existing 4604c4c3

I find this easier than the other solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Execute interdependent views from mysqldump backup mysqldump creates a dump with the tables (and views) listed alphabetically. When there are foreign key relationships between the tables this is not very convenient, however, the problem is easily resolved by running:
SET FOREIGN_KEY_CHECKS=0;

I have a situation whereby the view, vwapple, is dependent on the view, vworange, say. With the mysqldump, vwapple is listed and executed before vworange, which is problematic as we'll get a "view vworange does not exist" error message.
How is this situation solved? Do views have a similar solutions as tables have? Or is it better to make each view independent just to get round this problem?
NOTE
I'm restoring the database using a python script. Each view and table is in its separate .sql file as I want to source control each database object independently.

A: Recent versions of mysqldump, when dumping whole databases, solve things this way: for every view in the database, they first create an empty table with the same structure, then they create the views, dropping each placeholder table before creating a view. It seems that replacing a table with a view won't harm views that depend on it.
I know about this because this approach has another flaw, which bit me: rows in views may contain more data than rows in tables, so some of the placeholder tables cannot be created, causing some dumps to be unrestorable without manual intervention. For this reason, a topological sorting of views would be preferable, although it might require some work.


text:
Q: Detect and mark differences between two similar objects in different positions on each image - python I am trying to prepare program for comparison 2D drawings or just views on those drawings that can be positioned within the drawing in slightly different positions.
For now I have program that compares the drawings using SSIM and OpenCV but if i.e. one of the views on the drawing will be slightly shifted it will be marked as a completely different view.
Moreover I want to also have possibility to compare the screenshot taken with Windows snipping tool in the rectangular mode. Due to that the input screenshots would be  in different sizes and ratios.
Below I show you example what is the expected result with given input as:
IMAGE_1:
IMAGE_2:
And the expected result should be like this:
IMAGE_1 - expected result:
IMAGE_2 - expected result:
Help me with the idea how to solve this problem. I am newbie in image processing and in programming in general so please show me the right direction with this ;) Thanks in advance.
Code is copied from some other post and works only for drawing where the views are in the same position.
from skimage.metrics import structural_similarity
import cv2
import numpy as np

# Load images
before = cv2.imread('im1.jpg')
after = cv2.imread('im2.jpg')

# Convert images to grayscale
before_gray = cv2.cvtColor(before, cv2.COLOR_BGR2GRAY)
after_gray = cv2.cvtColor(after, cv2.COLOR_BGR2GRAY)

# Compute SSIM between the two images
(score, diff) = structural_similarity(before_gray, after_gray,
full=True)
print("Image Similarity: {:.4f}%".format(score * 100))

# The diff image contains the actual image differences between the
two images
# and is represented as a floating point data type in the range [0,1]
# so we must convert the array to 8-bit unsigned integers in the
range
# [0,255] before we can use it with OpenCV
diff = (diff * 255).astype("uint8")
diff_box = cv2.merge([diff, diff, diff])

# Threshold the difference image, followed by finding contours to
# obtain the regions of the two input images that differ
thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV |
cv2.THRESH_OTSU)[1]
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]

mask = np.zeros(before.shape, dtype='uint8')
filled_after = after.copy()

for c in contours:
    area = cv2.contourArea(c)
    if area > 40:
        x,y,w,h = cv2.boundingRect(c)
        cv2.rectangle(before, (x, y), (x + w, y + h), (36,255,12), 2)
        cv2.rectangle(after, (x, y), (x + w, y + h), (36,255,12), 2)

cv2.imwrite('before', before)
cv2.imwrite('after', after)
cv2.waitKey()


text:
Q: Using @index in meteor #each iterator doesn't work why doesn't this work in meteor? https://github.com/wycats/handlebars.js/issues/250

A: It's not yet implemented in meteor's version of handlebars; there's a subtlety about the reactivity of @index rendering properly. You can read more about it here: https://github.com/meteor/meteor/issues/489#issuecomment-11270564

A: This is definitely a frustration for me as well. In the meantime I made a handlebars helper to parse anything into named 'key' and 'value' objects:
Handlebars.registerHelper('key_value', function(context, options) {
  var result = [];
  _.each(context, function(value, key, list){
    result.push({key:key, value:value});
  })
  return result;
});

This would be used with the #each operator like:

  {{#each key_value attributes}}

{{key}}

{{value}}

  {{/each}}

A: Another way to get it to work is to use a standard Meteor template helper with the map cursor function.
Here's an example showing how to return the index when using each with a collection:
index.html:

<template name="print_collection_indices">
  {{#each items}}
    index: {{ this.index }}
  {{/each}}

index.js:

Items = new Meteor.Collection('items');

Template.print_collection_indices.items = function() {
  var items = Items.find().map(function(doc, index, cursor) {
    var i = _.extend(doc, {index: index});
    return i;
  });
  return items;
};


text:
Q: Others ways to save data than Cookie? What other ways can i use to store small pieces of information than cookies?
Im building a widget that uses an iframe to load certain content. Within that iframe i want to save different states of the application, but i am getting problem when the widget is not on the same domain as the content inside the iframe (99% of the time).
Any ideas?
Oh and this is jQuery.

A: other than Jquery you can use
1. hashtags to save the state
2.HTML5 History API
3.HTML5 localstorage

A: Cookies are the way to go if you want to save persistent data for the specific user, however you can use HTML5, the difference being that the data stored with HTML is not explicitly shared with the server unless you use HTML5's sessionStorage. (session storage uses the same API but stores data specifically against the user session and is not persistent beyond session close);
Saving state with the HTML5 API is actually very easy, it is also event driven meaning that an event is fired whenever data is modified allowing you to listen for changes and act accordingly within your javascript / jQuery.
localStorage.name = 'David';

would create a variable within the localStorage called name, with the value David. Close your browser, re-open and console.log the variable, you will notice it persists.
Be wary that localStorage, despite previous documentation will only store strings of data and objects must be serialised and de-serialised if you want to store / retrieve them.
The actual spec is much larger and you can read more about it here:
HTML5 Storage API
Using HTML5 storage
Tips and tricks on using HTML5 storage
If you are not looking for persistant data you can use jQuery's .data() methods to store arbitrary data against a DOM nodefor later use. This is very useful, certainly if you are developing widgets and need to store non persistent state against a DOM node.
Additional:
ie7 and ie8 support is lacking but you can use a framework like modernizr.js to force legacy browser compatibility with HTML 5.

A: I don't know why everyone is telling you to just to use HTML5 localstorage instead. Your issue is one of security.
Please see my comment above, for the community wiki link. Also see https://www.owasp.org/index.php/HTML5_Security_Cheat_Sheet and http://dev.w3.org/html5/webstorage/#security-localStorage


text:
Q: How to show tiny MCE Widgets (Tools or -Icons in Toolbar) in frontend Wordpress? im using the WP Emoji One Plugin, to give the user the chance to add emoticons to there Posts. This Plugin creates an icon in the tiny MCE toolbar. But its only appearing when the author is the admin in wordpress. While some other Plugins appearing for non logged in user as well. How can i change the code to also make this working for non logged in user??
And how to prevent some additional plugins to show up in Tiny MCE toolbar for non logged in user?


text:
Q: Getting value from table that is empty in sqlite android-Showing Null Pointer Exception I'd like to get a value from a table. If the column does not contain any value, then I am going to insert one.
If there is a value, I want to notify the user that a value was inserted already. When my table does not contain anything it shows an error as Java Null Pointer Exception. I want to get a null value from my table. Please help.
                   String qu="select * from userinfos";
                   c=db.rawQuery(qu,null);

                   int count = c.getCount();

                   String[] values = new String[count + 1];
                   int i = 0;
                   for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
                       values[i] = c.getString(c.getColumnIndex("mail"));
                       Toast.makeText(FiveActivity.this, values[i],Toast.LENGTH_LONG).show();
                       i++;
                    }

                   i=0;
                   if(values[i].equals(null))
                   {
                   String    Query =    "insert into userinfos (mail,pass) values ('"+ mailuser+ "','" + password + "')";
                   db.execSQL(Query);
                   Toast.makeText(FiveActivity.this,"Values Inserted",Toast.LENGTH_LONG).show();
                   }
                   else
                   {
                       for(int j=0;j<3;j++)
                       Toast.makeText(FiveActivity.this,"Already one Email-Id:"+ values[i]+" "+"you given. if you want to insert new mail and password then go to Delete app",Toast.LENGTH_LONG).show();

                   }

A: You just need to check your count value like below:
 c=db.rawQuery(qu,null);

 int count = c.getCount();

 if(count==0)
{
////// No data found
}
 else
{
 /////data available
}

getCount ()

Returns the numbers of rows in the cursor
http://developer.android.com/reference/android/database/Cursor.html#getCount

A: this is a simple fonction to manage Usertable or others:
/**
     * Check if data exist in table
     *
     * @param table
     *            The table to check data
     * @param whereArgs
     *            The conditions to check the data
     * @return boolean Return True while data exist; False while data not exist
     */
    public boolean isDataExist(String table, String column, String[] whereArgs) {
        boolean result = false;
        SQLiteDatabase db = this.getWritableDatabase();
        String sql = "select * from " + table + " where " + column + " = ?";
        Cursor cursor = db.rawQuery(sql, whereArgs);
        if (cursor.getCount() > 0) {
            result = true;
        }
        cursor.close();
        db.close();
        return result;
    }


text:
Q: Why is my array of struct not resizing with Array.Resize? I have an array of struct's declared as
public struct classMates
    {
        public string first;
        public string last;
        public string ID;
    }

I am using StreamReader  to read in a .txt file and my variables correspond to their relevant value. ie. first == first name, ID == phone number.
My array of struct is delcared as:
classMates[] classMateInfo = new classMates[43];

I have a method that is supposed to add a new member to my .txt file and append it to the end of my declared array. However, in order to do this, I will need to resize my array + 1 in order for a new member. Otherwise, it just overwrites an existing member.
I have my Array.Resize just after I call my method to add new members. However, once I've finished with that method, StreamWriting incurs and it saves it to variables ready to be written to the file.
static void addClassMates(classMates[] classMateInfo)
    {
        //I DECLARE MY ARRAY RESIZE HERE
        Array.Resize(ref classMateInfo, classMateInfo.Length + 1);
        //I am essentially creating a new space in my array for a new member, below.
        Console.Write("Enter first name: ");
        classMateInfo[classMateInfo.Length - 1].first = Console.ReadLine();
        Console.Write("Enter last name: ");
        classMateInfo[classMateInfo.Length - 1].last = Console.ReadLine();
        Console.Write("Enter phone number: ");
        classMateInfo[classMateInfo.Length - 1].ID = Console.ReadLine();

        Console.WriteLine("Would you like to save the changes back to the file? [Y/N]");
        string temp = Console.ReadLine();
        if ((temp == "Y") || (temp == "y"))
        {
            editNumber(classMateInfo);//A method where it saves it to variables ready to be StreamWritten.
        }
    }

After that, it then moves onto a method to add it into the file. However, with slight debugging I've found there is no new added space in my array for this value I'm trying to enter. I have [42] array placeholders, and with the help of Array.Resize, this should be in actual, [43].
My question is, why is my array not being resized as I ask it to? It seems I have misplaced it, and I really have no clear as to where I should put it.

A: You need to declare your method in the following way:
static void addClassMates(ref classMates[] classMateInfo)
Notice the ref for the parameter.


text:
Q: Можно ли удалить элемент страницы? Например картинку. Можно ли удалить элемент страницы? Например картинку.
A:
$('#pic').remove();
A: Можно.
А если серьезно, и именно средствами php, то:
if(!isset($_GET['wanna delete'])){
  print('');
}

Он не будет рисовать, еслт есть парамерт удаления
A: можно построить DOM дерево документа, найти в нем нужный нод, а потом его удалить. Хотя можно и просто регекспом вырезать подстроку.


text: Q: installing guest additions arch host windows 7 guest i am using vbox versions 6.1.32 and have pacmaned the latest iso for the guest additions suite but there is a snag when i press install it goes through the process and at a particular driver have to run the install again sorry i dont do notes, but yeah it calls exit code 2 with a reason that the driver in question has no signature. is there another source i can download from. im usually pretty good about finding compatible software. maybe a walk through if you have the patience to run it by me?


text:
Q: Angular js select ng-model binding i have a big problem with angularjs.
Here is my code:
Controller:
function testCt($scope){
    $scope.types = [
        {name:'fruit',label:'To Fruit'},
        {name:'meat',label:'To Meat'},
        {name:'other',label:'To Other'}
    ];

    $scope.foods = [
        {name:'apple',type:'fruit'},
        {name:'raptor',type:'meat'}
    ];

    $scope.selected = null;
    $scope.selectFood = function(food) {
        $scope.selected = food;
    }
};

And the view:

            {{food.name}}

    <select data-ng-model='selected' data-ng-options='t.name as t.label for t in types'></select>

    {{selected.name}}
 {{selected.type}}

The problem is, the angular js not binding to select element the food what i clicked.
Here is the fiddle:
http://jsfiddle.net/p7JJs/
When i choose one food from list, the select element not bind to type.
Thank for help :)

A: try this:
data-ng-options="t as t.label for t in types"

fiddle
you have to set t as reference, not t.name (no attributes name or type in t.name)

A: Try this:
Change Your controller function
From
   $scope.selectFood = function(food) {
   $scope.selected = food;
   }

To
   $scope.selectFood = function(food) {
   $scope.selected = food.type;
   }

It will work..

A: Did you try ngSelected? Here're the docs:
https://docs.angularjs.org/api/ng/directive/ngSelected


text:
Q: Install Splunk Universal Forwarder to OpenShift I tried googling it but without any luck, also I tried searching official mailing lists, but also without any information.
Is it possible to install Splunk Universal Forwarder to OpenShift platform?


text:
Q: How to remove "Quick edit" option in "register_post_meta" list page I am using register_post_type in list page automatically it is four actions Edit/Quick Edit/trash/View. I want to remove "Quick edit" option from list page. How I can do this.

A: /*------------------------------------------------------------------------------------
    remove quick edit for custom post type videos just to check if less mem consumption
------------------------------------------------------------------------------------*/
add_filter( 'post_row_actions', 'remove_row_actions', 10, 2 );
function remove_row_actions( $actions, $post )
{
  global $current_screen;
    if( $current_screen->post_type != 'videos' ) return $actions;
    unset( $actions['edit'] );
    unset( $actions['view'] );
    unset( $actions['trash'] );
    unset( $actions['inline hide-if-no-js'] );
    //$actions['inline hide-if-no-js'] .= __( 'Quick Edit' );

    return $actions;
}

It worked for me check with yours


text:
Q: How to run Flask on Public IP of EC2? I have used Flask in Python to create a simple web application. I have also created a Windows Amazon EC2 instance. What I would like to do, is be able to host the web application on the Public IP address associated with the EC2 instance, so that the web application can be accessed from anywhere on the Internet. In order to achieve this, I have added the Public IP of the EC2 instance to the host parameter inside app.run(). Thus, my Python code looks like this:
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')

def home():
  return render_template("index.html")

if __name__ == "__main__":
  app.run(host = "5.13.*.*")

However, when I run this code inside of the virtual machine I get this error:
OSError: [WinError 10049] The requested address is not valid in its context

Does anybody know how I could fix this? Basically what I would like to do is to have my Flask server be accessed remotely from any network, and not just my localhost, but I don't know if I'm going about it the wrong way. Any help is much appreciated!


text:
Q: How to add Bearer and Scope when using HttpWebRequest with XML post I have tried the following but still fails authentication
string requestXml = doc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "application/xml; charset=UTF-8;";
request.ContentLength = bytes.Length;
request.Method = "POST";
request.Headers.Add("Authorization", $"Bearer {accessToken} scope=myendpoint");

I have also tried
request.Headers.Add("scope", "myendpoint");

A: You first acquire a token via a series of HTTP requests/responses, then use this token as a bearer token in a subsequent API call (a new HTTP request/response).  The way you acquire a token depends on the protocol. If the protocol is oAuth v2 and (for example) you're doing client credentials grant type/flow, scope is an optional request parameter. The request might look like this:
String serviceURL = "https://blah.accesscontrol.windows.net/...";
String body = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope={2}", "<client id>","<client secret>","<scope>");

System.Net.WebRequest webRequest = System.Net.WebRequest.Create(serviceURL);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";

byte[] payload = System.Text.Encoding.ASCII.GetBytes(body);
webRequest.ContentLength = payload.Length;
using (System.IO.Stream outputStream = webRequest.GetRequestStream())
{
    outputStream.Write(payload, 0, payload.Length);
}
System.Net.WebResponse webResponse = webRequest.GetResponse(););
// extract token from response

Adding a bearer token:
request.Headers.Add("Authorization", "Bearer " + token);


text:
Q: what does pause track mean in play console I have uploaded an app in open testing (Release type) to let people use my app but without giving reviews to my app. Everything works well, many people used my app and really like it. So now I decided to release it in production (available for the world). I did that as well. But I want to remove the open testing app. So I saw an option Pause track in-play console (play.google.com). I have already made mistakes that took me days to re-correct them. So now I don't want any risks. Do the pause track button will remove the open testing or the production also.

A: See there are Four types of releases on play console for android developers;
1. Internal testing - It means you wanna share your app among the decided members. It means you have to put their Gmail into the testers list. This is usually for employees.
2. Alpha testing - Same as internal testing, but this time you can send your app to your friends, families or on your smartphones.
3. Beta testing - This is a serious matter, this is public testing. But people cannot give reviews to your app. You can also limit how many users can install the app.
4. Production - This is the last release, now everybody can install your app, can give reviews, can report to google play if something bad is there. One more thing, now your app appears in play store search listing.
So pause track means pausing that type of release. If you pause beta testing then the beta version will be removed from play store (actually hidden). Each release has its own pause button in their own page. Like you can see above.


text:
Q: Spring ContextLoader Error I tried to run JBilling Community Edition app. I have configured it properly (I think I do), but I have an error during the start up. All logs are below:
C:\dev\JAVA\jdk1.8.0_131\bin\java -Dgrails.home=C:\dev\grails-2.5.6 -Dtools.jar=C:\dev\JAVA\jdk1.8.0_131\lib\tools.jar -Dgroovy.starter.conf=C:\dev\grails-2.5.6/conf/groovy-starter.conf -Djline.WindowsTerminal.directConsole=false -javaagent:C:\dev\grails-2.5.6\lib\org.springframework\springloaded\jars\springloaded-1.2.7.RELEASE.jar -noverify -Dspringloaded=profile=grails;cacheDir=. -Dbase.dir=E:\workspace\jbilling\JBilling\jbilling-community-4.1.1 -Dfile.encoding=UTF-8 -classpath C:\dev\grails-2.5.6\lib\org.codehaus.groovy\groovy-all\jars\groovy-all-2.4.10.jar;C:\dev\grails-2.5.6\dist\grails-bootstrap-2.5.6.jar org.codehaus.groovy.grails.cli.support.GrailsStarter --main org.codehaus.groovy.grails.cli.GrailsScriptRunner --conf C:\dev\grails-2.5.6/conf/groovy-starter.conf "run-app -plain-output"
|Loading Grails 2.5.6
|Configuring classpath
.
|Environment set to development
.................................
|Packaging Grails application
.............Setting license in jbilling.properties from license.txt
.....Loading configuration files from classpath
Checking the connection to the DB...
Connected to the DB successfully!!!
.....................................Loading configuration files from classpath
.2017-09-12 14:12:54,101 0     INFO  [grails.plugin.webxml.WebxmlGrailsPlugin] (main:) Loading default config file: class DefaultWebXmlConfig
2017-09-12 14:12:54,115 14    WARN  [grails.plugin.webxml.WebxmlGrailsPlugin] (main:) Did not find application config file: WebXmlConfig
2017-09-12 14:12:54,812 711   INFO  [grails.plugin.webxml.WebxmlGrailsPlugin] (main:) Loading default config file: class DefaultWebXmlConfig
2017-09-12 14:12:54,836 735   WARN  [grails.plugin.webxml.WebxmlGrailsPlugin] (main:) Did not find application config file: WebXmlConfig

|Running Grails application
.Setting license in jbilling.properties from license.txt
.....2017-09-12 14:12:55,408 1307  INFO  [org.apache.coyote.http11.Http11NioProtocol] (main:) Initializing ProtocolHandler ["http-nio-8080"]
2017-09-12 14:12:55,440 1339  INFO  [org.apache.tomcat.util.net.NioSelectorPool] (main:) Using a shared selector for servlet write/read
Loading configuration files from classpath
2017-09-12 14:12:56,149 2048  ERROR [org.springframework.web.context.ContextLoader] (localhost-startStop-1:) Context initialization failed
java.lang.IllegalAccessError: tried to access method org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingletonMutex()Ljava/lang/Object; from class org.springframework.context.event.AbstractApplicationEventMulticaster
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)
2017-09-12 14:12:56,150 2049  ERROR [org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener] (localhost-startStop-1:) Error initializing the application: tried to access method org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingletonMutex()Ljava/lang/Object; from class org.springframework.context.event.AbstractApplicationEventMulticaster
java.lang.IllegalAccessError: tried to access method org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingletonMutex()Ljava/lang/Object; from class org.springframework.context.event.AbstractApplicationEventMulticaster
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

Process finished with exit code 1

Maybe somebody has a clue how to fix it? Any advices? I would appreciate that. It seems that the app is ok, but the only problem is spring in here?

A: I believe the problem could be the grails version you have 'grails-2.5.6'.
The jB CE 4.x version is based on grails-2.4.3. You should use that.


text:
Q: How do I get started with SQL databases in C#? I am going to use C# to access a SQL database, initializing a connection and create tables and editing stuff, so is SQL Server required to start using SQL queries in C# ?

A: No.
SqlClient (System.Data.SqlClient) is included as part of .NET framework, but you'd be wise to get a connection to an SQL server at some stage so that you can test your connection code.

A: You can connect to just about any SQL database using C# and .NET.
Microsoft's tooling works best with Microsoft SQL server, so if you want to experiment with SQL access in .NET, set up Microsoft SQL server on your development machine.
I suggest you try the free Microsoft SQL Server Express Edition (use the "Download ... with tools" link).


text:
Q: Android NDK cpp library where is located and where is loaded? I have a simple cpp library which returns a string value. This was made similar as in the https://developer.android.com/studio/projects/add-native-code.html
After building the apk, after analyzing it I see a lib folder which contains .so files for different ABIs.
My questions is: since the generated files are included in the apk itself, from where and to where does System.loadLibary(String) take action?
Is the library file within the private app's folder and only accessible to the app, after it's being loaded? Do other apps have access to this library once it has been loadLibrary in my app? Is it copied somewhere in the android system folder?

A:
Loads the dynamic library with the specified library name. A file
  containing native code is loaded from the local file system from a
  place where library files are conventionally obtained. The details of
  this process are implementation-dependent. The mapping from a library
  name to a specific filename is done in a system-specific manner.

Source: https://developer.android.com/reference/java/lang/Runtime.html#loadLibrary(java.lang.String)
The library is not copied to a shared location when it is loaded. Loading a library means its symbols are linked to native methods.


text:
Q: Getting syntax error in field definition while altering table of ms access using vb .net I want to alter a table and add multiple columns to my table but I am getting error

syntax error in field definition

I am working with vb.net and MS Access 2013.
Here is my code:
cmd.Connection = con

cmd.CommandText = "ALTER TABLE Game_Player ADD QUESTIONS TEXT(50),USER_ANSWER TEXT(10),TIME TEXT(10),SECOND (10),lbl_Lock TEXT(10),lbl_vis TEXT(10)"
cmd.ExecuteNonQuery()

A: Access SQL does support adding multiple columns with one ALTER TABLE statement.
The field definition error likely occurs due to the lack of a data type for the SECOND field.  However two of the column names, SECOND and TIME, are  reserved words. (Also see the link @Andrew provided.)  Those names may also trigger errors, but it's not always easy to predict when they will cause trouble. The safest alternative would be to choose column names which are not reserved words.  If you must keep those names, bracket them in your SQL statement ...
ALTER TABLE Game_Player
ADD COLUMN
    QUESTIONS TEXT(50),
    USER_ANSWER TEXT(10),
    [TIME] TEXT(10),
    [SECOND] TEXT(10),
    lbl_Lock TEXT(10),
    lbl_vis TEXT(10)

I included the COLUMN keyword and assumed TEXT as the data type for SECOND.


text:
Q: Highcharts: How to show marker in X range chart? I am trying to plot a marker in X range chart. (For example: After Sprint4, I would like to show a circular milestone in DEV category). Refer following JS fiddle.
Demo: https://jsfiddle.net/amrutaJgtp/jgn9bLak/56/
{
    type: "scatter",
    x: Date.UTC(2014, 5, 3),
    //x2: Date.UTC(2014, 4, 31),
    y: 0,
    marker: {
      enabled: true,
      symbol: 'circle',
      fillColor: "yellow",
      lineWidth: 1
    }
  },

Is there any way to achieve this?

A: I would suggest you make a separate series for scatter-points to keep these circular milestones since xRange does not support this point format. For example:
series: [{
  name: 'milestones'
  type: 'scatter',
  stickyTracking: false,
  marker: {
    enabled: true,
    symbol: 'circle',
    fillColor: "yellow",
    lineWidth: 5,
    radius: 10
  },
  data: [{
    x: Date.UTC(2014, 5, 3),
    y: 0,
  }]
},
...
]

You could also change marker per point, to have different shapes for different points. In addition to this, you would need to change your tooltip formatter like this:
tooltip: {
  formatter: function() {
    if (this.series.name != 'milestones') {
      ...
    }
  }
}

Working example: https://jsfiddle.net/jgn9bLak/90/

A: As @ewolden said you need to create a another serie, here is another example:
https://jsfiddle.net/code4jhon/oL83jty5/
 {
    // Second series
    name: 'Granted',
    color: 'green',
    id: 'blue',
    marker: {
      symbol: 'diamond'
    },
    dataRaw: [{
      y: 1,
      xRanges: [
        // first value: from; second value: to
        [toMs(2006, 10), toMs(2006, 10)]
      ]
    }]
  }


text:
Q: CentOS Mondo Rescue Error to Restore the iso: Kernel Panic I am trying to create an image (.iso) of my installed CentOS 5.11 system, for this i am using the "Mondo Rescue" with the command:
mondoarchive -Oi -9 -L -d /tmp/centos_iso -I / -T /tmp/centos_iso -p centos_image -s 4480m -E "/tmp|/var/spool/squid|/var/log"
The image is generated, and apparently is functional.
To install the iso in other machine i'm using the option "Nuke", in initialization page of "Mondo Rescue", like is represented in below image

When attempting to perform the installation, the following error occurs during the process:
Kernel panic - not syncing: No init found. Try passing init= options to kernel.


text:
Q: Shutil cannot import WindowsError on windows I've observed that shutil fails to import WindowsError on our windows 7 systems:
    from shutil import WindowsError
    File <file>, line <no>, in <module>
        from shutil import WindowsError
    ImportError: cannot import name WindowsError

The same statement works absolutely fine on linux. Has anyone else come across it too? Do you know how I could fix it?
Python version: 2.6.7
Linux OS: Centos 6.3
Windows OS: Windows 7 Professional x64

A: Got a solution from the python bug tracker:
http://bugs.python.org/issue18525
This is an implementation artifact and would not be fixed. The import statement such as above are a wrong usage. The correct usage being(if necessary):
try:
    WindowsError
except NameError:
    WindowsError = None


text:
Q: How to apply a Doctrine filter to a whole bundle in Symfony? I would like to use the SoftDeleteable behavior extension for Doctrine2 in my Symfony2 application to hide deactivated users and entities related to them. This is great and simple solution for the frontend, but I would like to disable this filter for the administration section to make it possible to re-enable these entities. The admin section is located in a separate bundle.
The documentation says it is as easy to disable this filter as writing this line before querying the repository:
$em->getFilters()->disable('soft-deleteable');

Now I would like to ask if there is any way to disable this behaviour for the whole admin bundle to make unsetting this filter for every related controller action unnecessary.
Thank you.

A: You detect bundle name and decide, whether to enable or disable filter.
If you wonder where to perform enabling/disabling, check this answer

A: Tomáš's links helped me to solve the problem. Even though it might not be the best solution that's how I implemented it:
I created a PHP class:
namespace Acme\AdminBundle\EventListener;

use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

class SoftDeleteListener {

    public function onKernelController(FilterControllerEvent $event) {
        // Get the full name of the current controller
        $controllername = $event->getRequest()->attributes->get('_controller');

        $matches = array();
        // Explode the name of the current controller
        preg_match('/(.*)\\\(.*)Bundle\\\Controller\\\(.*)Controller::(.*)Action/', $controllername, $matches);

        // preg_match should store the name of the bundle at the second index of the array
        if (isset($matches[2]) && $matches[2] == "Admin") {
            $controller = $event->getController();
            $doctrine = $controller[0]->get('doctrine');
            $em=$doctrine->getManager();
            $em->getFilters()->disable('softdeleteable');
        }
    }
}

And added these lines to services.yml to make it listen to the kernel.controller event:
kernel.listener.admin_softdelete_listener:
        class: Goldfish\AdminBundle\EventListener\SoftDeleteListener
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

That way I reached my goal - the softdeletable filter is disabled for the whole AdminBundle and I don't need to turn it off manually in every single controller.


text:
Q: Several Zend framework projects in the same root folder Zend Framework project structure presumes you run only one application per server, like
localhost/guessbook, where controllers and stuff are located one folder above that level.
How can I have a few different ZF-based projects in my localhost so that to address them like I do with regular php script apps - with localhost/app1, localhost/app2?
Ideally, I want to do without DocumentRoot, I want to switch between apps instantly using browser.

A: I don't quiet understand what's the problem? Perhaps you're referring at typical rewrite rules that send to /index.php? Well, you can change that rewriting rules from
RewriteRule ^.*$ /index.php [NC,L]

to
RewriteRule ^/app1/.*$ /app1/index.php [NC,L]
RewriteRule ^/app2/.*$ /app2/index.php [NC,L]

In bootstrap.php you define all the include path, so you can have Zend Framework libraries shared.

A: I think that you are wrong on this one. You can have multiple zend framework application on the same hostname. I.e. i've been using multiple magento's installation on my server in order to try out things. Zend doesn't have fixed file structure as far as i know (one of the reason of my choice of framework)
You can place even place Zend Library outside the webroot folder and call it with something like this:
$lib = realpath(dirname(basename(__FILE__)) . '/../../../lib');
set_include_path(get_include_path() . PATH_SEPARATOR . $lib);

$rootDir = dirname(dirname(__FILE__));
        define('ROOT_DIR', $rootDir);

        set_include_path(get_include_path()
            . PATH_SEPARATOR . ROOT_DIR . '/library/'
            . PATH_SEPARATOR . ROOT_DIR . '/app/models/'
        );

        include 'Zend/Loader.php';
        spl_autoload_register(array('Zend_Loader', 'autoload'));

        // Load configuration
        Zend_Registry::set('configSection', $configSection);
        $config = new Zend_Config(new Zend_Config_Ini(ROOT_DIR.'/application/config.ini', $configSection));
        Zend_Registry::set('config', $config);

A: You can do that by making Zend Library shared with your multiple projects this Url will show you how can you do that
http://www.mauriciocuenca.com/blog/2009/03/two-or-more-zend-framework-projects-on-a-shared-host/
beside that in wamp you can configure Vhost to make multiple local domain:
http://mikebernat.com/blog/Adding_Virtual_Hosts_to_Apache_&_Wampserver


text:
Q: Very slow sites on plesk 12 , nginx having 7000+ connections 'm using plesk 12 on dedicated i5 2300 16 gb ram server.
Apache is main web server and nginx is set as reverse proxy. If i stop nginx site runs ok but after a while they take too long to open but connections goes down from 7000+ to few 100.
If i start nginx site runs ok but after a while they take too long to open and connections goes up from 100 to 7000+.


text:
Q: Selenium-webdriver java dropdown issue element should have been select I have HTML code for dropdown:
<div class="column two">
<select id="CCType" name="CCType">
    <option value="">Please select...</option>
    <option value="Mcard">Master Card</option>
    <option value="Visa ">VISA</option>
</select>

My script:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].select();", selectCreditCardType);
selectCreditCardType.selectByValue("Visa");

or
selectCreditCardType.selectByVisibleText(customer.creditCardType);

Result: Element should have been select but was input.
Tried different options from stackoverflow: Selenium webdriver C# CSS dropdown Issue - Element should have been select but was div
But no luck yet.

A: It should work if you utilize the OpenQA.Selenium.Support.UI.SelectElement class
C# example:
    var selElement = new OpenQA.Selenium.Support.UI.SelectElement([Web Element goes here]);
    foreach (var option in selElement.Options)
    {
      if (option.Text == "desired text here")
         selElement.SelectByText(Option.Text);
    }

You can also do by value, but that would be a get attribute selection and comparison on the option of the select element.
    option.GetAttribute("value");


text:
Q: Error on installing packages on python I tried to install pandas on my cmd and this is the output
Requirement already satisfied: pandas in c:\users\name\anaconda3\lib\site-packages (0.23.0)
Requirement already satisfied: python-dateutil>=2.5.0 in c:\users\name\anaconda3\lib\site-packages (from pandas) (2.7.3)
Requirement already satisfied: pytz>=2011k in c:\users\name\anaconda3\lib\site-packages (from pandas) (2018.4)
Requirement already satisfied: numpy>=1.9.0 in c:\users\name\anaconda3\lib\site-packages (from pandas) (1.14.3)
Requirement already satisfied: six>=1.5 in c:\users\name\anaconda3\lib\site-packages (from python-dateutil>=2.5.0->pandas) (1.11.0)

**distributed 1.21.8 requires msgpack, which is not installed.**

This last line is in red.
Im on windows 10, I installed anaconda

A: This seems to work for me.
First I tried
pip install msgpack

And if you need this too,
pip install msgpack-python

Then install whatever you need. In your case,
conda install pandas

A: You should install msgpack and then install pandas again.

A: How are you installing pandas? If you're using Anaconda, then
conda install pandas

is typically enough to make everything work. This is because Anaconda is using binary installs - it is uploading prebuilt code and has already done the combinatorics to make everything work together - and it gets everything it needs for a package.
Sometimes, of course, you have to go into a dependency combination that is tough, or you are pulling from non-core Anaconda repos, etc. In that case, you can try
conda install msgpack
# or
pip install msgpack
# or
conda install -c conda-forge msgpack

The right choice sort of depends on what you're doing. Using the -c flag with conda gives you access to non-core repositories - these carry fewer guarantees about working together, but gives you access to many more versions of the package, usually.

A: I am getting a similar error when trying to install pymc3. I solved it by using conda rather than pip.
The first time I used pip install pymc3 and I got the same error as you:
distributed 1.21.8 requires msgpack, which is not installed

Then I installed using conda instead: conda install pymc3, and it installed fine.
My understanding is that conda handles all the dependent packages for you, which pip does not.

A: I found this on the Anaconda site:
Use anaconda to install msgpack for python with this command:
conda install -c conda-forge msgpack-python

It seems to have worked for me.

A: conda install pip
pip uninstall -y msgpack-python
pip install msgpack
TCIP-scheduler

run these commands


text:
Q: how to create a Custom list model in Java I'm trying to create list that shows contacts, each list item shows the name on a line, and the phone number on a second line, and maybe an image or icon. I was thinking of using two labels for that, but i can figure out how to use a custom list model to implement this.
My first attempt was to add a Panel object that contained the info i wanted in the list, then add it to an instance of the defualt list model, but that only turned up the class name in the list.
    DefaultListModel Clistmodel = new DefaultListModel();//
    Clistmodel.addElement(Contact);//Contact is an JPanel object
    GroupList.setModel(Clistmodel);//GroupList is the List object

this didn't work out at all then i learnt that the default list model only knows how to render strings i think, so i have to create a custom list model, or a custom ListCellRenderer, i don't really know which will solve the problem.

A: Your question asks how to create a custom list model, however, that's not what you need (I don't think) as a DefaultListModel will work nicely for you. Rather you will need to work on the renderer. You need to create a non-GUI class to hold your information that each item will display, probably your Contact class, and then create a JList that holds this in its DefaultListModel.
The key for you will be to then create a custom list cell renderer to display the information on multiple lines -- perhaps a JTextArea, or a JPanel that holds two JLabels in a GridLayout. Please understand that the renderer does not display the actual underlying components, but something more akin to a stamped image of whatever components you're trying to display, so it will not have the full behaviors available to it as the actual component would. It will take work, but the writing a renderer section of the tutorial linked to by user714965 will show you how to do this.
Please give it a try, and then if you still are stuck, come on back with your code, your errors, and your questions, and we'll be better able to give you specific help.


text:
Q: How to make object rotate with drag, how to get a rotate point around the origin use sin or cos? I've been searching long time, but can't find a better way solve my problem,
make div draggable, rotate and resize by each handle like these 2 example 1 2,, now it can be draggable, but rotate..
Regarding Prasanth K C, Chango, Yi Jiang ..'s answer, these code maybe not correct,
1. it should have a rotate point around the origin.
2. need to consider radius.
But I don't know how to use sin or cos here to make rotate consider radius?
Any suggestion will be be appreciated.
http://jsfiddle.net/tBgLh/8/
var dragging = false, target_wp;
$('.handle').mousedown(function(e) {
    var o_x = e.pageX, o_y = e.pageY; // origin point
    e.preventDefault();
    e.stopPropagation();
    dragging = true;
    target_wp=$(e.target).closest('.draggable_wp');

    $(document).mousemove(function(e) {
        if (dragging) {
            var s_x = e.pageX, s_y = e.pageY; // start rotate point
            if(s_x !== o_x && s_y !== o_y){ //start rotate
                var s_rad = Math.atan2(s_y, s_x);
                var degree = (s_rad * (360 / (2 * Math.PI)));
                target_wp.css('-moz-transform', 'rotate(' + degree + 'deg)');
                target_wp.css('-moz-transform-origin', '50% 50%');
                target_wp.css('-webkit-transform', 'rotate(' + degree + 'deg)');
                target_wp.css('-webkit-transform-origin', '50% 50%');
                target_wp.css('-o-transform', 'rotate(' + degree + 'deg)');
                target_wp.css('-o-transform-origin', '50% 50%');
                target_wp.css('-ms-transform', 'rotate(' + degree + 'deg)');
                target_wp.css('-ms-transform-origin', '50% 50%');
            }
        }
    })
    $(document).mouseup(function() {
        dragging = false
    })
})// end mousemove

html

A: There are two problems with your approach:

*

*The origin shouldn't be where the user clicked (that is the handle), but a fixed point in your div:
target_wp=$(e.target).closest('.draggable_wp');
//var o_x = e.pageX, o_y = e.pageY; // origin point
var o_x = target_wp.offset().left,
    o_y = target_wp.offset().top; // origin point

You will use the clicked point also, but for something else (more later):
var h_x = e.pageX, h_y = e.pageY; // clicked point

Finally, the origin should be fixed (i.e. should not change between rotations). One way of doing so is preserving it as a data attribute (there are other options though):
if ( !target_wp.data("origin") )
    target_wp.data("origin", { left:target_wp.offset().left,
                               top:target_wp.offset().top    });
var o_x = target_wp.data("origin").left,
    o_y = target_wp.data("origin").top; // origin point

Update: One good candidate for the origin is the CSS property transform-origin, if present - it should ensure that the mouse follow the handle as closely as possible. This is an experimental feature, however, so the actual resulsts may vary. P.S. I'm not sure setting it to 50% 50% is a good idea, since the transformation itself may vary the element's width and height, top and left.

*To find the angle, you should not call atan2 on the mouse point only, since it will only calculate the angle between that point and the top left corner of the page. You want the angle between that point and the origin:
var s_rad = Math.atan2(s_y - o_y, s_x - o_x); // current to origin

That'll lead you halfway, but it will still behave oddly (it will rotate around the element origin, but not following the handle as you expect). To make it follow the handle, you should adjust the angle in relation to the clicked point - which will serve as a base for the amount to rotate:
s_rad -= Math.atan2(h_y - o_y, h_x - o_x); // handle to origin

After that you get the rotation working (for one user iteration at least).
You'll notice the handle does not follow the mouse precisely, and the reason is the choice of the origin point - defaulting to the element's top/left corner. Adjust it to somewhere inside the element (maybe using a data- attribute) and it should work as expected.
However, if the user interacts with the handle multiple times, it's not enough to just set the rotation angle, you must update whatever it was during the last iteration. So I'm adding a last_angle var that will be set on the first click and then added to the final angle during drag:
// on mousedown
last_angle = target_wp.data("last_angle") || 0;

// on mousemove
s_rad += last_angle; // relative to the last one

// on mouseup
target_wp.data("last_angle", s_rad);

Here's the final working example. (Note: I fixed the nesting of your mouse handlers, so they don't get added again after each click)

$(function () {
    var dragging = false,
        target_wp,
        o_x, o_y, h_x, h_y, last_angle;
    $('.handle').mousedown(function (e) {
        h_x = e.pageX;
        h_y = e.pageY; // clicked point
        e.preventDefault();
        e.stopPropagation();
        dragging = true;
        target_wp = $(e.target).closest('.draggable_wp');
        if (!target_wp.data("origin")) target_wp.data("origin", {
            left: target_wp.offset().left,
            top: target_wp.offset().top
        });
        o_x = target_wp.data("origin").left;
        o_y = target_wp.data("origin").top; // origin point

        last_angle = target_wp.data("last_angle") || 0;
    })

    $(document).mousemove(function (e) {
        if (dragging) {
            var s_x = e.pageX,
                s_y = e.pageY; // start rotate point
            if (s_x !== o_x && s_y !== o_y) { //start rotate
                var s_rad = Math.atan2(s_y - o_y, s_x - o_x); // current to origin
                s_rad -= Math.atan2(h_y - o_y, h_x - o_x); // handle to origin
                s_rad += last_angle; // relative to the last one
                var degree = (s_rad * (360 / (2 * Math.PI)));
                target_wp.css('-moz-transform', 'rotate(' + degree + 'deg)');
                target_wp.css('-moz-transform-origin', '50% 50%');
                target_wp.css('-webkit-transform', 'rotate(' + degree + 'deg)');
                target_wp.css('-webkit-transform-origin', '50% 50%');
                target_wp.css('-o-transform', 'rotate(' + degree + 'deg)');
                target_wp.css('-o-transform-origin', '50% 50%');
                target_wp.css('-ms-transform', 'rotate(' + degree + 'deg)');
                target_wp.css('-ms-transform-origin', '50% 50%');
            }
        }
    }) // end mousemove

    $(document).mouseup(function (e) {
        dragging = false
        var s_x = e.pageX,
            s_y = e.pageY;

        // Saves the last angle for future iterations
        var s_rad = Math.atan2(s_y - o_y, s_x - o_x); // current to origin
        s_rad -= Math.atan2(h_y - o_y, h_x - o_x); // handle to origin
        s_rad += last_angle;
        target_wp.data("last_angle", s_rad);
    })
})
.draggable_wp {
    position: absolute;
    left: 150px;
    top: 150px;
}
.el {
    width: 25px;
    height: 50px;
    background-color: yellow;
}
.handle {
    position: absolute;
    left:0;
    top:-75;
    width: 25px;
    height: 25px;
    background-color: blue;
}

A: They use a matrix function in a transform properties. You can rotate element by muliplay your matrix (element coordinates) by rotation matrix.
transform:  matrix(a, c, b, d, tx, ty)

More info and examples here: The CSS3 matrix() Transform for the Mathematically Challenged


text:
Q: Excel IF statement based on the highest value cell I have put together a spreadsheet used for scheduling and currently I have the following columns-
'Start Time' 'Job Details' 'Planned Print Time' Actual Print Time'

The time column is formatted as such =A3+TIME(0, D3,0) so that it utilises the planned print time and automatically update the next time time to coincide with previous finish time.
what I would like to do is have this formula use either 'planned print time' or 'actual print time' dependant on which value is higher.
hope this makes sense. thank you in advance for help.

A: You can you use the if statement as long as the date formats you are using can be compared.
= if(date1 > date2, date1, date2)

This will return the highest date to the cell, again assuming your date fields can be compared.


text:
Q: How to Change a Visibility Window property from the one form to another? In my current project. I click a button and the main form will set the ShowIcon false and the Visibility to false. Once I terminate the second window, I want to see the main form again. By resetting both properties to true. How is that possible?
As well where would I place the code.

A: You can overRide the OnFormClossing event
protected override void OnFormClosing(FormClosingEventArgs e)
{
     // code that u want
}

A: Place this code in your button_click event:
newform nf = new newform(); //or whatever the name of your second form is
this.Hide(); //to hide your mainform
nf.ShowDialog();
this.Show(); //to show your mainform after closing your new form
nf.Dispose(); //optional


text:
Q: Is there a way to use MSTest to run all tests for a set of parameters? I just have one parameter that can take two values. I would like to see two sets of my tests in the test runner, one for the first value, one for the second. How can I do this?

A: Can use the [DataSource] attribute too:
http://callumhibbert.blogspot.com/2009/07/data-driven-tests-with-mstest.html
http://codeclimber.net.nz/archive/2008/01/18/How-to-simulate-RowTest-with-MS-Test.aspx

A: MSTest is very limited, but it never really troubled me. You can do parameterized tests like this:
[TestMethod] public void SomeMethod_WithValidArgs1_Succeeds()
{
    Assert_ThatSomeMethodSucceeds(0, "bla");
}

[TestMethod] public void SomeMethod_WithValidArgs2_Succeeds()
{
    Assert_ThatSomeMethodSucceeds(1, "bla");
}

[TestMethod] public void SomeMethod_WithValidArgs3_Succeeds()
{
    Assert_ThatSomeMethodSucceeds(1, "funcy");
}

private static void Assert_ThatSomeMethodSucceeds(
    int param1, string param2)
{
    // Act
    SubSystem.SomeMethod(param1, param2);
}


text:
Q: Finding isolated links in a network of links with PostgreSQL I have a street network from many of links in a PostgreSQL table. Some links have no connection to the network. I want to isolate these links from the network. Each link has a geometry (geom) and id column.
How can I get the linkids from the network, which don't touch any other links?
Maybe the function is st_touches, but how can I ask this on the whole network from each link?

A: On a properly noded network, you could use also use st_intersects
So, one could select all records where no other records (with a different ID) intersects. It would be querying the same layer twice:
SELECT l1.id
FROM links l1
WHERE NOT EXISTS
 (SELECT 1
  FROM links l2
  WHERE l1.id != l2.id
  AND ST_INTERSECTS(l1.geom, l2.geom)
 )


text:
Q: How to add month to an export macro name? i have an macro that exports worksheets to pdf's to a designated folder using their sheet name. What I would like is to add the month in as part of the filename. I can retrieve this from a cell in my workbook. Where in my code would I add this reference to?

Dim outFldr As String
Dim ws As Worksheet
Dim i As Variant, sheets_to_select As Variant

outFldr = ActiveWorkbook.Path
sheets_to_select = Array("Summary", "PLC", "MI", "Venture", "EIS", "VCT", "PE", "Debt")

For Each i In sheets_to_select
   ThisWorkbook.Sheets(i).ExportAsFixedFormat Type:=xlTypePDF, _
    Filename:=outFldr & "\" & i & ".pdf", _
    Quality:=xlQualityStandard, IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, OpenAfterPublish:=False

Next i
MsgBox ("All pdf's exported.")
End Sub

A: Read the date from Excel, use for example format to get the month number or name and add that to the file name. I prefer to use intermediate variables as this makes the code much easier to read and debug.
Adapt the format to create the pattern you want - you could also include the year.
For Each i In sheets_to_select
    Dim filename As String, filedate As Date, month As String
    filedate = ThisWorkbook.Sheets(1).Range("A1")       ' Change this so that it reads your cell with the date

    month = Format(filedate, "mm") ' For month as 2-digits
    month = Format(filedate, "mmm") ' For month as 3 letters month name
    month = Format(filedate, "mmmm") ' For month as full month name

    filename = outFldr & "\" & i & "_" & month & "_.pdf"

    ThisWorkbook.Sheets(i).ExportAsFixedFormat Type:=xlTypePDF, _
        filename:=filename, _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, OpenAfterPublish:=False
Next i


text:
Q: self.layer renderInContext:context in drawRect method gives Bad Access in ipad but not in simulator I am working in an app and in which i do the video recording. Now what i do is capture the images and then create the video the code is as follows
- (void) drawRect:(CGRect)rect {
    NSDate* start = [NSDate date];

    CGContextRef context = [self createBitmapContextOfSize:self.frame.size];
    NSLog(@"context value %@",context);

    [self.layer renderInContext:context];

    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    UIImage* background = [UIImage imageWithCGImage: cgImage];
    CGImageRelease(cgImage);
    self.currentScreen = background;

    if (_recording) {
        float millisElapsed = [[NSDate date] timeIntervalSinceDate:startedAt] * 1000.0;
        [self writeVideoFrameAtTime:CMTimeMake((int)millisElapsed, 1000)];

    }

      float processingSeconds = [[NSDate date] timeIntervalSinceDate:start];
      delayRemaining = (1.0 / self.frameRate) - processingSeconds;

      [self performSelectorInBackground:@selector(setNeedsDisplay) withObject:nil];

}

Now the problem is that the method is called recursively and when stop recording it gives me Exc_Bad_Access.
It works fine in simulatoor bot crash in  device, How can i solve this issue?

A: You shouldn't be doing this in drawRect:, the only reason to override drawRect: is to do some custom drawing (which you are not). You also shouldn't call setNeedsDisplay on a background thread, this is a GUI method which can only be called from the main thread. Also depending on how your createBitmapContextOfSize: method and your environment you might need to release your bitmap context object.


text:
Q: Natural Collocations (Finance) Could you please tell me what the native-like option for this case is:

He diversifies his stock portfolio

OR

He varies his stock portfolio.

I am talking about the stock market (finance).

A: Probably the former.
We generally say something varies if it changes over time. Diversifying a stock portfolio means investing it so that multiple securities with different risk profiles are held at the same time.
So

He diversifies his stock portfolio

means the portfolio contains a diversity of risks at any single moment, but doesn't say anything about whether this diverse portfolio ever needs adjustment, whereas

He varies his stock portfolio

means that he changes the contents of the portfolio over time.


text:
Q: If multiprocessing is doing X processes, there is a way to make another multiprocessing use total cpu process minus X? Specifications regarding the CPU of my computer that uses Windows 11 (values retrieved while a 4-task multiprocessing was running):
import psutil
import multiprocessing

print(multiprocessing.cpu_count())
# 12
print(psutil.cpu_count())
# 12
print(psutil.cpu_count(logical=False))
# 6
print(len(psutil.Process().cpu_affinity()))
# 12

I have two different projects that run on my computer at the same time throughout the day, both of which sometimes need to use multiprocessing.
Currently, as the maximum number of rows in dataframe of each project is 4, so the total maximum they can reach if activated together will be 8 process.
So I can keep it like this:
def stackoverflow(stack):
    df = create_dataframe(stack)
    if len(df) == 0:
        pass
    else:
        try:
            max_process = multiprocessing.cpu_count()-1 or 1
            pool = multiprocessing.Pool(max_process)
            list_pool = pool.map(data_event, zip(repeat(stack), df.iterrows()))
        finally:
            pool.close()
            pool.join()

But, let's say that now I want to leave the dataframe unlimited, being able to have 1 row up to, for example, 1000 rows, whatever...
I could put 5 as the limit value for each Pool, but when one of them happens to have only 2 rows and the other 8 rows, the one with 8 rows would be harmed because it could be using more cpu.
The example below is just to visually demonstrate what I want to do, it is totally unfeasible for multiple factors.
In a bizarre and erroneous way, I could try saving the value that will be used in a CSV file, then the other one before starting the multiprocessing would take that value and at the end of the multiprocessing it would save it as 0:
def stackoverflow(stack):
    df = create_dataframe(stack)
    if len(df) == 0:
        pass
    else:
        another_mp = int(list(csv.reader(open(r'C:\Users\Computer\Desktop\multiprocessing_B.csv')))[0][0])

        free_to_use = 10-another_mp

        with open(r'C:\Users\Computer\Desktop\multiprocessing_A.csv', 'w+', newline='', encoding='UTF-8') as f:
            f.write(free_to_use)

        try:
            max_process = free_to_use
            pool = multiprocessing.Pool(max_process)
            list_pool = pool.map(data_event, zip(repeat(stack), df.iterrows()))
        finally:
            pool.close()
            pool.join()
            with open(r'C:\Users\Computer\Desktop\multiprocessing_A.csv', 'w+', newline='', encoding='UTF-8') as f:
                f.write(0)

And I would do it in the other one too, just inverting the substring A and B in the name of the files that are opened.
Is there a correct way to do this?


text:
Q: Write $Z = 3 + 6i$ in the form $\rho e ^{i \theta}$ How do I write $Z = 3 + 6i$ in the form $\rho e ^{i \theta}$?
Note: $$e^{i\theta} = \cos(\theta) + i\sin(\theta)$$

A: $\rho=\sqrt{3^2+6^2}=\sqrt{45}=3\sqrt 5$ and $\theta=\arctan\frac{6}{3}=\arctan2$. So we have $Z=3\sqrt 5e^{i\arctan(2)+2k\pi i}$ with $k\in\mathbb{Z}$.

A: Note that:
$$3 = ρ\cos(t), 6 = ρ\sin(t)$$
Dividing one by the other gives:
$$\tan(t) = 2 \rightarrow t = \arctan(2)$$
Square them both and add them together (equivalent to finding the magnitude)
$$ρ(\sin^2(t) + cos^2(t)) = ρ = \sqrt{3^2 + 6^2} = 3\sqrt{5}$$


text:
Q: Exception while using AS in C# While writing
var e = element.NextSibling as HtmlElement;

I get an invalid cast exception. I thought as prevents cast exception and returns null? because thats what i wanted/excepted. Either tell me how do i get e to be null instead of an exception? or why i got this exception when using the as keyword?
-edit- Correct it was element.NextSibling throwing the exception. How strange that its throwing a cast exception when i havent tried to cast it yet. I am not sure how to check if a next sibling exist. The error in NextSibling is below
    Message "Unable to cast COM object of type 'System.__ComObject' to interface type 'IHTMLElement'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{3050F1FF-98B5-11CF-BB82-00AA00BDCE0B}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))."  string

A: Are you sure it's this particular statement that is causing the exception to be thrown?
If you've wrapped it in a try/catch block to determine that it is, try picking it apart:
var next = element.NextSibling;
var e = next as HtmlElement;

Perhaps the exception is thrown from within .NextSibling?
In any case, it is not possible to override the as operator in C#, so it should always do what you expect it to do, and not throw that exception. I suspect the problem is elsewhere, but looks like it comes from this location.
Edit: As suggested by @Jon Skeet in his deleted answer, I would also suggest you try to replicate the problem in a short, but complete, program, and post the program here in your question so that we can try to reproduce the problem ourselves. Also, trying to reproduce the problem in a shorter piece of code might give you valuable insight into the specific scenario you're experiencing in your main project.
Judging by the code, it looks like you're parsing HTML code. If element is a HtmlElement object, then the .NextSibling method itself does not contain a cast that would produce that problem, but it does call another .NextSibling method through an interface reference, which means that Reflector alone won't tell me which object is involved here.
Edit in response to updated question: Unfortunately, I cannot help you with that part of the problem.
It appears that the call to .NextSibling internally retrieves a COM object, which it believes should implement the IHTMLElement interface, but in fact it does not. This internal code, however, is using a hard cast, which thus fails with that exception.
I don't think you have any other choice than to wrap at the very least the call to .NextSibling in a try/catch block to avoid this, unless you can find some patently wrong with the HTML code it is attempting to parse that you could correct instead.
Best of luck.


text:
Q: function "this" set some type context + original "this" context How do I merge given context of "this" with original "this" context I have in a function. Example:
interface Repository {
    find(): void
    findOne(): void
}

interface CustomRepository {
    [key: string]: (this: Repository & this) => any // note: I tried to add & this but it doesn't work.
}

const repository: CustomRepository = {
    findNew() {
        this.findOne()
    },
    findOld() {
        // here I would like to access find(), findOne(), findNew() using this.
        // this.
    }
}

If there is issue / feature request / discussion in TypeScript repository, link is appreciated.


text:
Q: How to call an Apex WebService from an External System I'm trying to build a webservice that will expose the ability to input data from an external system into salesforce.
I've found multiple resources on making a webservice.
I can't however find how to structure the actual http POST to Salesforce from another system.

A: Depends on a few things...what platform is the source system using? Are you authenticating? If so, what method?
EDIT
You can post to SF anonymously by exposing an APEX class on the profile of the public site user that gets created for each site. As such, you don't need an additional licence to capture the request, BUT that is now a publicly accessible endpoint, so anyone can post there and potentially mess with your data unless you add some form of security check. Also, a public site user has certain restrictions e.g. can't update standard objects, can't write to chatter etc.
If you use some form of authentication e.g. oauth, it will require you to set up the authentication flow, and require you to have a user that flow can login as. But that approach is more secure, and that user can then have as much access as the permissions allow.
For a simple example of how to post to a APEX rest service using CURL, you can look here:

curl -H "Authorization: Bearer sessionId" -H "Content-Type:
  application/json" -d @account.txt
  "https://instance.salesforce.com/services/apexrest/Account/"


text:
Q: ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10): I am using angular material spinner in my project but , It shows this

ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10):
  error TS2305: Module '"D:/ControlCenter/ofservices/node_modules/rxjs/internal-compatibility/index"'
  has no exported member 'ShareReplayConfig'.

I am getting this error :

ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10): error TS2305: Module
  '"D:/ControlCenter/ofservices/node_modules/rxjs/internal-compatibility/index"'
  has no exported member 'ShareReplayConfig'
  `

Can anyone help me???
spinner.service.ts file
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
export interface ISpinnerState {
  show: boolean
}

@Injectable()
export class SpinnerService {
  private _spinnerSubject = new Subject();

spinnerState = <Observable<ISpinnerState>>this._spinnerSubject.asObservable();
  show() {
    this._spinnerSubject.next(<ISpinnerState>{ show: true });
  }
  hide() {
    this._spinnerSubject.next(<ISpinnerState>{ show: false });
  }
}

spinner.component.ts
import {Component, OnDestroy, OnInit} from '@angular/core';
import { Subscription } from 'rxjs/Rx';
import {  ISpinnerState, SpinnerService } from './services/spinner.service';
@Component({
  selector: 'loading-spinner',
  template: `
  <div *ngIf="visible"
  class="spinner">
</div>
  `,
  styles: [`.spinner {position: absolute;left: 46%;top: 12%;background-color:black;width:50px;height:50px}`]
})

export class SpinnerComponent implements OnDestroy, OnInit {
  visible = false;

  private _spinnerStateChanged: Subscription;

  constructor(private _spinnerService: SpinnerService) { }

  ngOnInit() {
    this._spinnerStateChanged = this._spinnerService.spinnerState
      .subscribe((state: ISpinnerState) => this.visible = state.show);
  }
  ngOnDestroy() {
    this._spinnerStateChanged.unsubscribe();
  }
}

A: Try this version to  see if it work for you
"rxjs": "6.3.3",
"rxjs-compat": "6.3.3",


text:
Q: round-mode conditional on number size I would like to give numbers with three decimals places of precision, unless they are so small that this would round them down to zero.  In that case, I would like three significant figures instead.
Here is a minimal non-working example:
\documentclass{article}
\usepackage[round-mode=places,round-precision=3]{siunitx}
\begin{document}

\num{0.0437}  % gives 0.044

\num{0.00437} % gives 0.004

\num{0.000437}% I want this to give 0.000437

\end{document}

Right now I do it by overriding the settings from the preamble for any number that is small enough.  So I'd replace \num with \num[round-mode=figures].  But I'd like to do it automatically if I can.
I read the source of siunitx.sty but I still don't grok LaTeX3-style programming.  I'd appreciate any advice.

A: Here's a LuaLaTeX-based solution. It defines a utility macro called \mynum which, in turns, calls a Lua function to do the actual work.

% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{siunitx}
\sisetup{round-precision=3,group-digits=false,round-mode=places}

\usepackage{luacode} % for '\luaexec' macro
%% Lua-side code:
\luaexec{%
function mynum ( n )
  if n<0.001 then tex.sprint ( "\\num[round-mode=figures]{"..n.."}" )
             else tex.sprint ( "\\num{"..n.."}" )
  end
end
}
%% LaTeX-side code:
\newcommand\mynum[1]{\directlua{mynum(#1)}}

\begin{document}
\num{0.0437},   \mynum{0.0437}   % both give 0.044

\num{0.00437},  \mynum{0.00437}  % both give 0.004

\num{0.000437}, \mynum{0.000437} % only \mynum gives 0.000437
\end{document}

A: Using just expl3 functions, and assuming v3 of siunitx to allow us to do this using the code-level API, we might go for
\documentclass{article}
\usepackage{siunitx}
\sisetup{round-precision=3,group-digits=false}
\ExplSyntaxOn
\NewDocumentCommand \mynum { O { } m }
  {
    \mode_leave_vertical:
    \group_begin:
      \keys_set:nn { siunitx } {#1}
      \fp_compare:nNnTF {#2} < { 0.001 }
        { \keys_set:nn { siunitx } { round-mode = none } }
        { \keys_set:nn { siunitx } { round-mode = places } }
      \siunitx_number_format:nN {#2} \l___siunitx_number_tmp_tl
      \siunitx_print_number:V \l___siunitx_number_tmp_tl
    \group_end:
  }
\ExplSyntaxOff
\begin{document}
\num{0.0437},   \mynum{0.0437}   % both give 0.044

\num{0.00437},  \mynum{0.00437}  % both give 0.004

\num{0.000437}, \mynum{0.000437} % only \mynum gives 0.000437
\end{document}

using the demo from Mico's answer.
Note that the fp function here is limited to IEEE754 range/precision (e.g. 16 digits of mantissa), which may be an issue in some cases. (The core siunitx functions can handle arbitrary precision rounding.)


text:
Q: Grails accessing data where dates equal in database first mode I'm returning to Grails after a year hiatus while I worked for .Net shop. I had always programmed Grails in code first mode. My newest project is database first, and I thought I was ready. I have a simple calendar table in my MySql database:
commit;CREATE TABLE `Calendar` (
  `ID` bigint(20) NOT NULL,
  `Title` varchar(200) NOT NULL,
  `EventDate` date NOT NULL,
  `StartTime` time DEFAULT NULL,
  `EndTime` time DEFAULT NULL,
  `Location` varchar(500) NOT NULL,
  `version` int(11) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

With the following data in the table:
insert into Calendar (Title, EventDate, StartTime, EndTime, Location, version)
values ('Summer 2016 Garage Sale', '2016-07-23', '7:00 ', '19:00', 'Lodge', 0);

insert into Calendar (Title, EventDate, StartTime, EndTime, Location, version)
values ('August 2016 Member Meeting', '2016-08-03', '19:00', '20:00', 'Lodge', 0);

commit;

My calendar class in Grails looks like:
package plaquemineelks

import java.sql.Time
import grails.validation.Validateable

@Validateable
class Calendar {

    Long id
    Integer version

    String title
    Date eventDate
    Time startTime
    Time endTime
    String location

    static constraints = {
        title (blank: false)
        eventDate (blank: false)
        location (blank: false)
    }

    static mapping = {
        table "Calendar"
        id column: "ID"
        version column: "version"
        eventDate column: "EventDate"
        startTime column: "StartTime"
        endTime column: "EndTime"
        location column: "Location"
    }
}

My controller looks like:
package plaquemineelks

class CalendarController {

def index() { }

    def getByDate(String EventDate) {
        def Date newDate = Date.parse("mm/dd/yyyy", EventDate)
        def results = Calendar.findAllByEventDate(newDate)
        render(contentType: 'text/json') {[
            'results': results,
            'status': results ? "OK" : "Nothing present"
        ]}
    }
}

When I run the app and open the URI
http://localhost:8080/PlaquemineElks/Calendar/getByDate?EventDate=07/23/2016

My Json looks like:
{"results":[],"status":"Nothing present"}

I have tried a variety of formats, etc. for the date, keeping it groovy. I'm sure I'm missing something simple.
Thanks for any assistance.

A: You are inserting data to your table using sql query which means by default the StartDate contains date only and 00:00:00 for timestamp. Otherwise it will consider the timezone also if you insert into it using GORM.
First thing that you need to do is set the time zone to UTC for your application. In Bootstrap.grooy:
TimeZone.setDefault(TimeZone.getTimeZone('UTC'))

Secondly the format mm/dd/yyyy that you are using to parse the date is wrong, it should be: MM/dd/yyyy.
println Date.parse("mm/dd/yyyy", "07/23/2016")
Sat Jan 23 00:07:00 UTC 2016 //wrong

println Date.parse("MM/dd/yyyy", "07/23/2016")
Sat Jul 23 00:00:00 UTC 2016 //correct


text:
Q: What is the difference between mounting in fstab and by mounting in file manager ..and what are the consequences of the different methods?
I have been trying some things with the mounting of an sda2 partition.
Mounting in fstab, not mounting in fstab but from the file manager.
So far, if I am right, I learned that by mounting in fstab, a partition is mounted automatically at startup.
But this mounted partition is not shown under 'devices' in the file manager, whereas the root partition and cdrom for example are shown.
When you want to have it under devices in the sidebar, a partition should not be mounted in fstab but by clicking it in the file manager. Is that correct?
But which way to go if you want both? Automatically mounted at startup AND being shown in the sidebar of file manager?

A: This is documented (at least for gnome-shell/nautilus) in gvfs-udisks2-volume-monitor:
The gvfs-udisks2-volume-monitor process is responsible for the disks,
media, mounts and fstab entries shown in the desktop user interface.
..........................................
A device is either mounted (in which case its directory is known) or
it's not. If the device is not mounted, then its directory is known
only if it's referenced in the /etc/fstab file.

Further down comes the explanation:
If the directory for a device is known and outside /media, $HOME
(typically /home/foo) or /run/media/$USER then the device is not shown
in the user interface. Additionally, if any of component directories
in its directory starts with a dot ("."), the device is not shown
either. This policy may be overriden by use of the options x-gvfs-show
and x-gvfs-hide.

To sum up:
Partitions listed in /etc/fstab would (by default) only show up if they're mounted under /media, $HOME or /run/media/$USER. If you want a partition to be automatically mounted at system startup and also listed in the file manager sidebar, the easiest way is to mount it via /etc/fstab under one of those three locations.
If you want the partition to be mounted under a different directory (e.g. /mnt) and still be shown in the sidebar, you can override the default behaviour by adding x-gvfs-show to your mount options in fstab:
UUID=5a1615ca-cffd3124917a /mnt/storage ext4 rw,noatime,discard,x-gvfs-show 0 2

Partitions not listed in /etc/fstab are handled by udisks2 and will be mounted under /run/media/$USER/VolumeName or /media/VolumeName depending on the value of UDISKS_FILESYSTEM_SHARED1 hence they will be shown under Devices in the sidebar. However, they are not automatically mounted. A user could automatically mount them at session startup with udisksctl, e.g. adding:
udisksctl mount -b /dev/sdb2 -t ext4

to the session startup scripts.

1
man udisks:
UDISKS_FILESYSTEM_SHARED
   If set to 1, the filesystem on the device will be mounted in a shared directory e.g. /media/VolumeName)
   instead of a private directory (e.g. /run/media/$USER/VolumeName) when the Filesystem.Mount() method is handled.


text:
Q: подключение Qiwi интерфейса v1.1 для поставщика услуг Доброго времени, с недавнего времени Qiwi отключила свою платежку для интернет магазинов (тех кто успел подключиться не тронули все работает) отправил интерфейс на доработку, в замен предложив упрощенную систему документация интерфейса тут -> http://qiwi.kz/static/data/how-to-become-provider/interface_podkl_usl.pdf я в отправки таких вещей не силен, старую систему подключал но вот с новой пока не могу разобраться, прошу помощи по этому. Для начала решил протестировать отправку запроса на проверку оплаты - реализовывать решил на php (тут может я ошибаюсь и нужно по другому на jquery например поправьте если не прав) делаю так вроде все по документации:
$payparams = array(
'command' => 'check',
'txn_id'  => '1234567',
'account' => '4957835959',
'sum' => '200.00'
 );

$myCurl = curl_init();
curl_setopt_array($myCurl, array(
    CURLOPT_URL => 'https://service.someprv.ru:8443/payment_app.cgi',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query(array($payparams))
));
$response = curl_exec($myCurl);
curl_close($myCurl);

echo "Ответ: ".$response;

Но вот почему то ответ не приходит, так же для теста пробовал использовать их тестовый сервис -> http://www.qiwi.kz/ru/provider-test/ но тоже все одно - ошибка, так как видимо интерфейс запустили недавно в интернете кроме документации киви каких то примеров я не нашел, может кто уже делал такое? Подскажите пожалуйста!


text:
Q: How to form a string by replacing dict key with its values I have 2 items in dict, both has list of strings as values, I need to form and print strings by replacing all the substrings matching _key_ of the dict with its values (all possible combination).
e.g:
my_dict['season']=['spring','summer','fall']
my_dict['sport']=['baseball','soccer']

name='bobs-_season_-_sport_'

From above, I need to produce below output, by replacing pattern _season_ and _sport_ in name with all possible value combinations.
bobs-spring-baseball
bobs-spring-soccer
bobs-summer-baseball
bobs-summer-soccer
bobs-fall-baseball
bobs-fall-soccer

The below code works, but there should be a better way, also need to make this work when I have another item (3rd item) in my_dict. Thanks.
>>> my_dict=dict()
>>> my_dict['season']=['spring','summer','fall']
>>> my_dict['sport']=['baseball','soccer']
>>> name='bobs-_season_-_sport_'
>>>
>>> keys_list = list(my_dict.keys())
>>> if len(keys_list) == 2:
...     first_key = keys_list[0]
...     sec_key = keys_list[1]
...     for first_value in my_dict[first_key]:
...         name1 = name
...         if f'_{first_key}_' in name1:
...            name1 = name1.replace(f'_{first_key}_', first_value)
...         for sec_value in my_dict[sec_key]:
...            name2 = name1.replace(f'_{sec_key}_', sec_value)
...            print(name2)
...
bobs-spring-baseball
bobs-spring-soccer
bobs-summer-baseball
bobs-summer-soccer
bobs-fall-baseball
bobs-fall-soccer

A: You can use itertools.product to generate the different cases :
import itertools
my_dict = {}
my_dict['season']=['spring','summer','fall']
my_dict['sport']=['baseball','soccer']

name='bobs-_season_-_sport_'

for values in itertools.product(*my_dict.values()):
    new_name = name
    for key, value in zip(my_dict.keys(), values):
        new_name = new_name.replace(f'_{key}_', value)
    print(new_name)

Note that you need Python 3.6+ to ensure that dictionary insertion order is kept.

A: I suggest that you split the problem up into two parts. The first parses your input string (name) to figure out which keys it needs to use for replacements later. Then in a second step, you calculate all the combinations of values and do the substitutions.
I suggest using regular expressions for the parsing:
import re

keys = re.findall(r'_([^_]+)_', name)

Now make the combinations using itertools.product:
for values in itertools.product(*[my_dict[key] for key in keys]):
    output = name
    for key, value in zip(keys, values):
        output = output.replace("_{}_".format(key), value)
    print(output)

If you can choose the format you're using in name, a much nicer one (for your code) would be bob-{season}-{sport} because you can use it directly as a format string (rather than needing to repeatedly call str.replace). Using that style of input, you could replace the code above with:
keys = re.findall(r'\{([^}]+)\}', name)
for values in itertools.product(*[my_dict[key] for key in keys]):
    print(name.format(**dict(zip(keys, values))))

I see in a recent comment that your dictionary may not always have keys for all of the key strings in name. If that's the case, then you should use my_dict.get(key, ['_{}_'.format(key)]) instead of my_dict[key] in the list comprehension inside of the product call. This will replace _unknownkey_ with itself, since there's nothing else to use instead.

A: You can use re for finding the keys in the string, then create a suitable template string and use itertools.product for creating the value tuples:
from functools import reduce
import itertools as it
import re

keys = re.findall(r'_([a-z]+)_', name)
template = reduce(lambda s, k: s.replace(f'_{k}_', '{}'), keys, name)
result = list(template.format(*x) for x in it.product(*[my_dict[k] for k in keys]))

Or you can use it.starmap in place of the last line, if you find it clearer:
result = list(it.starmap(template.format, it.product(*[my_dict[k] for k in keys])))

A: Yes, you can do this using list comprehensions
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
my_dict=dict()
my_dict['season']=['spring','summer','fall']
my_dict['sport']=['baseball','soccer']
name='bobs-_season_-_sport_'

def generate_all_replaced(name, d):
    names = [name]
    for k in d.keys():
        names = [n.replace(f'_{k}_', v) for v in d[k] for n in names]
    return names

print(generate_all_replaced(name, my_dict))


text: Q: Scaladoc: Is it possible to insert a link into every page? Is it possible to insert a link to my home page into every Scaladoc page? Is there a way to add content, modify the layout, or even change the style of every page?


text:
Q: Syntax error (TypeError: 'DataFrame' object is not callable) Where I am going wrong in syntax?
vif_cal(input_data=dataset(['a','b','c'], axis=1),
dependent_col='d')

I'm getting this error:
TypeError: 'DataFrame' object is not callable

A: You are calling dataframe as a function which is not callable. Try using this way:
vif_cal(input_data=dataset[['a','b','c']], dependent_col='d')


text:
Q: When action takes place, how does swift updates screen? I am new to swift and just curious about how swift updates screen.
What I mean by this is that when we click button or activate some function, how does it load the result into screen?
For ex)
if I push the button which changed the background color, does swift reload entire screen output? Or does it just dynamically update the specific feature that changed by the preceding action?
Sorry for vague question...

A: Welcome to StackOverflow!
This is a very broad question. Your second intuition about how the screen is updated is correct, but the mechanism that updates only the part of the screen that needs to be updated isn't Swift itself -- it's the underlying libraries contained in iOS that handle these events and other lower-level events and concerns.
The highest level library on iOS is called Cocoa Touch. It is similar to Cocoa on Mac OS X, or any other high-level library on any other operating system. The critical point is that Cocoa Touch is the main API (Application Programming Interface) for iOS. It allows you to interact with the top-level system services. The Cocoa Touch API can be used by C, Objective-C, and Swift, so when you write Swift code that responds to a button press, your Swift code is being called by the Cocoa Touch APIs that expose the built-in system controls. Those controls are in turn drawn by another library called Core Graphics. There are many layers to the operating system onion, and they are all extremely interesting in their own right.
You may want to have a look at some broader perspectives on programming and how code is translated into the actions you see on a screen. Definitely get your hands dirty and have fun, but your initial question is fundamental to all modern GUI programming, and an introductory text on Operating Systems will be very helpful.
Note that it doesn't need to be a book about the iOS operating system. Even better, learn some basics about Unix, Linux, or any *nix-style OS because iOS is based on a variant of *nix systems, and you'll run into them all the time.


text:
Q: MySQL Query, Count issue THANKS EVERYONE - SOLVED!
I have the following code:
SELECT region, division, SUM(staff_count) AS Total_Staff,
(SELECT COUNT(region) FROM tresults_xyc WHERE division = 'Central' GROUP BY region) AS Total_Responses
FROM  `trespondent_xyc`
WHERE division = 'Central'
GROUP BY region

It brings back the following:
region  division    Total_Staff Total_Responses
1       Central     212         8
2       Central     168         8
3       Central     164         8
4       Central     180         8

The information contained in the colomns region, division, and Total_Staff are correct.
However, the Total_Responses colomn is not - that is showing the total number of responses for the Division and not each region.
Can anyone advise?
Thanks in advance,
Homer.

A: You have to do this :
SELECT region, division, SUM(staff_count) AS Total_Staff,
       (
           SELECT COUNT(*)
           FROM tresults_xyc t2
           WHERE t2.region = t1.region
       ) AS Total_Responses
FROM  `trespondent_xyc` t1
WHERE division = 'Central'
GROUP BY region

A: try
SELECT region, division, SUM(staff_count) AS Total_Staff, (SELECT COUNT(region) FROM tresults_xyc WHERE division = 'Central' and region = xx.region GROUP BY region) AS Total_Responses
FROM  `trespondent_xyc` xx
WHERE division = 'Central'
GROUP BY region


text:
Q: Why is `boost::container::flat_set` not `nothrow_move_constructible`? I was writing some code that has a generic container that requires elements to be nothrow_move_constructible.
I decided to add a static_assert that enforces this, just in case.
To my surprise I can't compile now when using boost::container::flat_set.
I assumed that this was just an oversight and I need a more recent boost verison, but it seems that actually they deliberately made it not safely movable:
See docs here:
http://www.boost.org/doc/libs/1_61_0/doc/html/boost/container/flat_set.html
You can see that they did update it to use R-value references and marked swap as noexcept, but they chose not to make the move ctor noexcept.
It appears that move assignment is conditionally noexcept. The condition appears to depend on the value type and on the allocator in some way.
What could be the rationale for not being nothrow move constructible? Is it just an oversight?

A: If the objects within a container are not nothrow_move_constructible then it is very dangerous to take an entire set of one container and relocate it to another under certain conditions (usually involving Allocators).  If two containers were not constructed with the same allocator, then it is no longer safe to move memory from one container to another (think two containers from two different memory arenas).
Digging in to the current source, both the contract and the implementation are problematic:
//! <b>Effects</b>: Move constructs a flat_map.
//!   Constructs *this using x's resources.
flat_map(BOOST_RV_REF(flat_map) x)
    : m_flat_tree(boost::move(x.m_flat_tree))
{ ... }

So your current expectation that it could currently by nothrow is correct.  But what they are doing is probably not right.
I can only guess that they are worried that they will have to do revisit this in the future and don't want to have to weaken the nothrow contract later.


text:
Q: Javascript function and Array I am trying to cut some values from an array, for example i want to cut 1 from it's position and return array as (3,5,4,6,2,7), but there is an error saying splice is not a function.
function findMin() {
   var arr = arguments;
   arr.splice(1,1);
   return arr[0];
 }
 document.getElementById("demo").innerHTML = findMin(1,3,5,4,6,2,7);

A: arguments isn't an array, it's array-like. You can get a copy of its contents as an array like this:
var arr = Array.prototype.slice.call(arguments, 0);

...and then you can use array operations on it.
Two other issues with the code:

*

*Indexes you use with splice start at 0, not 1

*You're returning the (new) first entry, not the array
But note that for your specific task, you don't need to go through all those operations, you can just use slice directly; Denys Séguret shows you that.
Here's an example just using slice to copy arguments, without combining it with the other code, with the other issues above fixed as well:

function findMin() {
  var arr = Array.prototype.slice.call(arguments, 0);
  arr.splice(0, 1);
  return arr;
}
document.getElementById("demo").innerHTML = findMin(1, 3, 5, 4, 6, 2, 7);

A: The problem is arguments isn't an array, but an array-like object.
The usual solution is to use slice to get an array from an array-like object. And as the normal purpose of slice is to get a slice from an array, here's a solution giving you a copy of arguments without the first element:
function findMin() {
   return Array.prototype.slice.call(arguments, 1);
}

Notes

*

*Manipulating arguments, even using slice has a performance impact on the whole function in which you do it. Avoid it when you can.

*Thanks to ES6 (the next iteration of the standard behind JavaScript), we'll be able to use Array.from instead of slice  in the near future.


text:
Q: Get assigned platforms to Azure B2C application Is it any other way to get assigned platforms to application in AADB2C except following?
https://graph.microsoft.com/v1.0/myorganization/applications?$filter=appId eq 'guid id'
If I add multiple platforms like IOS/Desktop/Android all redirects uris for them land in the same b2c applications property publicClient: redirectUris[] I need to know which uri is for which platform type and I do not want to achieve this by guessing based on specific redirect uri structure.

A: You can either write your own logic to determine which redirect Uri belongs to which app. Or another cleaner alternative is to have multiple apps, one per platform. There is no additional cost to having a separate app per platform each with a single redirect Uri. And that may give you additional flexibility to support different auth flows or configuration in case of library updates or changes.