text:
Q: Delphi Embarcadero XE: tons of warnings with String and PAnsiChar I'm trying to migrate from Delphi 2007 to Embarcadero RAD Studio XE.
I'm getting tons of warnings.
They all look like this: I have a procedure where I declare a "String":
procedure SendMail( ADestinataire,ASubject : String);

And I'm trying to call Windows API like:
  Res := MAPIResolveName(Session, Application.Handle,
    PAnsiChar(ADestinataire), MAPI_LOGON_UI, 0, PRecip);

So the warnings are:

W1044: Transtyping string into PAnsiChar suspect.

What am I doing wrong / how should I correct this (350 warnings...)?
Thank you very much

A: MAPIResolveName uses LPSTR parameter, which is PAnsiChar in Delphi. Simple MAPI does not support UTF16 strings (though it can be used with UTF8 strings), so if you adhere to simple MAPI you should use AnsiStrings, for example
procedure SendMail( ADestinataire,ASubject : AnsiString);

or better you can use
procedure SendMail( ADestinataire,ASubject : String);

and explicitly convert string parameters to AnsiStrings prior to calling MAPIResolveName

Update
The whole Simple MAPI is now deprecated; Simple MAPI can be used with UTF8 strings, but it requires some changes in code and registry.
So if the question is about quick porting old ANSI Simple MAPI to Unicode Delphi, the best is to adhere to AnsiStrings.
A more solid approach is to abandon Simple MAPI completely and use Extended MAPI instead.

A: Just write
Res := MAPIResolveName(Session, Application.Handle,
  PChar(ADestinataire), MAPI_LOGON_UI, 0, PRecip);

If you have a string, that is, a Unicode string, that is, a pointer to a sequence of Unicode characters, you shouldn't cast it to PAnsiChar. PAnsiChar is a pointer to a sequence of non-Unicode characters. Indeed, a cast to a PSomethingChar type simply tells the compiler to interpret the thing inside the cast as a pointer of the specified type. It doesn't do any conversion. So, basically, right now you lie to the compiler: You have a Unicode string and instructs the compiler to interpret it as an ANSI (non-Unicode) string. That's bad.
Instead, you should cast it to PWideChar, a pointer to a sequence of Unicode characters. In Delphi 2009+, PChar is equivalent to PWideChar.
Of course, if you send a pointer to a sequence of Unicode characters to the function, then the function had better expect Unicode characters, but I am not sure if this is the case of the MAPIResolveName function. I suspect that it actually requires ANSI (that is, non-Unicode) characters. If this is the case, you need to convert the Unicode string to an ANSI (non-Unicode) string. This is easy, just write AnsiString(ADestinataire). Then you cast to a ANSI (non-Unicode) PAnsiChar:
Res := MAPIResolveName(Session, Application.Handle,
  PANsiChar(AnsiString(ADestinataire)), MAPI_LOGON_UI, 0, PRecip);

A: Starting with Delphi 2009, the string data type is now implemented as a Unicode string. Previous versions implemented the string data type as an Ansi string (i.e. one byte per character).
This had significant implications when we ported our apps from 2007 to XE, and these article were very helpful:
Delphi in a Unicode World (first of three parts)
Delphi and Unicode
Delphi Unicode Migration for Mere Mortals

A: To step back a moment:
When using    use the cast
============  ================
String        PChar
AnsiString    PAnsiChar
WideString    PWideChar

String used to be an alias for AnsiString, which means it happened to work if you used PAnsiChar (even though you should have used PChar).
Now string is an alias for UnicodeString, which means using PAnsiChar (which was always wrong) is now really wrong.
Knowing this you can solve the question:
ADestinataire: String
PAnsiChar(ADestinataire)


text:
Q: Shrink and move /home partition onto another HDD On arch linux with gpt uefi, installed /home partition on a separate HDD, how can I shrink it and move it back?

A: 1) Copy your home directory to your local drive.
2) Set your home directory to the local path
sudo usermod --home /path/to/dir

see man usermod
3) As suggested here, use GParted to resize your external drive.

I don't have a lot of experience with this, so I just used google. Please consider doing so as well - it is more polite.
https://superuser.com/help/how-to-ask

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delete user input from MySQL I'm takin input from user and trying to delete that data MySQL but my code doesn't work. I can't find error on my code. Appriciate aditional pair of eyes.
import mysql.connector

    Accno = int(input("Enter account number which you delete"))

    mydb = mysql.connector.connect(host="localhost", user="root", passwd="root",database="abc")
    mycursor = mydb.cursor()

    sql = "Delete from addacc1 where accno = %s"
    val = (Accno)
    mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record Deleted.")

After executing script I'm getting this error.
Traceback (most recent call last):
  File "C:/Users/K/PycharmProjects/Pratice/DELETE record in db.py", line 13, in <module>
    mycursor.execute(sql, val)
  File "C:\Users\K\PycharmProjects\Pratice\venv\lib\site-packages\mysql\connector\cursor.py", line 551, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "C:\Users\K\PycharmProjects\Pratice\venv\lib\site-packages\mysql\connector\connection.py", line 490, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "C:\Users\K\PycharmProjects\Pratice\venv\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1

A: You need to change
val = (Accno)

into
val = (Accno,)

for the reference from the official docs:

a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective


text:
Q: jetty on android is crashing hey I am developing an android application and I came to a problem, I want to develop a web http server for my android application and through my research I came across this example
Integrate Jetty Server In Your Application
and whenever I tried to run it I get this type of error that I don't know how to solve it, has any one came across this error or similar? I'm using eclipse and trying to run it on android 4.2.2 and also on 4.1.2
05-23 12:53:18.351: D/dalvikvm(626): Not late-enabling CheckJNI (already on)
05-23 12:53:19.112: E/Trace(626): error opening trace file: No such file or directory (2)
05-23 12:53:19.461: W/dalvikvm(626): Unable to resolve superclass of Lcom/example/jettytest/MainActivity$1; (641)
05-23 12:53:19.461: W/dalvikvm(626): Link of class 'Lcom/example/jettytest/MainActivity$1;' failed
05-23 12:53:19.461: E/dalvikvm(626): Could not find class 'com.example.jettytest.MainActivity$1', referenced from method com.example.jettytest.MainActivity.<init>
05-23 12:53:19.461: W/dalvikvm(626): VFY: unable to resolve new-instance 536 (Lcom/example/jettytest/MainActivity$1;) in Lcom/example/jettytest/MainActivity;
05-23 12:53:19.461: D/dalvikvm(626): VFY: replacing opcode 0x22 at 0x0003
05-23 12:53:19.471: E/dalvikvm(626): Could not find class 'org.eclipse.jetty.server.Server', referenced from method com.example.jettytest.MainActivity.onCreate
05-23 12:53:19.471: W/dalvikvm(626): VFY: unable to resolve new-instance 640 (Lorg/eclipse/jetty/server/Server;) in Lcom/example/jettytest/MainActivity;
05-23 12:53:19.471: D/dalvikvm(626): VFY: replacing opcode 0x22 at 0x0008
05-23 12:53:19.471: W/dalvikvm(626): Unable to resolve superclass of Lcom/example/jettytest/MainActivity$1; (641)
05-23 12:53:19.471: W/dalvikvm(626): Link of class 'Lcom/example/jettytest/MainActivity$1;' failed
05-23 12:53:19.471: D/dalvikvm(626): DexOpt: unable to opt direct call 0x0ff3 at 0x05 in Lcom/example/jettytest/MainActivity;.<init>
05-23 12:53:19.471: D/dalvikvm(626): DexOpt: unable to opt direct call 0x10bf at 0x0c in Lcom/example/jettytest/MainActivity;.onCreate
05-23 12:53:19.481: D/AndroidRuntime(626): Shutting down VM
05-23 12:53:19.481: W/dalvikvm(626): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
05-23 12:53:19.491: E/AndroidRuntime(626): FATAL EXCEPTION: main
05-23 12:53:19.491: E/AndroidRuntime(626): java.lang.NoClassDefFoundError: com.example.jettytest.MainActivity$1
05-23 12:53:19.491: E/AndroidRuntime(626):  at com.example.jettytest.MainActivity.<init>(MainActivity.java:26)
05-23 12:53:19.491: E/AndroidRuntime(626):  at java.lang.Class.newInstanceImpl(Native Method)
05-23 12:53:19.491: E/AndroidRuntime(626):  at java.lang.Class.newInstance(Class.java:1319)
05-23 12:53:19.491: E/AndroidRuntime(626):  at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
05-23 12:53:19.491: E/AndroidRuntime(626):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
05-23 12:53:19.491: E/AndroidRuntime(626):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
05-23 12:53:19.491: E/AndroidRuntime(626):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
05-23 12:53:19.491: E/AndroidRuntime(626):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
05-23 12:53:19.491: E/AndroidRuntime(626):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 12:53:19.491: E/AndroidRuntime(626):  at android.os.Looper.loop(Looper.java:137)
05-23 12:53:19.491: E/AndroidRuntime(626):  at android.app.ActivityThread.main(ActivityThread.java:4745)
05-23 12:53:19.491: E/AndroidRuntime(626):  at java.lang.reflect.Method.invokeNative(Native Method)
05-23 12:53:19.491: E/AndroidRuntime(626):  at java.lang.reflect.Method.invoke(Method.java:511)
05-23 12:53:19.491: E/AndroidRuntime(626):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
05-23 12:53:19.491: E/AndroidRuntime(626):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-23 12:53:19.491: E/AndroidRuntime(626):  at dalvik.system.NativeStart.main(Native Method)
05-23 12:53:21.291: I/Process(626): Sending signal. PID: 626 SIG: 9

A: For starters, use Jetty 7, as it is compatible with the JDK that Android uses.
(Jetty 8 uses advanced features of JDK 6 not present in Android, and Jetty 9 has a minimum requirement of JDK 7 which is too new for Android)
The error you got Could not find class 'org.eclipse.jetty.server.Server' is typically a sign that you tried to use Jetty 8/9 with Android (or more rarely, you had a packaging mistake)
You also have to replace the standard JVM classloader that Jetty uses with one that is Android compatible.
An open source example of Jetty 7 on Android can be found at the i-jetty project at code.google.com/p/i-jetty/.  The i-jetty project is maintained by the Jetty developers.


text:
Q: troubleshooting OpenVPN not connecting to the server I've installed OpenVPN GUI for Windows, created and put config file to the appropriate folder. When I'm pressing "Connect", it shows a progress window (without any messages) and after a few seconds - "can't connect to the server" error. I'm trying to find a log file, but there isn't any.
Any ideas what can I do to troubleshoot this?

A: It's necessary to run the program as Admin, but the app's shortcut doesn't enforce that.


text:
Q: Is there anything deep about Fuzzy sets/Fuzzy logic? I keep coming across the term "fuzzy". I browsed around a bit and read a few articles.. It seems to me that there's absolutely nothing deep or foundational about fuzzy set theory or fuzzy logic. I know they are practically useful in robotics, ..etc. but since there's a lot of buzz around them, I am led to think that there might be something deep that I just don't see.
I realize that my question is perhaps vague or "not constructive", I would understand if it were closed for that reason.

A: I know quite a lot of mathematicians who claim that there is nothing deep about "formal logic" (in the sense of mathematical logic): they believe it is just a waste of time to spend so much time in formalizing a problem. What these people do not realize is that the interesting part of logic is not the process of formalization, what it is really interesting is the metamathematical reasoning we can do once a problem is formalized. Particular examples of useful results concerning metamathematics are: compactness theorem, Löwenheim-Skolem theorems, completeness theorem, incompleteness theorems, etc.
My interpretation about your question is that you share the same prejudices I have explained above, but towards fuzzy logic insted of logic. So, let me try to point out that what is interesting about fuzzy logic for me, at least, is not the process of formalizing using fuzzy sets (I agree that this is not worth spending time), it is the metamathematics that can be developed around this alternative semantics. To emphasize this distinction some people has coined the term "mathematical fuzzy logic" (you can find much more details in the link Mathematical Fuzzy Logic and the references there in).
Let me just summarize some statements about fuzzy logic in this metamathematical sense:

*

*First-order logic using an infinite-valued Lukasiewicz semantics (this is a natural choice of connectives) is not recursively axiomatizable, indeed it is $\Pi_2^0$-complete. The first part was proved by Bruno Scarpellini, and the second by Mathias Ragaz. Other choices of interpreting connectives give different situations (e.g., using what is called "product logic" you get a non-arithmetical set of validities, etc.).

*The comprehension axiom is consistent in case you restrict your logical rules from classical logic to Lukasiewicz fuzzy logic. Thus, an alternative approach to restricting comprehension axiom (this is method used in ZFC) consists on restricting the logical rules. To explore a bit more on this topic look at https://mathoverflow.net/questions/86151/boolean-valued-models-vs-the-infinite-valued-logic-of-lukasiewicz-and-set-theory

*Finally, let me point out that while it is known that Peano arithmetic cannot be consistenly expanded with a truth predicate, this is not so clear in case you allow the truth predicate to be fuzzy. Unfortunately, the situation is the same than in classical logic, but the proof is more tricky than the one given for classical logics. You can find the details of this in the paper http://www.jstor.org/stable/2586541 published at Journal of Symbolic Logic (see also http://www.logicmatters.net/2010/05/curry-lukasiewicz-and-field ).

A: This is what yours truly answered on a related question on MathOverflow:

Fuzzy measure theory has applications in pure measure theory. The
  Choquet capacity theorem is a standard tool for showing the universal
  measurability of analytic sets. The   theory of capacities (or
  fuzzy measures) is fairly well developed and strongly related to
  "normal" analysis.
The theory of capacities was not created in the context of fuzzy
  mathematics, but M. Sugeno developed a form of fuzzy integration in
  his PhD thesis that shares many formal similarities with the Choquet
  integral and some work on the Sugeno integral carried over to the
  Choquet integral.
A rather extensive introduction to these topics is given in the book
  Generalized Measure Theory by Wang and Klir.

A: I'm not sure what you mean by "deep".  However, I believe you will think it reasonable to postulate that if something leads to the creation or expansion of new mathematics, then it seems reasonable to think of it as deep in some sense.  Well, fuzzy set theory can get said to have lead to the creation of new branches of group theory (and other branches of abstract algebra), topology, differential calculus, arithmetic, geometry, trigonometry, graph theory, etc., see here and here for potential sources.  On top of this, there exists possibility theory, and generalized measure theory where fuzzy sets usually come up at some point one way or another.  This, of course, is not an argument that you should like fuzzy set theory, nor an argument that you should dislike fuzzy set theory, just as if you read enough philosophers you'll almost surely find someone extremely deep who you intensely dislike.

A: When I think of "Fuzzy logic" the first thing that comes to mind is engineering, where is it used in control systems, and information processing. For example, "fuzzy logic" is used in control systems for washing machines. I think it was a hot topic in 1980s and 1990s, and one article from that time is "Designing with Fuzzy Logic" by Kevin Self from the IEEE Spectrum magazine in 1990.
My opinion as a logician is that "fuzzy logic" per se has not developed significant interest in mathematical logic for the study of foundations of mathematics. I have not seen any examples of "deep" applications of fuzzy logic to classical foundational issues. One reason why it will be difficult to develop deep foundational implications of fuzzy logic is that much work in foundations is motivated by a few standard structures (ignoring any philosophical objections): the natural numbers, the real numbers, the cumulative hierarchy of sets. These are not ordinarily conceived as "fuzzy" structures.
As a personal aside, I would not use the term "fuzzy logic" to refer to multivalued logic in general, and I think it is somewhat ahistorical to refer to work of Łukasiewicz as "fuzzy logic". However, others do use "fuzzy logic" more broadly, and there is a book by Hájek entitled "Metamathematics of Fuzzy Logic", so my opinion is far from universal.
None of this means there is a lack of value in fuzzy logic, of course. It is obviously of great interest for information processing, control theory, and engineering, where it may indeed have deep aspects.
The introduction to the Stanford Encyclopedia of Philosophy article on fuzzy logic also remarks on some of these issues.  In that terminology, I am apparently speaking about "fuzzy logic in the broad sense".


text:
Q: Error when starting jHipster application on heroku i'm using jhipster 4.5.6. I'm trying to run my application on heroku and i'm getting this error when executing this code on in main class:
Environment env = app.run(args).getEnvironment();
2017-06-24 17:35:32.293 ERROR 4 --- [           main] o.s.boot.SpringApplication               : Application startup failed
2017-06-24T17:35:32.294416+00:00 app[web.1]:
2017-06-24T17:35:32.294418+00:00 app[web.1]: org.springframework.beans.FatalBeanException: Could not copy property 'password' from source to target; nested exception is java.lang.reflect.InvocationTargetException

A: You generated a monolith app with service discovery enabled, this is why your app expects JHipster registry URL to be configured. You should edit your .yo-rc.json file and set "serviceDiscoveryType": false and re-generate your app with yo jhipster --with-entities.


text:
Q: Is there a systematic way to compute the receptive field of a neuron? I am interested in computing the receptive field of a neuron relatively to the input, or more generally relatively to an earlier layer.
This can be done manually, but I would like to know if there is a built-in function to do it or otherwise if there is a way do compute it automatically.
Is there something that could work at least on a simple (single stream, no skip/concatenation) network restricted to convolutions and reduce layers, with possibly a mix of SAME and VALID paddings and non-unit strides?

A: Yes, as of Aug 2017, you can simply use tf.contrib.receptive_field
See https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/receptive_field for details.


text:
Q: NSTimer don't stop when I present another viewcontroller I have a viewController1 setting a timer.
When the timer countdown to 0, I'll present viewController2.
The timer also keeps going, although I call the timer function invalidate
Then I mark present viewcontroller code, it seems stop correctly.
//ViewController2 *vc = [[ViewController2 alloc] init];
//[self presentViewController:vc animated:false completion:nil];

What's wrong with code?
#import "ViewController.h"
#import <WebKit/WebKit.h>
#import "ViewController2.h"

@interface ViewController ()<WKScriptMessageHandler, WKNavigationDelegate,WKUIDelegate>

    @property (nonatomic,strong) WKWebView* webView;
    @property (nonatomic, strong) WKWebViewConfiguration * webConfig;
    @property (nonatomic, strong) NSTimer *timer;
    @property (nonatomic) int count;

    @end

    @implementation ViewController

    - (void)viewDidLoad {
        [super viewDidLoad];

        self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:[self createWKWebApp]];
        [self.view addSubview: self.webView];
        [self.webView.configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
        self.webView.scrollView.bounces = NO;
        [self.webView setContentMode:UIViewContentModeScaleAspectFit];
        self.webView.navigationDelegate = self;
        self.webView.UIDelegate = self;

        NSURL *url = [NSURL URLWithString:@"https://www.google.com.tw"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [self.webView loadRequest:request];

        self.count = 5;

        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
    }

    -(void)timerFired {

        NSLog(@"===) self.count : %d", self.count);

            if (self.count == 0) {

                ViewController2 *vc = [[ViewController2 alloc] init];
                [self presentViewController:vc animated:false completion:^{
                    [self.timer invalidate];
                    self.timer = nil;
                }];

            } else {
                self.count -= 1;
            }

    }

    - (WKWebViewConfiguration *)createWKWebApp {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        WKUserContentController *userContent = [[WKUserContentController alloc] init];

        config.userContentController = userContent;

        return config;
    }

    - (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message {

    }

    @end

A: Before present a ViewController, stop the timer
[self.timer invalidate];
 self.timer = nil;
ViewController2 *vc = [[ViewController2 alloc] init];
[self presentViewController:vc animated:false completion:nil];

A: Invalidate the timer in viewWillDisappear delegate method and tigger again whenever view will appear again.


text:
Q: Override settings of jQuery plugin? I've built a plugin  like this :
;(function ($,window,undefined){

  ...
  ...default settings area...
  ...content area...
  ...

})(jQuery,window);

But this plugin can have many(!) configurations .(files configurations)
So each configuration file can be in a js file . example :
mySettings.js :
var mySetings= {a:1,b:2.....}
So where is the problem :

*

*the settings file must be loaded before the plugin. ( so the plugin will be able to read mySettings  in the override settings area)

*the only way to communicate  mySettings with the plugin itself is via the window object
Question :
What is the correct way to configure a plugin which can have many(!) settings via js file.

A: As I don't have a code example to work with I'll give you some generalized solutions.

*

*Collect the settings object(s) in an array and iterate over them within your override settings area.

*Expose your plugin via window and directly append the settings there.

Example 1
JS
//File 1.js
window.settings = window.settings || [];
window.settings.push({a:'11'});

//File2.js
window.settings = window.settings || [];
window.settings.push({b:'22', c:'33'});

//File3.js
window.settings = window.settings || [];
window.settings.push({b:'222'});

//Main.js File
;(function ($,window,undefined){

    var plugin = function(settings){
        var defConfig = {
            a: '1',
            b: '2',
            c: '3'
        };

        var len = settings.length, i;

        if(len){
            for(i = 0; i < len; i++){
               defConfig = $.extend(defConfig, settings[i]);
            }
        }else{
            defConfig = $.extend(defConfig, settings);
        }

        alert(JSON.stringify(defConfig));
    };

    var instance = new plugin(window.settings || []);

})(jQuery,window);

Example 2
//Main.js File
;(function ($,window,undefined){

    var plugin = function(){
        var defConfig = {
            a: '1',
            b: '2',
            c: '3'
        };

        this.overrideSettings = function(settings){
            var len = settings.length, i;

            if(len){
                for(i = 0; i < len; i++){
                   defConfig = $.extend(defConfig, settings[i]);
                }
            }else{
                defConfig = $.extend(defConfig, settings);
            }

            alert(JSON.stringify(defConfig));
        }
    };

    window.instance = new plugin();

})(jQuery,window);

//File 1.js
window.instance.overrideSettings({d:'93'});

//File2.js
window.instance.overrideSettings({b:'22222'});


text:
Q: How to create a JayData model entity with a Knockout ko.computed property? Using this simple example model:
function Person(){
    var self = this;
    self.firstName = ko.observable();
    self.lastName = ko.observable();
    self.fullName = ko.computed(function(){
        return self.firstName() + ' ' + self.lastName();
    });
}

How would you implement FullName with JayData?
$data.Entity.extend("Person", {
    FirstName: { type: String },
    LastName: { type: String },
    FullName: ???
});

A: Sorry, it is not supported. Workaround can be made.


text:
Q: Remove svn:externals property from a folder I have a branch of the trunk. I need to re-set the properties of the externals in the branch to a different point.
My idea was to remove them all and re-set them with propset.
When I type svn propdel svn:externals http://path-to-branch/externals
I get

svn: E200009: Targets must be working copy paths

Whats the problem with my command?

A: Your command is operating on the repository URL, not a working copy.  Check out a working copy first:
svn co http://path-to-branch path/to/workingcopy

Then modify the property in your working copy:
svn propdel svn:externals path/to/workingcopy

Commit the change, and you should be all set.  I would be remiss not to point out that it is not actually necessary to delete them first, propedit will overwrite whatever the property was beforehand.


text:
Q: decode from unicode hex to string When I load my data from my model (asp.net model) if the string is in another language (Russian for example), I'm getting the unicode hex code of the chars. How can I convert them to a normal string?
The problem isn't from the javascript encoding, it's from loading it from the model. I tried using a lot of functions from the forum but none worked!
Here is an example of a value I should get:
Петър

And here is what I'm actually getting:
Петър

A:

const sequence = 'Петър'
const charCode = sequence.split(/[;\s]+/g)
  // remove empty
  .filter((v) => v)
  // &#x41F -> 0x41F -> number
  .map((v) => Number.parseInt(v.replace(/&#/, '0')))

console.log(
  String.fromCharCode(...charCode)
)


text:
Q: Enable CDbCache and CDbCacheDependency I am trying to optimise a query by applying cache on it. But even after running the query again and again their is no change and no YiiCache table is created in my database. I think my CDbCache is not configured properly or dependency is not working. Or suggest something else to optimise SQL queries in Yii.
This my configuration :
    'cache'=>array(
            'class'=>'system.caching.CDbCache',
        'connectionId'=>'db',
    ),

and i want to optimise this query:
    $dependency = new CDbCacheDependency('SELECT MAX(id) FROM         user_notification');

    $userNotificationModel = UserNotification::model()->cache(9000,            $dependency)->findAllByAttributes(
        array(
            'status' => NotificationCronCommand::QUEUED
        )
    );


text:
Q: How to escape a Hungry Node in Minecraft? How can I escape the grasp of a Hungry Node and survive?

A: Use an Open Blocks Hang Glider, when you get caught in a Hungry Node while using it, you'll get sucked in, but you won't be flung around like a ragdoll. Instead you'll just hang in the middle of the node. Eventually you'll get launched in the air, but since you still have your Hang Glider open, you'll be safe from the fall.
If you don't have Open Blocks installed, you can use Ender Pearls to teleport away, this is not very reliable though and can possibly get you killed instead.

A: how about putting your node in a jar, you don't have to escape from something that's not there:
Node In A Jar:
This Research allows you to bottle up Nodes, and move them to wherever you want to place them.
Warded jars have proven themselves capable of storing all manner of mundane and mystical things, and you believe you have discovered another use for them - trapping aura nodes.
By constructing a large version of a jar around a node and enacting the proper mystical formula with your wand, the node will become trapped inside the construct which will quickly shrink to a more manageable size. The jar can then be safely picked up and moved around, but the initial trapping spell does have a very good chance of damageing the node.
While trapped the node is kept suspended and will not regenerate vis, nor can vis be drawn from it.
It is possible to free the node from the jar by placing it in the world and clicking on it with a wand. The jar will be destroyed in the process.
To capture a Node, you must place a multi-layered construct directly around it, as shown in the picture on the right.

Layer 1 (upper layer): 9 Wooden Slabs.
Layer 2: 9 Glass.
Layer 3 (Node level: 8 Glass, surrounding the Node.
Layer 4: 9 Glass

Then click on the construct with your Wand. This consumes 70 of each Primal Aspect, so you cannot do this with a lesser Wand only.
Once this is done, the Node can be picked up, like you would a Warded Jar.
Required Research: Node Preserver
Node In A Jar

30px Auram
30px Lucrum
Motus
Permutatio

Notes:
Moving a Node has a good chance of lowering its quality: a Bright Node may devolve into a Normal one, or a Normal Node into a Fading one. Therefore, moving already Fading Nodes isn't advised.
Thaumcraft 4 needed.


text:
Q: HTML5 Canvas | Nuances with .moveTo() and .fillI() I'm trying to fill a face I drew in canvas (made of quadratic and bezier curves) with green. After the first bezier curve, I use a moveTo and have it direct to the endpoint of the curve (yes, a bit redundant) before creating the next curve (a quadratic curve). After I made the whole face, I used fill. The face fills some of the face with green, but leaves a white triangle in the middle. When I remove the redundant moveTo() I mentioned earlier, however the entire shape fills with green as intended. Can someone explain this?
My thoughts/attempts:

*

*Because the triangle's points are the same as the points between two intersecting curves, I first thought it was because the curves weren't touching, and went back and fixed that.

*moveTo() creates a 'new point' above the endpoint of the bezier Curve so it's really that new point and the next curve that are intersecting instead of the bezier curve and the next curve?
Consulted:
I looked at Mozilla Developer Network's Canvas Tutorial explanation of moveTo(), and searched here using keywords like 'moveTo()' '.fill()' 'adjacent curves' 'adjacent bezier curves.' I found this, but it wasn't exactly what I was looking for.
HTML code:
<!DOCTYPE html>

<title>FACE</title>

    <canvas id = 'canvas' height = '900' width = '900'></canvas>

Javascript Code Here
var canvas = document.getElementById('canvas');

var context = canvas.getContext('2d');

function greenHeadFront()
{
    var rightHeadx = 110.5;
    var rightHeady = 80;
    var leftHeadx = 40.5;
    var leftHeady = 80;

    context.moveTo(leftHeadx, leftHeady);
    context.bezierCurveTo(leftHeadx+6, leftHeady-40, rightHeadx-6, rightHeady-40, rightHeadx, rightHeady);        //TOP OF HEAD
    context.moveTo(rightHeadx, rightHeady);
    context.quadraticCurveTo( 115 , 100  ,  rightHeadx, rightHeady+30);//RIGHT CHEEK
    context.bezierCurveTo (100 , 114, 129, 152,   75, 131); //RIGHT CHIN
    context.moveTo(leftHeadx,leftHeady);
    context.quadraticCurveTo(35, 100, leftHeadx, leftHeady+30);//LEFT CHEEK
    context.bezierCurveTo(53, 120, 23, 148, 75, 131); //LEFT CHIN
    context.fillStyle = 'rgb(0,156,0)';
    context.fill();
    context.stroke();
}

greenHeadFront();

 Thank you in advance!!

A: Canvas paths are dependent on the direction the path is drawn (either clockwise or counter-clockwise). Here's a little info about how drawing the different ways affects areas that are filled.
Also a bit unrelated but I believe you are missing calls to the context.beginPath(); and context.closePath(); methods to signify the beginning and end of a shape. Hope this helps!

A: First thing : do not use hard-coded constant, this might be a source of troubles.
Another thing, do not hesitate to use context transforms to simplify your drawing code.
Lastly, your code will be much easier to (re)use if you are using simple to understand parameters : for instance you could provide the bounding box's top-left's x,y and width/height of the figure to draw.
So below i wrote untested code just to show you how could re-write your drawing code more clearly.
The idea is to translate to top-left corner of the figure, then scale the context so you can use only coordinates in between 0.0 and 1.0 to later do your draw.
Again, do not hesitate to name your constants in the function, and you might later elect some constant as function parameter.
function greenHeadFront(x, y, width, height )
{
    context.save();
    context.translate(x,y);
    context.scale(width, height);
    // !! required !!
    context.beginPath();
    // now all coordinates are beetween (0,0) (top-left)
    //     and (1.0,1.0) (bottom-right)
    var cheekHeight = 0.1 ;
    context.moveTo(0.5, 1 - cheekHeight); // move to center middle point.
    context.quadraticCurveTo( ??);//RIGHT CHEEK
    context.bezierCurveTo (??); //RIGHT CHIN
    context.bezierCurveTo(  ?? );  //TOP OF HEAD
    context.bezierCurveTo(??); //LEFT CHIN
    context.quadraticCurveTo(??);//LEFT CHEEK
    context.fillStyle = 'rgb(0,156,0)';
    context.fill();
    context.strokeStyle='#000';
    context.lineWidth=0.01;
    context.stroke();
    context.strokeRect(0,0,1,1);  // for debug
    context.restore();
}

greenHeadFront( ?? );

Now for your triangle issue, it's the expected behavior : each time you call moveTo, you are creating a new sub-path, so your figure is now built out of several sub-path that will all be filled when you call to fill(). And those sub-paths do not cover all the surface you'd like to be filled.


text:
Q: trying to send HTTP response from low level socket server This is my code:
# Process connections

print('Listening on port', port)
while True:
    c, addr = s.accept()
    print("Got connection from", addr)
    msg = ""

    response_headers = {
        'Content-Type': 'text/html; encoding=utf8',
        'Content-Length': len(msg.encode(encoding="utf-8")),
        'Connection': 'close',
    }

    response_headers_raw = ''.join('%s: %s\n' % (k, v) for k, v in response_headers.items())

    response_proto = 'HTTP/1.1'
    response_status = '200'
    response_status_text = 'OK' # this can be random

    # sending all this stuff
    r = '%s %s %s' % (response_proto, response_status, response_status_text)
    c.send(r.encode(encoding="utf-8"))
    c.send(response_headers_raw.encode(encoding="utf-8"))
    c.send('\n'.encode(encoding="utf-8")) # to separate headers from body
    c.send(msg.encode(encoding="utf-8"))

    c.close()

When I visit my local ip on the browser, I get an error page that says
ERR_CONNECTION_RESET

What am I doing wrong?
NOTE:
The full code snippet is here:
import socket

# Create socket object and set protocol
s = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM)

# Get name of local machine
host = socket.gethostname()
port = 80

# Bind
s.bind((host, port))

# Listen and set backlog (?)
s.listen(5)

# Process connections
print('Listening on port', port)
while True:
    c, addr = s.accept()
    print("Got connection from", addr)
    msg = ""

    response_headers = {
        'Content-Type': 'text/html; encoding=utf8',
        'Content-Length': len(msg.encode(encoding="utf-8")),
        'Connection': 'close',
    }

    response_headers_raw = ''.join('%s: %s\n' % (k, v) for k, v in response_headers.items())

    response_proto = 'HTTP/1.1'
    response_status = '200'
    response_status_text = 'OK' # this can be random

    # sending all this stuff
    r = '%s %s %s' % (response_proto, response_status, response_status_text)
    c.send(r.encode(encoding="utf-8"))
    c.send(response_headers_raw.encode(encoding="utf-8"))
    c.send('\n'.encode(encoding="utf-8")) # to separate headers from body
    c.send(msg.encode(encoding="utf-8"))

    c.close()

A: The problem is that HTTP headers need to be line separated by \r\n not just \n.  See RFC 1945 - HTTP/1.0 Sec 2.2 and RFC 7230 - HTTP/1.1 Syntax and Routing  Sec 3.
If you change this it will fix the problem.
import socket

# Create socket object and set protocol
s = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM)

# Get name of local machine
host = "127.0.0.1"
port = 8081

# Bind
s.bind((host, port))

# Listen and set backlog (?)
s.listen(5)

# Process connections
print('Listening on port', port)
while True:
    c, addr = s.accept()
    print("Got connection from", addr)
    msg = "
This is a test

More content here
"

    response_headers = {
        'Content-Type': 'text/html; encoding=utf8',
        'Content-Length': len(msg),
        'Connection': 'close',
    }

    response_headers_raw = ''.join('%s: %s\r\n' % (k, v) for k, v in response_headers.items())

    response_proto = 'HTTP/1.1'
    response_status = '200'
    response_status_text = 'OK' # this can be random

    # sending all this stuff
    r = '%s %s %s\r\n' % (response_proto, response_status, response_status_text)
    c.send(r)
    c.send(response_headers_raw)
    c.send('\r\n') # to separate headers from body
    c.send(msg.encode(encoding="utf-8"))

    c.close()

A: According to the ERR_CONNECTION_RESET error, chances are your tcp socket doesn't listen to the port successfully.
I change the port to 8080 in your code and write a Hello world in the output, resulting in getting the right HTML page.
If you want to listen to 80 port successfully, you have to use root user privilege to run your python script:
`sudo python server.py'
That is because 80 port is a system restricted port:Why are the first 1024 ports restricted to the root user only?.

A: I assume that you will be able to listen to port 80 and accept connections because otherwise your server should throw an exception early.
My guess is you get the connection reset because your server does not read the clients request but instead simply sends some data and closes the connection - with the request from the client still in the socket buffer. This is such a typical error which was already asked and answered at Perl: Connection reset with simple HTTP server and HTTP Server Not Sending Complete File To WGET, Firefox. Connection reset by peer? and "The connection was reset" on web browsers when trying to connect to a localhost socket server and Ultra simple HTTP socket server, written in PHP, behaving unexpectedly and Simple http generic server using fork and dup.


text:
Q: Equation $x^2 + y^2 + 1 = 0$ (mod $p$) How to prove that equation $x^2 + y^2 + 1 = 0$ (mod $p$) has roots?
Hints are acceptable.

A: Hint: Let $p$ be an odd prime. Note that $x^2$ takes on $\frac{p+1}{2}$ distinct values modulo $p$, and so does $-(y^2+1)$. Now use the Pigeonhole Principle.


text:
Q: jQuery - event parameter vs this? When I was browsing some ideas for wizard step forms I found the below code and spotted the usage of event parameter e as well as $(this).
From my understanding $(this) also has event object information
but since e is the parameter used in this example, why not use e throughout the code block instead of this?
$(document).ready(function() {
    $('a').click(function(e) {
        e.preventDefault();
        var parent = $(this).parent('div'), grandpa = $('.steps-content>div'), index = grandpa.index(parent)+1;
        parent.removeClass('content-active');
        grandpa.eq(index).addClass('content-active');
$('.steps-wizard').children('div').removeClass('step-active').eq(index).addClass('step-active');
    });
});

A: In this example e is used in
e.preventDefault();

which is used to prevent the link default's action, that is leading the browser to another page.
That's something that can't be done using just this.

A: e.target is this. e also has other methods and propertes. See here for further details of the jquery event object


text:
Q: R delete rows with least count based on multiple rows I have the below dataset:
   Var1  Var2  Var3 Var4
1 Rank 1 Sub 1     0   10
2 Rank 1 Sub 1     0   20
3 Rank 2 Sub 2     0   30
4 Rank 1     0 Sub 1   40
5 Rank 2 Sub 2     0   50
6 Rank 2     0 Sub 2   10

I want to remove the rows that have the least values based on Var2 and Var3. For example, Rank 1 (in Var1) has 2 values in Var2 and 1 value in Var3. I want to remove all entries of Rank 1 that have a value in Var3 and keep all entries that have a value in Var2. The same applies for all other Var1 values.
So the final result will be:
       Var1  Var2  Var3 Var4
    1 Rank 1 Sub 1     0   10
    2 Rank 1 Sub 1     0   20
    3 Rank 2 Sub 2     0   30
    4 Rank 2 Sub 2     0   50

Is there a way to do that? find the code to build the above table below:
Var1 = c("Rank 1", "Rank 1", "Rank 2", "Rank 1", "Rank 2")
Var2 = c("Sub 1", "Sub 1", "Sub 2","0", "Sub 2")
Var3 = c(0, "Sub 1", 0, "Sub 1", "0" )
Var4 = c(10,20, 30, 40,50)
df <- data.frame(Var1,Var2,Var3,Var4)

PS: This will be a very large dataset with multiple entries in both Var2 and Var3
Thanks

A: Use dplyr package to group on Var1 to count non-zero values for both Var2 and Var3 columns.  Based on the which count is greater, the filter criteria can be applied on respective columns. The case_when will make logic simpler and cleaner.
library(dplyr)
df %>% mutate_if(is.factor, as.character) %>%
  group_by(Var1) %>%
  filter( case_when(
    sum(Var2 != "0") >= sum(Var3 != "0") ~ Var2 != "0",
    sum(Var2 != "0") < sum(Var3 != "0") ~ Var3 != "0"
      ))
    # # A tibble: 4 x 4
# # Groups: Var1 [2]
# Var1   Var2  Var3   Var4
# <chr>  <chr> <chr> <int>
# 1 Rank 1 Sub 1 0        10
# 2 Rank 1 Sub 1 0        20
# 3 Rank 2 Sub 2 0        30
# 4 Rank 2 Sub 2 0        50

Data:
df <- read.table(text =
"Var1  Var2  Var3 Var4
1 'Rank 1' 'Sub 1'     0   10
2 'Rank 1' 'Sub 1'     0   20
3 'Rank 2' 'Sub 2'     0   30
4 'Rank 1'     0 'Sub 1'   40
5 'Rank 2' 'Sub 2'     0   50
6 'Rank 2'     0 'Sub 2'   10",
stringsAsFactors = FALSE, header = TRUE)


text:
Q: How to see an xml object in firefox console jQuery.get("oberonmetadata.xml", function(metadata){
    console.log(metadata);
});

This shows me [column,column,.... (as shown in pic below)] in console and when I click on it, it exands its whole object tree structure...
Whereas all I want to see is metadata.xml file in console.  This works flawlessly in chrome but in IE-9 and mozilla I am unable to do it.

Thanks

A: Try console.log(metadata.xml);
See here for more info.

A: If you simply want to log the response to console, utilize the 3rd parameter passed to the success callback and examine its responseText property which contains a string representation of the document returned.
$.get("oberonmetadata.xml", function(data, status, response){
    console.log(response.responseText);
});

This works for me in all browser environments.


text:
Q: CSS dropdown menu z-index I'm trying to do a dropdown menu that I designed with photoshop. However, there is a border in the top of this menu. The image, can explain it better:

Using CSS, all I get is a line that covers more that it is designed to. I tryed to use z-index position to make, but without success. Take a look at my code:

nav{

    display: inline;
    font-weight:900;
    text-transform:uppercase;
    font-size:13px;
    margin-left:95px;
}
.menu > li > a {

    width:auto;
    padding:10px 20px 10px 10px;
    background-image:url('img/seta_menu.png');
    background-repeat:no-repeat;
    background-position:right 50%;
}

.menu>li{

    width:auto;
    margin-right:45px;
    padding:10px;
    border-left: solid 1px #F8FAFA;
    border-right: solid 1px #F8FAFA;
    border-top:solid 1px #F8FAFA;
    border-bottom:solid 1px #F8FAFA;
}

.menu>li:hover{

    border-left: solid 1px #bdc9c5;
    border-right: solid 1px #bdc9c5;
    border-top:solid 1px #bdc9c5;
    border-bottom:solid 1px #bdc9c5;
    background-color:white;

}

nav>div{

    display:inline;

}
nav>div>ul{

    display: inline;

}
.menu li{
    display: inline-table;
}
.menu>li:hover >ul{

    display:block;

}
.sub-menu{

    position:absolute;
    display:none;
    padding:10px;
    margin-left:-11px;
    margin-top:10px;
    border-left: solid 1px #bdc9c5;
    border-right: solid 1px #bdc9c5;
    border-bottom:solid 1px #bdc9c5;
    /*border-top:solid 1px #bdc9c5;*/
    background-color:white;

}

.sub-menu ol, ul {

    padding:0px;
    margin:0px;

}
.sub-menu > li{

    display:block;

}

http://jsfiddle.net/btgfE/

A: Problem solved...
jsfiddle: http://jsfiddle.net/btgfE/2/
1) uncomment the top border of the .sub-menu
2) comment out the bottom border of the .menu>li:hover
3) give .sub-menu the css rule z-index:-1;
4) decrease the margin-top of .sub-menu to 9px
Really what this is doing is letting the top level menu item slightly overlap ontop of the sub-menu item's top border, giving the appearance you are looking for

A: I have edited your fiddle here:
http://jsfiddle.net/btgfE/4/
I gave the .submenu a z-index of -1, this fixed it.
I also changed the colours so they are more easily visible. You will want to set the green to white, I did this so that you can see the border is on top of the sub-menu's border


text:
Q: Calculating number of times each IAT was called from PE I am trying to calculate the number of times each IAT-import address table was called by a PE. It is like this:
counter=0

for entry in file.DIRECTORY_ENTRY_IMPORT:

    print (entry.dll)

    for imp in entry.imports:

        print ('\t', hex(imp.address), imp.name)

        counter=counter+1

    print(entry.dll,":",counter)

The output is somewhat like this:
b'KERNEL32.dll'
 0x180006000 b'GetProcAddress'

 0x180006008 b'LoadLibraryA'

 0x180006010 b'IsProcessorFeaturePresent'

 0x180006018 b'GetStartupInfoW'

 0x180006020 b'SetUnhandledExceptionFilter'

 0x180006028 b'UnhandledExceptionFilter'

 0x180006030 b'IsDebuggerPresent'

 0x180006038 b'RtlVirtualUnwind'

 0x180006040 b'RtlLookupFunctionEntry'

 0x180006048 b'RtlCaptureContext'

 0x180006050 b'InitializeSListHead'

 0x180006058 b'DisableThreadLibraryCalls'

 0x180006060 b'GetSystemTimeAsFileTime'

 0x180006068 b'GetCurrentThreadId'

 0x180006070 b'GetCurrentProcessId'

 0x180006078 b'QueryPerformanceCounter'

 0x180006080 b'GetModuleHandleW'

b'KERNEL32.dll' : 17
b'MSVCP140.dll'
 0x180006090 b'?_Xout_of_range@std@@YAXPEBD@Z'

 0x180006098 b'?_Xlength_error@std@@YAXPEBD@Z'

 0x1800060a0 b'?_Xbad_alloc@std@@YAXXZ'

b'MSVCP140.dll' : 20
b'VCRUNTIME140.dll'
 0x1800060b0 b'_purecall'

 0x1800060b8 b'__std_terminate'

 0x1800060c0 b'memmove'

 0x1800060c8 b'_CxxThrowException'

 0x1800060d0 b'__std_type_info_destroy_list'

 0x1800060d8 b'__RTDynamicCast'

 0x1800060e0 b'memcpy'

 0x1800060e8 b'__C_specific_handler'

 0x1800060f0 b'__std_exception_copy'

 0x1800060f8 b'__std_exception_destroy'

 0x180006100 b'__CxxFrameHandler3'

 0x180006108 b'memset'

b'VCRUNTIME140.dll' : 32
But it should count each entry individually. For example, MSVCP140.dll should be counted as '3' and not '20'. Any help would be gladly appreciated.


text:
Q: PhantomJS page-break-inside and last PDF page background I have a PhantomJS script which generates a PDF from an HTML, the HTML contents have some structure separated by "rows" of content (rows as in Bootstrap), I have added the "page-break-inside: avoid" this "rows" of content so the content doesn't cut in the middle of two pages.
The thing I want to do now is to fill the last page background, because the content is dynamic the last page background doesn't fill the entire PDF page, I did some calculations in order to make the html body bigger before rendering based on the body height, but I realize PhantomJS is returning the height based on the viewport size and not the PDF size.
Is there anyway to know the PDF body heigh or any work arround to always fill the latest page background or in the worst scenario to tell phantom to use a background color for all pages?


text:
Q: Unit test can not pass I have the program which make division.
I need to print division to the screen, I did It and on the screen everything the same but unit test still fails..

Below the class that print It :
 private String drawResultForDividentThatEqualsZero(StringBuilder result, Integer divisor) {
    result.append("_0").append(SYMBOL_VERTICAL_BAR).append(divisor.toString()).append("\n");
    result.append(" 0").append(SYMBOL_VERTICAL_BAR).append("-").append("\n");
    result.append(" -").append(SYMBOL_VERTICAL_BAR).append("0").append("\n");
    result.append(" 0");

    return result.toString();
}

And some code :
 public static final String SYMBOL_VERTICAL_BAR = "|";

 StringBuilder result = new StringBuilder();

The test which does not pass :
@Test
public void Should_MakeDivision_When_DividentEqualsZero() {
    String expected = "_0│100\n" +
            " 0│-\n" +
            " -│0\n" +
            " 0";
    assertEquals(expected, numbersDivision.makeDivision(0, 100));
}

Main method makeDivision :
public String makeDivision(int introducedDividend, int introducedDivisor) {

    StringBuilder result = new StringBuilder();
    StringBuilder reminder = new StringBuilder();
    StringBuilder quotientForDividentMoreThanDivisor = new StringBuilder();
    StringBuilder quotientForDividentLessThanDivisor = new StringBuilder("0.");
    StringBuilder lastReminderNumber = new StringBuilder();

    int dividend = Math.abs(introducedDividend);
    int divisor = Math.abs(introducedDivisor);
    checkExceptions(divisor);

    Integer divisorMuplipliedByQuotient = 0;
    Integer reminderInInteger = 0;
    Integer newReminder = 0;

    String[] digits = String.valueOf(dividend).split("");

    mainMethodForCalculateDivision(dividend, divisor, digits, reminderInInteger, reminder, divisorMuplipliedByQuotient, result, quotientForDividentMoreThanDivisor, quotientForDividentLessThanDivisor,
            newReminder, lastReminderNumber);
    return result.toString();
}

And the main work class for this case :
private String mainMethodForCalculateDivision(Integer dividend, int divisor, String[] digits, Integer reminderInInteger, StringBuilder reminder, Integer divisorMuplipliedByQuotient,
                                              StringBuilder result, StringBuilder quotientForDividentMoreThanDivisor, StringBuilder quotientForDividentLessThanDivisor,
                                              Integer newReminder, StringBuilder lastReminderNumber) {
    if (dividend == 0) {
        drawResultForDividentThatEqualsZero(result, divisor);
        return result.toString();
    }
    if (dividend >= divisor) {
        for (int i = 0; i < digits.length; i++) {
            calculateDivisionWhenDividentMoreOrEqualsDivisor(reminder, digits, i, divisor, divisorMuplipliedByQuotient, dividend,
                    result, quotientForDividentMoreThanDivisor, quotientForDividentLessThanDivisor, newReminder, lastReminderNumber);
        }
        improveResultViewing(dividend, divisor, result, quotientForDividentLessThanDivisor, quotientForDividentMoreThanDivisor, lastReminderNumber,
                reminderInInteger);
        return result.toString();
    }
    checkIfDividentEqualsZeroOrLessThanDivisorAndCalculate(dividend, divisor, reminder, reminderInInteger, digits, divisorMuplipliedByQuotient, newReminder, quotientForDividentMoreThanDivisor,
            quotientForDividentLessThanDivisor, result, lastReminderNumber);
    return result.toString();
}

A: Symbols in "expected" and in "SYMBOL_VERTICAL_BET" are different.


text:
Q: Image Panel doesn't show up immediately in JFrame So I have a class which extends JPanel and on which I draw a BufferedImage (in its paintComponent method).
However, the image doesn't show up until I resize the window. Any idea how to fix this?
I've tried repaint without much success.

A: You must use the validate(); method along with repaint();.
frame.repaint();
frame.validate();
frame.setVisible(true);


text:
Q: Java library function for converting from gregorian timestamp to UNIX timestamp(epoch) I am getting a variable with Gregorian seconds and would like to use it in Java. Is there a library function in Java <=8, JodaTime, Apache commons, guava or anything else, where this is implemented?
I know I can convert the gregorian seconds to epoch timestamp by multiplying by 1000 and then subtracting 62167219200000 but I'd prefer not to hardcode it if there already is an implementation. I haven't found any so far.
[edit: this is not a duplicate of the linked question, there's no xml dateTime used here, the answer in linked question does not answer this one]


text:
Q: (ring homomorphisms $k[X] / (f(X)) → R)$ ⇆ $\{x \in k | f(x) = 0 \}$ one-to-one correspondence I want to prove that there is a bijection from the set of $k$-algebra homomorphisms $k[X] / (f(X))\rightarrow R$ to $V(f) = \{x \in k | f(x) = 0 \}$, where $k$ is a field.
What should I do?
Thanks in advance!


text:
Q: Changing two fields in large table from varchar to nvarchar and back again has made table very slow, large differentials on backup also? A colleague of mine changed two fields on a large table that relates to forum posts from varchar to nvarchar and then back again.  The two original fields were varchar(500) and varchar(8000) and were changed to nvarchar(500) and nvarchar(max) and back again.  The table contains approximately 1 million rows, one of the fields is for forum posts and so can contain a decent amount of text.  This table seems to have foreign keys for both the registration table and the table containing the forum topic where the replies are present.
On making the change queries to this table seem to be a lot slower, leading to timeouts.  I've noticed that there was a differential to the backup at roughly the time the field was changed to nvarchar of 1.3GB, which is much larger than a regular differential backup for this db.  Presumably this was changing the post field from varchar to nvarchar.  The odd thing is the differential is now absolutely huge each time, as if it is backing up the entire db.  This is causing the additional problem of losing space on the hd.
What has caused this problem and how can we fix it?  Thanks.

A: Check your recovery model, truncate logs or create backup.


text:
Q: Do I have to define every button on screen in xml if those buttons are generated in a grid every time a new game is made? I am working on a small personal project to port a version of the Same Game that I made to android. I have most of the game coded in java (still finishing it), but I am reading up on android development (reading the documentation and watching thenewboston on youtube). I am curious about the AndroidManifest.xml. If I understand correctly, everything that goes on screen is defined in that xml file. However, my java game has its own code to create the board:
 //game board
JFrame gameBoard = new JFrame();
gameBoard.setTitle("CrossGame");
gameBoard.setSize(400,400);

int numColors = 3;

//board grid
JPanel boardGrid = new JPanel(new GridLayout(gridSize, gridSize));

try {
  UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}
catch (Exception e) {
}
//A loop to add a new button to each section of the board grid.
for (int i = 0; i < gridSize; i++) {
  for (int j = 0; j < gridSize; j++) {

    gameButtons[i][j] = new JButton();
    gameButtons[i][j].addActionListener(new Listener());
    gameButtons[i][j].setBackground(colors[(int)(Math.random() * numColors)]);
    boardGrid.add(gameButtons[i][j]);

  }
}

//Adds the grid of buttons to the window.
gameBoard.add(boardGrid);
//Quits the program when the close window button is pressed.
gameBoard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameBoard.setVisible(true);

}
I am programming on a Mac, which is why I have the setLookAndFeel in there. Do all these buttons have to be defined in the XML? Or do I have to revamp this code?

A: Android do recommend to add button in xml to separate out Business and Presentation Layer. But it is not mandatory. So you can revamp them entirely in your code also just like java application
 For Example::
 for(int i::n)//depend upon your loop requirement
  {
      layout = (LinearLayout) findViewById(R.id.statsviewlayout);
      Button bi = new Button(this);
      bi.setText(R.string.button_back);
      bi.setLayoutParams(new LayoutParams(
      ViewGroup.LayoutParams.WRAP_CONTENT,
      ViewGroup.LayoutParams.WRAP_CONTENT));
      layout.addView(bi);
  }

A: You can generate the interface dynamically as you do currently, however there are several advantages to using the XML layout facilities.
Firstly you need to be clear that there are many different xml files involved in an android application. The manifest file is not (in general ) oriented around screen layout.
If you were to use an xml layout file instead of dynamically creating your buttons, android provides excellent facilities for designing multiple versions for different device sizes and resolutions.

A: You can randomized the style using
array.xml
<?xml version="1.0" encoding="utf-8"?>
<array name="color">
<item name="green">0000FF</item>
<item name="red">FF0000</item>
<item name="blue">00FF00</item>
</array>

You can use these array file in random fashion to style your button
  Resources re=getResources();
  bi.setBackGroundColor(random(r.getArray(color)));

Hope these might help your programming structure


text:
Q: Extending a block disables whole output on Magento2 - Product - Reviews I've tried to extend \Magento\Review\Block\Product\View\ListView. I've did so by creating a new module, MS_RealReviews. Within that I've created Block/Review.php and etc/frontend/di.xml and a few others. This is my file tree:

Block/Review.php:
<?php
namespace MS\RealReviews\Block;

class Review extends \Magento\Review\Block\Product\View\ListView
{

    public function isRealReview(){
        // Codebla
    }

}

etc/frontend/di.xml:
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Review\Block\Product\View\ListView" type="MS\RealReviews\Block\Review" />
</config>

default.xml
<?xml version="1.0"?>
<!--
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>

        <referenceContainer name="content">
            <referenceContainer name="product.info.details">
                <block class="MS\RealReviews\Block\Review" name="product.info.product_additional_data" as="product_additional_data" template="product/view/list.phtml"/>
            </referenceContainer>
        </referenceContainer>

        <referenceBlock name="product.info.product_additional_data" remove="true" />

    </body>
</page>

The list.phtml is an unmodified copy of the original file.
When now checking the product page, I do not get any output anymore. I see the form, but once submitted and enabled in the backend, the review is not there.
What am I missing here?

A: Got it. In the end I got 2 errors to solve.
I my case the cause of the failure was my wrong referenceContainer tag instead of referenceBlock in default.xml. This caused an Exception and rendered the page useless.
And there was a type, also in default.xml. I've used the wrong class name. I had that already fixed when edited the Question.


text:
Q: PostgreSQL : Difference between ItemIdData & CTID According to postgres documentation :
ItemIdData is an Array of item identifiers pointing to the actual items. Each entry is an (offset,length) pair.
&
CTID is The physical location of the row. and this is also pair.
Please help to understand that whether both are same?
Thanks ..!

A: I can find only one mention of ItemIdData in the postgres docs, and that is in the Database Page Layout section. It explains the difference quite well:

Every table […] is stored as an array of pages of a fixed size.
Following the page header are item identifiers (ItemIdData), each
requiring four bytes. An item identifier contains a byte-offset to the
start of an item, its length in bytes, and a few attribute bits which
affect its interpretation. […] Because an item identifier is never
moved until it is freed, its index can be used on a long-term basis to
reference an item, even when the item itself is moved around on the
page to compact free space. In fact, every pointer to an item
(ItemPointer, also known as CTID) created by PostgreSQL consists
of a page number and the index of an item identifier.

      (Emphasis mine)
So no, they're not the same.


text:
Q: How to test Rails model associations Trying to test a module. It works when executed in rails console, but not when written as a test. Suppose the following:

*

*MyModel
a) has_many :my_other_model

*MyOtherModel
a) belongs to :my_model
Module example:
module MyModule

  def self.doit
    mine = MyModel.first
    mine.my_other_models.create!(attribute: 'Me')
  end

end

Now test:
require 'test_helper'

class MyModuleTest < ActiveSupport::TestCase

  test "should work" do
    assert MyModule.doit
  end

end

Returns:
NoMethodError: NoMethodError: undefined method `my_other_models' for nil:NilClass

Now try the same thing in the console:
rails c

MyModule.doit

Works just fine. But why not as a test?

A: Your test database is empty when you run this test, so calling MyModel.first is going to return nil, then you try to chain an unknown method to nil. What you'll probably want for your test suite is a fixture, which is just sample data. For now, you you can just create the first instance to get the test to work.
  test "should work" do
    MyModel.create #assuming the model is not validated
    assert MyModule.doit
  end

You could also refactor your module. Adding if mine will only try to create the other models if mine is not nil. That would get the test to pass, but negates the purpose of your test.
  def self.doit
    mine = MyModel.first
    mine.my_other_models.create!(attribute: 'Me') if mine
  end


text:
Q: How do I call an API in another project but same solution without hard-coding the url? I have two projects. One for my front-end angular code. Another for Web API. When I'm in the front-end project, I want to make a call to an API in my other project.
The Web API tutorials I have seen show a relative url involving /api such as this:
    $http.get("/api/trivia")
That works great if the javascript is in the same project as Web API, but it's not for my Solution.
I can hard-code the url to my API's localhost port and it works fine, but of course that won't work when I deploy the app to Azure. How should I be handling these urls?
Thank you.

A: When you make a $http with full url  (http://...) it directly look at given address. But when you specify relative path (without http://...) it look at your current site + given relative path url.
So If your api also hosted in same site you can still make the reference as $http.get("/api/trivia") or else as you said if you know where you host your site in Azure you can make it hard code in in your script.


text:
Q: GAE - Search API - search doesn't return newly added documents Im using GAE Search API in my server implementation and have been experiencing a strange and undocumented behavior. Sometime new documents that were just added to an index (Index.put()) are not retrieved by searches (Index.search()) that are being performed straight after. Sometime it takes even a minute or so until they become available.
It looks like an eventual consistency problem but i couldnt find anything in the documents that even mentions this issue in relation to the Search API. Stranger is the fact that during this time that these documents are unavailable, i can perform the exact same query on the Admin Console and get the expected results.
Anyone knows what's the deal here ? Is this a normal behavior ? If so, then what is the maximum time for a newly added document until it can be searched ? And why isn't this documented ? This seriously affects my app's functionality.
Thanks.

A: From your additional comments it is logical and absolutely essential that all newly added points-of-interest must appear on the user's map.  However the Search service will probably continue to not return new additions for an unpredictable amount of time.  I would consider two strategies, one server-side and one client-side, and perhaps even use both.  But neither is simple.
On the server you could augment the Search service or even replace it entirely with a custom Search that you would develop yourself.  Store the data you want to search in Google Cloud SQL which is basically MySQL.  This will always immediately return what is written into it, because it is a single instance not subject to eventual consistency.
In the client you could cache all recently added points of interest.  Then when requesting data from the server, also query the local cache.  Delete any local results that duplicate what the server returns.  Other users will also eventually see what this user sees immediately.

A: Yes it makes sense that eventual consistency (Brewer's keynote PDF) also applies to Search.  No documented maximum convergence time probably means implementing one would on balance be counterproductive.  Without a timing guarantee, GAE might even evolve and behave differently in future.  I heard that some GAE users migrate to Riak in order to tune their CAP parameters to suit specific application timing requirements.
The symptom of your newest writes appearing in different subsystems at different times suggests distributed cacheing.  Your best strategy is to redesign your functionality to rely less on timing.  Most scalable applications have done that.


text:
Q: In RactiveJS how can I detect is it detached? I want to
if(ractive.isDetached()){
    otherRactive.detach();
    ractive.render().then(()=>ractive.insert());
}

Instead of insert and detach every time, how can I achieve this ?

A: This question was answered on GitHub – for future travellers, the tl;dr is you can either render to a specific target, or insert an already-rendered ractive to a new target (detaching it if it's currently in the DOM).
function insertRactive( ractive, node ) {
  if( ractive.fragment.rendered ) ractive.insert( node );
  else ractive.render( node );
}

Note that we're determining if an instance is rendered with ractive.fragment.rendered, though note that this isn't officially part of the API and is therefore subject to change, so it's better to keep track of it yourself.


text:
Q: How to fix this program to show 0's in the output I have this code
int main()
    {
        int mobBroj,prvicifri,vtoricifri,treticifri;
        scanf("%d", &mobBroj);
        prvicifri = mobBroj / 1000000;
        vtoricifri = (mobBroj % 1000000) / 1000;
        treticifri = mobBroj % 1000;
        if(prvicifri == 70 || prvicifri == 72 || prvicifri == 71)
        printf("0%d/%d-%d T-mobile", prvicifri, vtoricifri, treticifri);
        else if(prvicifri == 75 || prvicifri == 76 || prvicifri == 77 || prvicifri == 78)
        printf("0%d/%d-%d A1", prvicifri, vtoricifri, treticifri);
        else
        printf("0%d/%d-%d LycaMobile", prvicifri, vtoricifri, treticifri);

        return 0;
    }

And for input 070120004 i get 070/120-4. If the zero is at the beggining its not outputing. How to fix this?


text:
Q: Specify Azure key in Spark 2.x version I'm trying to access a wasb(Azure blob storage) file in Spark and need to specify the account key.
How do I specify the account in the spark-env.sh file?
fs.azure.account.key.test.blob.core.windows.net
   EC5sNg3qGN20qqyyr2W1xUo5qApbi/zxkmHMo5JjoMBmuNTxGNz+/sF9zPOuYA==

WHen I try this it throws the following error
fs.azure.account.key.test.blob.core.windows.net: command not found

A: From your description, it is not clear that the Spark you used is either on Azure or on local.
For Spark running on local, refer this blog post which introduces how to access Azure Blob Storage from Spark. The key is that you need to configure Azure Storage account as HDFS-compatible storage in core-site.xml file and add two jars hadoop-azure & azure-storage to your classpath for accessing HDFS via the protocol wasb[s].
For Spark running on Azure, the difference is just only access HDFS with wasb, all configurations have been done by Azure when creating HDInsight cluster with Spark.


text:
Q: Call the Azure Resource Graph API from .NET Application I am trying to author an application that allows a user to query a list of websites from their Azure subscription from within my application. I do not want to store their credentials in my app (nor should they want me to), but instead I would ask them them to register an Application from within their Azure AD instance, and then have them store the ClientID and TenantID generated in my app. I would give them a set of instructions on how to do this from their Azure Portal that uses the most restrictive permissions possible, and that they could turn off at anytime. They need to feel comfortable doing this, as I would.
I am trying to follow the plot of this article:
Using Azure resource graph with .net SDK
It gets me very close, but when I run the app I get a "Forbidden" response from the Azure Resource Graph, so the call is getting through but is being rejected. I have also tried to add various API Permissions using my own Azure Portal for testing. The article says that I need to create a service principal using:
az ad sp create-for-rbac -n "MyApp" --role contributor --sdk-auth
Which I have not done, yet.
So my questions are:

*

*Is this my problem?

*Do I need to ask my user to create a service principal, and if so, what value goes into the "MyApp" variable in the example above?

*Is there a better approach to doing this that expects less of the user?
I appreciate any guidance or article referrals anyone can provide.
Many thanks....

A: If you want to call Azure resource graph Rest API with service principal, you must assign Azure RABC Role to the sp. So you must run the following command
# it will create a service pricipal and assign a contributor rolen to the sp
az ad sp create-for-rbac -n "MyApp"  --scope "/subscriptions/<subscription id>" --sdk-auth

# if you have a service principal, please run the following script
az ad sp list --display-name "{name}" --query [].objectId --output tsv
az role assignment create --assignee <sp object id> --role "Contributor " --scope "/subscriptions/<subscription id>"

Meanwhile, the detailed steps about how to run the sample are as below

*

*Run the following script.

az login
az ad sp create-for-rbac -n "MyApp"  --scope "/subscriptions/<subscription id>" --sdk-auth

*Configure Code. Please note that if you want to call the resource in the different subscriptions, you need to create different service principal by changing the scope value in step1

public  async static Task Test() {

            CustomLoginCredentials creds = new CustomLoginCredentials();

            var resourceGraphClient = new ResourceGraphClient(creds);

            var queryReq = new QueryRequest {

                Subscriptions = new List<string> { "<the subscriptionId you copy>" },
                Query = "where type == 'microsoft.web/sites'"

            };
            var result = await resourceGraphClient.ResourcesAsync(queryReq);
            Console.WriteLine(result.Count);
        }

class CustomLoginCredentials : ServiceClientCredentials {
        private static string tenantId = "<the tenantId you copy >";
        private static string clientId = "<the clientId you copy>";
        private static string cert = "<the clientSecre tyou copy>";
        private string AuthenticationToken { get; set; }
        public override void InitializeServiceClient<T>(ServiceClient<T> client)
        {
            var authenticationContext =
                new AuthenticationContext("https://login.microsoftonline.com/"+tenantId);
            var credential = new ClientCredential(clientId: clientId, clientSecret: cert);

            var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/",
                clientCredential: credential).Result;

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            AuthenticationToken = result.AccessToken;
        }
        public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (AuthenticationToken == null)
            {
                throw new InvalidOperationException("Token Provider Cannot Be Null");
            }

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);

            await base.ProcessHttpRequestAsync(request, cancellationToken);

        }

For more details, please refer to
https://odetocode.com/blogs/scott/archive/2018/02/01/setting-up-service-principals-to-use-the-azure-management-apis.aspx
https://learn.microsoft.com/en-us/cli/azure/ad/sp?view=azure-cli-latest#az-ad-sp-create

update
According to your needs, I think you can create a web application to call Azure Resource Graph API. If you do that, you can provide the url of web app then your customers can login your application and call the API by themselves.

*

*Register  Azure AD web application

2.Configure permissions

*Create client secret

*Configure code. Please refer to the sample


text:
Q: Transform data from columns to rows in excel I need to transform data that is in multiple rows and multiple columns into unique rows, but there are specific rules around what i need. An example of the current data format is below:

The split should be based on the style, colour and unique upc but i need to copy some of the fields to each unique upc for the style and colour. I also need to show a parent child relationship.
The example below is how I want the data to be shown.

I've tried doing this in power query...but totally stuck!
Thanks in advance for any advice.

A: This seems to work in powerquery pasted into home...advanced editor.. assuming your initial table is range Table1 and similar to the sample structure you provided
Unpivot, remove numbers from the the attributes, group and add index for the later pivot, pivot.  The rest is just custom columns and filling
 let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
 #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"style", "colour"}, "Attribute", "Value"),
 #"removed numbers" = Table.TransformColumns(#"Unpivoted Other Columns",{{"Attribute", each Text.Remove(_, List.Transform({48..57}, each Character.FromNumber(_))), type text}}),
 #"Grouped Rows" = Table.Group(#"removed numbers", {"style", "colour", "Attribute"}, {{"data", each Table.AddIndexColumn(_, "Index", 2, 1), type table}}),
 #"Expanded data" = Table.ExpandTableColumn(#"Grouped Rows", "data", {"Value", "Index"}, {"Value", "Index"}),
 #"Added Custom" = Table.AddColumn(#"Expanded data", "Custom", each if [Attribute]="description" then 1 else [Index]),
 #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Index"}),
 #"Pivoted Column" = Table.Pivot(#"Removed Columns", List.Distinct(#"Removed Columns"[Attribute]), "Attribute", "Value"),
 #"Added Custom1" = Table.AddColumn(#"Pivoted Column", "parent", each if [description]=null then "child" else "parent"),
 #"Filled Down" = Table.FillDown(#"Added Custom1",{"description"}),
 #"Removed Columns1" = Table.RemoveColumns(#"Filled Down",{"Custom"})
 in  #"Removed Columns1"

Alternate version that uses index and transform on that column prior to pivoting
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"style", "color", "desc"}, "Attribute", "Value"),
#"removed numbers" = Table.TransformColumns(#"Unpivoted Other Columns",{{"Attribute", each Text.Remove(_, List.Transform({48..57}, each Character.FromNumber(_))), type text}}),
#"Added Index" = Table.AddIndexColumn(#"removed numbers", "Index", 1, .5),
#"Rounded Down" = Table.TransformColumns(#"Added Index",{{"Index", Number.RoundDown, Int64.Type}}),
#"Pivoted Column" = Table.Pivot(#"Rounded Down", List.Distinct(#"Rounded Down"[Attribute]), "Attribute", "Value"),
#"Added Custom1" = Table.AddColumn(#"Pivoted Column", "parent", each "child"),

#"Add parent" = Table.Combine({Table.AddColumn(Table.Distinct(Table.SelectColumns(#"Added Custom1",{"style", "color", "desc"})), "parent", each "parent"), #"Added Custom1"}),

#"Removed Columns" = Table.RemoveColumns(#"Add parent",{"Index"}),
#"Reordered Columns" = Table.ReorderColumns(#"Removed Columns",{"style", "color", "upc", "size", "desc", "parent"}),
#"Sorted Rows" = Table.Sort(#"Reordered Columns",{{"style", Order.Ascending}, {"color", Order.Ascending}, {"upc", Order.Ascending}})
in  #"Sorted Rows"

A: Here is another Power Query method that uses a custom function to enable creation of a Pivot Table with no aggregation where there are multiple items.
Examine the comments in the M-Code and the Applied steps, and also the reference in the custom function, to understand how it works:
To enter the custom function, select to

*

*New Query => Blank Query.

*Rename the Query from (probably) Query1 to fnPivotAll
M Code
//Rename Table3 to your actual table name
let Source = Excel.CurrentWorkbook(){[Name="Table3"]}[Content],

//Unpivot all except the style and color columns
 #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"style", "colour"}, "Attribute", "Value"),

//remove digits from the UPC and SIZE attributes
 remDigits = Table.TransformColumns(#"Unpivoted Other Columns",{
     {"Attribute", each Text.Remove(_, List.Transform({48..57}, each Character.FromNumber(_))), type text}}),

//Pivot on Attribute Column
//Custom function to use when there are multiple values for the column
pivot = fnPivotAll(remDigits,"Attribute","Value"),

//Fill in the blank descriptions
    #"Filled Down" = Table.FillDown(pivot,{"description"}),

//Group (by style, colour and description) to add a description row to each grouped table
    #"Grouped Rows" = Table.Group(#"Filled Down", {"style", "colour", "description"}, {
        {"All", each _, type table [style=text, colour=text, upc=number, size=any, description=text]},
        {"addRow", each Table.InsertRows(_, 0, {[style=[style]{0}, colour=[colour]{0}, upc=null, size=null, description=[description]{0}]})}
        }),
    #"Removed Columns" = Table.RemoveColumns(#"Grouped Rows",{"style", "colour", "description", "All"}),

//expand the grouped table
    #"Expanded addRow" = Table.ExpandTableColumn(#"Removed Columns", "addRow", {"style", "colour", "upc", "size", "description"}, {"style", "colour", "upc", "size", "description"}),

//Add column for Parent or child
    #"Added Custom" = Table.AddColumn(#"Expanded addRow", "Parent", each if [upc] = null then "Parent" else "Child")
in
    #"Added Custom"

Custom Function
named fnPivotAll  -- Rename the Query
//credit: Cam Wallace  https://www.dingbatdata.com/2018/03/08/non-aggregate-pivot-with-multiple-rows-in-powerquery/

(Source as table,
    ColToPivot as text,
    ColForValues as text)=>

let
     PivotColNames = List.Buffer(List.Distinct(Table.Column(Source,ColToPivot))),
     #"Pivoted Column" = Table.Pivot(Source, PivotColNames, ColToPivot, ColForValues, each _),

    TableFromRecordOfLists = (rec as record, fieldnames as list) =>

    let
        PartialRecord = Record.SelectFields(rec,fieldnames),
        RecordToList = Record.ToList(PartialRecord),
        Table = Table.FromColumns(RecordToList,fieldnames)
    in
        Table,

    #"Added Custom" = Table.AddColumn(#"Pivoted Column", "Values", each TableFromRecordOfLists(_,PivotColNames)),
    #"Removed Other Columns" = Table.RemoveColumns(#"Added Custom",PivotColNames),
    #"Expanded Values" = Table.ExpandTableColumn(#"Removed Other Columns", "Values", PivotColNames)
in
    #"Expanded Values"


text:
Q: PowerShell trying to convert to an integer instead of a string My problem is that PowerShell wants to convert "=" into an integer, when trying to use it to make a new string. I made sure that my resulting variable would also be a string. Here's my task:
I have a little Excel table like this:

___________|VLANID1|VLANID2|VLANID3|
SwitchName1|    1-7|  12-16|   8-11| ← Ports 1-7 of Switch1 are configure for VLAN1...
SwitchName2|    1-7|  12-16|   8-11|

Out of this table I want to save each port in an .ini file with the VLAN it is configured too, aka:
[SwitchName1]
1=VLANID1
2=VLANID3
...

And here's my code which I loop until there are no ports, and then no more switches.
$split = $global:Ports -split("-") #$Ports is the Value with the saved excel cell (7-11)
$split[0]..$split[1] | ForEach-Object {
    $vlan = $global:Switches.Cells.Item(1, $global:SSpallte).Text
    [string]$inistring = "`n" + $_ + "=" + $vlan #<- Here it tries to convert "=" into integer
    Add-Content -Path $global:portsini -Value $inistring
}

I even tried converting every variable which I use to make $inistring to a string before, it still doesn't work. Also, both $_ and $vlan have a Value and are not $null.
The Error states that "=" cannot be converted into the type "System.Int32".

A: So, im not quite sure what the problem was, but my way to solve it was to restart my environment. I am programming in the PowerShell ISE which I have sometimes seen "caching" variables. This restart of the ISE made the program work again.
And no, I didn't change anything beforehand.
In the end I'm happy that my problem is no more, but I'm still wondering why the error got triggered by the "=".


text:
Q: 30 days LeetCode April Challenge Day 1 - Single Number Am new to coding challenges,am trying to solve a coding challenge on leetCode. Can anybody help me understand the problem clearly to code in python.What you mean by Without using extra memory?
Problem
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1
Input: [2,2,1]
Output: 1

Example 2
Input: [4,1,2,1,2]
Output: 4

A: You can solve this problem without extra memory by using the XOR operator. The XOR logical operation, or exclusive or, takes two boolean operands and returns true if and only if the operands are different.
There are 2 properties of the XOR operator:

*

*XOR of a number with itself is 0.

*XOR of a number with 0 is number itself.

So, for example, when you do 2 ^ 2, the result will be 0 (0010 ^ 0010 = 0000), if you do 2 ^ 0, then the result will be 2 (0010 ^ 0000). As the problem stated, there is only one number appears once and every other appears twice, then when doing this operation, those identical will eliminate each other and give us the final number that appears once.
Here is the simple solution in Python which do it in-place (in-place means that you don't have to create auxiliary data structure to solve the problem):
def find_12_xor(items):
    result = 0
    for item in items:
        result ^= item
    return result


text:
Q: Creating a podspec file with local dependencies I'm trying to wrap my code into a CocoaPod library ( for external use as a SDK ) but I'm experiencing some problems ( I'm new at this so I'm sorry if it doesn't make to much sense). Basically I'm using 3 pods ( Alamofire, MobilePlayer and SwiftEventBus ) and these last 2 would be great if I had the files local to work with since I'm doing some modifications on it. Am I doing this right? And how can I "install" those dependencies to use it on my code ( not the example one but my Classes/*swift itself )?
I've tried this .podspec but it gives me some sintax errors when I run pod spec lint --verbose:
-> SambaPlayerSDK.podspec
    - ERROR | spec: The specification defined in SambaPlayerSDK.podspec could not be loaded.
[!] Invalid SambaPlayerSDK.podspec file: syntax error, unexpected =>, expecting keyword_end
  s.dependency = 'MobilePlayer', :local => 'library/mobileplayer-ios'
                                          ^
SambaPlayerSDK.podspec:41: syntax error, unexpected =>, expecting keyword_end
...y = 'MobilePlayer', :podspec => 'library/mobileplayer-ios/Mo...
...                               ^
SambaPlayerSDK.podspec:42: syntax error, unexpected =>, expecting keyword_end
  s.dependency = 'SwiftEventBus', :local => 'library/SwiftEventBus'
                                           ^
SambaPlayerSDK.podspec:43: syntax error, unexpected =>, expecting keyword_end
... = 'SwiftEventBus', :podspec => 'library/SwiftEventBus/Swift...
...                               ^. Updating CocoaPods might fix the issue.
  s.platform     = :ios, '8.0'
  s.requires_arc = true
  s.source_files = 'Pod/Classes/**/*'
  s.resource_bundles = {
    'SambaPlayerSDK' => ['Pod/Assets/*.png']
  }
  # s.public_header_files = 'Pod/Classes/**/*.h'
  # s.frameworks = 'UIKit', 'MapKit'
  # s.dependency 'AFNetworking', '~> 2.3'
  s.dependency = 'Alamofire', '~> 3.0'
  s.dependency = 'MobilePlayer', :path => 'library/mobileplayer-ios'
  s.dependency = 'MobilePlayer', :podspec => 'library/mobileplayer-ios/MobilePlayer.podspec'
  s.dependency = 'SwiftEventBus', :path => 'library/SwiftEventBus'
  s.dependency = 'SwiftEventBus', :podspec => 'library/SwiftEventBus/SwiftEventBus.podspec'

Thanks for any help =)


text:
Q: On the accuracy of the statement "Current is the source of all magnetism" Many physics textbooks and websites state that electric current is the source of all magnetism. They go on to support this statement by saying that electrons move around nuclei AND they have spin. Later, and almost without exception, the book or site will warn us that the term spin is not to be taken too literally because the electron is not actually spinning like a top, but is instead an intrinsic property of the electron.
My question is: aren't these sources contradicting themselves? If spin is not associated with moving charge, then how can it be claimed that all magnetism arises from electric current? It seems that if spin is an intrinsic property of electrons (and other particles), then in this case magnetism is also just an intrinsic property of them.

A: There are much easier, classical counterexamples to this claim. For example, a magnetic field can be created by a time-varying electric field, through induction. Context matters. These books are saying things like this in the context of a presentation of classical electromagnetism (in which there is no spin), and they're starting from magnetostatics (so there is no induction).
Similarly, a freshman physics textbook will present Newton's law of gravity without apologizing and saying that it's superseded by general relativity. They can't tell you everything before they even get started, and they're also mirroring the way that science advances, with new theories staying backward-compatible with older ones through the correspondence principle.
By the way, to me the word "source" has the connotation that it's a place where field lines begin or end. In this sense, current is not actually a source of the magnetic field, but you could say it's the cause of it.

A: It depends what you mean by current. If by this you mean the movement of charges, then certainly yes, it is wrong.
Current for electromagnetism, in a very general way, means the derivative of the interaction term with respect to the EM potential. For spinor fields, this corresponds to the vector current of the field
$$J^\mu = -\frac em \bar \psi \gamma^\mu \psi$$
which features in the Maxwell equation as
$${F^{\mu\nu}}_{,\mu} = \frac{e\mu_0}{m} \bar \psi \gamma^\nu \psi$$
The induction of a magnetic field from this is given by the relation $B_{i}=-{\frac {1}{2}}\epsilon _{ijk}F^{jk}$, which from
\begin{eqnarray}
{F^{\mu j}}_{,\mu} &=& \frac{e\mu_0}{m} \bar \psi \gamma^j \psi\\
&=& - {F^{tj}}_{,t} + {F^{ij}}_{,i}\\
&=& \frac{\partial E}{\partial t} + \vec \nabla\times \vec B
\end{eqnarray}
gives us the proper expression for the Ampère law, with the current $\dfrac{e\mu_0}{m} \bar \psi \gamma^j \psi$. We can decompose this expression using the Gordon decomposition :
$$J^\mu = -\frac{e\hbar}{m^2} \left[ \frac i2 (\frac{\partial \bar \psi }{\partial x^\nu}\psi - \bar \psi \frac{\partial \psi }{\partial x^\nu}) + \frac{\partial}{\partial x^\nu} (\bar \psi \sigma^{\mu\nu} \psi) \right]  $$
Or, for the spacelike part,
$$\vec J = -\frac{e\hbar}{m^2} \left[ \frac i2 ((\vec \nabla \bar \psi)\psi - \bar \psi \vec\nabla  \psi ) - \frac{\partial}{\partial t} (\bar \psi \sigma^{i0} \psi) + \partial_j (\bar \psi {\sigma}^{ij} \psi) \right]  $$
The first part of the current is simply the current, as is generally accepted (it is the same expression as the current in the Schrodinger equation, for instance). The second part is the time variation of the polarization tensor, while the third part is the derivative of magnetization tensor. The magnetization tensor is the part containing the dependance on spin, which is the source of the magnetic field from the spin. It can be rewritten in a more readable way as
$$\vec J = -\frac{e\hbar}{m^2} \left[ \vec{j}_{\text{free}} - \frac{\partial}{\partial t} \vec{P} + \vec{\nabla} \times \vec{M} \right]  $$
Of course, it is still wrong to say that the magnetic field stems only from currents. There are at least two cases where this is not the case : sourceless electromagnetic waves and, if the underlying spacetime isn't simply connected, it is possible to have EM fields stemming from the geometry of the spacetime directly (this was the basis of geometrodynamics).


text:
Q: Objective-C:  @class Directive before @interface? What is the difference between these two class declarations?  I don't understand why @class is utilized here.  Thanks.
@class TestClass;

@interface TestClass: UIView {
    UIImage *image1;
    UIImage *image2;
}

and
@interface TestClass: UIView {
    UIImage *image1;
    UIImage *image2;
}

A: As per Matt's answer there's absolutely no point to the @class declaration in your code. @class forward defines a class so that the compiler subsequently knows what general sort of unit you are referring to. Since Objective-C is pretty much typeless at runtime, that's often all that the compiler actually needs to know — just enough to distinguish the thing from an atomic C value.
I'm going to take a stab in the dark and say that because the instance variables are declared in the @interface you're looking at some old code. Because it's old code, the @class probably used to be somewhere else (eg, there was a delegate protocol declared in between) and has just ended up harmlessly stranded.

A: @class is pretty handy when you need to define a protocol for an object that will usually interact with the object whose interface you are also defining. Using @class, you can keep the protocol definition in header of your class. This pattern of delegation is often used on Objective-C, and is often preferable to defining both "MyClass.h" and "MyClassDelegate.h". That can cause some confusing import problems
@class MyClass;

@protocol MyClassDelegate<NSObject>

- (void)myClassDidSomething:(MyClass *)myClass
- (void)myClass:(MyClass *)myClass didSomethingWithResponse:(NSObject *)reponse
- (BOOL)shouldMyClassDoSomething:(MyClass *)myClass;
- (BOOL)shouldMyClass:(MyClass *)myClass doSomethingWithInput:(NSObject *)input

@end

// MyClass hasn't been defined yet, but MyClassDelegate will still compile even tho
// params mention MyClass, because of the @class declaration.
// You're telling the compiler "it's coming. don't worry".
// You can't send MyClass any messages (you can't send messages in a protocol declaration anyway),
// but it's important to note that @class only lets you reference the yet-to-be-defined class. That's all.
// The compiler doesn't know anything about MyClass other than its definition is coming eventually.

@interface MyClass : NSObject

@property (nonatomic, assign) id<MyClassDelegate> delegate;

- (void)doSomething;
- (void)doSomethingWithInput:(NSObject *)input

@end

Then, when you are using the class, you can both create instances of the class as well as implement the protocol with a single import statement
#import "MyClass.h"

@interface MyOtherClass()<MyClassDelegate>

@property (nonatomic, strong) MyClass *myClass;

@end

@implementation MyOtherClass

#pragma mark - MyClassDelegate Protocol Methods

- (void)myClassDidSomething:(MyClass *)myClass {

    NSLog(@"My Class Did Something!")

}

- (void)myClassDidSomethingWithResponse:(NSObject *)response {

    NSLog(@"My Class Did Something With %@", response);

}

- (BOOL)shouldMyClassDoSomething {

    return YES;

- (BOOL)shouldMyClassDoSomethingWithInput:(NSObject *)input {

    if ([input isEqual:@YES]) {

        return YES;

    }

    return NO;

}

- (void)doSomething {

    self.myClass = [[MyClass alloc] init];
    self.myClass.delegate = self;
    [self.myClass doSomething];
    [self.myClass doSomethingWithInput:@0];

}

A: @class exists to break circular dependencies.   Say you have classes A and B.
@interface A:NSObject
- (B*)calculateMyBNess;
@end

@interface B:NSObject
- (A*)calculateMyANess;
@end

Chicken;  meet Egg.   This can never compile because A's interface depends on B being defined and vice-versa.
Thus, it can be fixed by using @class:
@class B;
@interface A:NSObject
- (B*)calculateMyBNess;
@end

@interface B:NSObject
- (A*)calculateMyANess;
@end

@class effectively tells the compiler that such a class exists somewhere and, thus, pointers declared to point to instances of said class are perfectly valid.  However, you couldn't call a method on an instance reference whose type is only defined as an @class because there is no additional metadata available to the compiler (I can't remember if it reverts the call site to being evaluated as a call through id or not).
In your example, the @class is harmless, but entirely unnecessary.

A: @class TestClass;

This merely declares "class TestClass will be defined".
In this case (the one you pasted) this has no effect of whatsoever, so these are the same.
However, in case you're going to define a protocol that would use your class name (as type of parameters passed to delegate, for example), you will need to declare @class TestClass before the protocol definition, as your class is still not defined.
In general, if you need to mention your class name before the class definition is made, you will need to issue @class declaration first


text:
Q: Is there a better way to write this answer to this problem? First question ever of probably many more to come.
I have a simple python problem that I solved that I will post below, along with my answer.
I was wondering if there were any more elegant answers, as I feel like this could be solved more eloquently.
Given a string, return a "rotated left 2" version where the first 2 chars are moved to the end. The string length will be at least 2.
left2('Hello') → 'lloHe'
left2('java') → 'vaja'
left2('Hi') → 'Hi'
Here is the code I came up with:
def left2(str):
  first = list(str)
  first.insert(len(first),first.pop(0))
  first.insert(len(first),first.pop(0))
  x = ''.join(first)
  return x

A: You can slice the string and concatenate the slices instead:
def left2(s):
    return s[2:] + s[:2]