text:
Q: How to get JSON Data from multiple url in same thread using loop or any other way I want to get data from different url in same thread. How can i do that.
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultConfigObject];

for(int i=0;i<[url count];i++){
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url[i]];

[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[param dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:urlRequest
                                                   completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                       NSLog(@"Response:%@ %@\n", response, error);
                                                       if(error != nil)
                                                       {
                                                           NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                           NSLog(@"Data = %@",text);
                                                       }
                                                       else{
                                                           // If no error occurs, check the HTTP status code.
                                                           NSInteger HTTPStatusCode = [(NSHTTPURLResponse *)response statusCode];

                                                           // If it's other than 200, then show it on the console.
                                                           if (HTTPStatusCode != 200) {
                                                               NSLog(@"HTTP status code = %d", HTTPStatusCode);
                                                           }

                                                           // Call the completion handler with the returned data on the main thread.
                                                           [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                                                               completionHandler(data);
                                                           }];
                                                       }

                                                   }];
[dataTask resume];
}

i want to get all value ..If i get that than i will save each url value in an array


text:
Q: Refreshing DIV with AngularJS and Rails on backend I use `ng-click' to use AngularJS to delete a post from my database.
%table.table{"ng-controller" => "PostsCtrl"}
  %tr
    %th Title
    %th ....
    %th
  - @posts.each do |post|
    %tr
      %td...
      %td= link_to 'Delete', '', 'ng-click' => "deletePost('#{post.id}')", :id => "post_#{post.id}"

This is in /app/views/posts/index.html.haml.
And the action for it:
 def index
   @posts = Post.all
 end

And now JS:
var app = angular.module('MyApp', ['ngResource']);
app.factory('Posts', function($resource){
 return $resource('/posts.json', {},{
    query: { method: 'GET', isArray: true },
    create: { method: 'POST' }
 })
});

app.factory('Post', function($resource) {
    return $resource("/posts/:id", { id: '@id' }, {
        'destroy': { method: 'DELETE', params: {id: '@id', responseType: 'json'} }
    });
});
app.controller("PostsCtrl", ['$scope', '$http', '$resource', 'Posts', 'Post', '$location', function($scope, $http, $resource, Posts, Post, $location) {

$scope.posts = Posts.query();
$scope.deletePost = function (post_id) {
    if (confirm("Are you sure you want to delete this user?")){
      Post.delete({ id: post_id }, function(){
        $scope.posts = Posts.query();

        $location.path('/');
        $scope.$apply();
      });
    }
  };
}]);

When I hit the link for deleting the post, the record is deleted from the database, but in the JS console is thrown the following error message:
DELETE http://localhost:3001/posts/5620a8766f85ce82ce000002 406 (Not Acceptable)

Here's the Rails action:
  def destroy
    puts "test"
    respond_with @post.destroy!
  end

And routes.rb:
resources :posts do
  resources :comments
end

How to get rid of the error and refresh the table once the record is deleted?
Thank you in advance.
EDIT:
I just found out that if I click the link to delete the respective post, AngularJS sends the request as HTML? Judging from what I see in terminal:
Processing by PostsController#destroy as HTML
...
ActionController::UnknownFormat - ActionController::UnknownFormat:
...

A: As you say the 406 error indicates that your backend cannot respond with the requested format ( here HTML ).
A possible solution is to specify in your request the json format like :
note the .json after the :id
app.factory('Post', function($resource) {
    return $resource("/posts/:id.json", { id: '@id' }, {
        'destroy': { method: 'DELETE', params: {id: '@id', responseType: 'json'} }
    });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: DOM Changes Javascript I was trying to make some DOM changes. When I try to add or update my DOM it is possible thru this small code snippet
$(abc).each(function() {
    if (($(this).attr("id") != "SceneOne")) {
        var txt=$($.parseXML(xml)).find(shashin).children().appendTo(thashin);
        console.log(txt);
    }
});

and for deleting some parts of the DOM structure I use
var targeti = $(this).find("targetid").text();
var el=document.getElementById(targeti);
el.parentNode.removeChild(el);

But then, When I use the code for my server side JS using Node. The add and update functions work perfectly but not the delete funciton.
I tried using this as well from the Jquery library , but that does not work either.
any ideas why?


text:
Q: Websphere Portal 8.5, portlets is changing JSESSIONID I deployd release with some script portlets applications on more managed pages to production as is described here:
http://www-01.ibm.com/support/knowledgecenter/SSHRKX_8.5.0/mp/deploy/dep_deploy.dita?lang=en
Portlets have security restrictions to authentificated users. After I first time logged in its all OK. However when I try to click on another page on that portal I'm redirected to login page again.
I investigated it in web browser console. There were changing JSESSIONID in cookie every GET method:
...sessionCode=-776125765; JSESSIONID=0000f7VRxv0SelqdHKq_cdSkfwr:-1;...
...sessionCode=-776125765; JSESSIONID=0000CgNGvCB89PS5pam1KA4q1jM:-1;...
...sessionCode=-776125765; JSESSIONID=0000LzkNhV2ycEx9irw8ueRJeV6:-1;...

But in source portal it stay the same:
...sessionCode=-776125765; JSESSIONID=0000S9uf4WFCR1-HbNKvK2oRwVp:-1;...
...sessionCode=-776125765; JSESSIONID=0000S9uf4WFCR1-HbNKvK2oRwVp:-1;...
...sessionCode=-776125765; JSESSIONID=0000S9uf4WFCR1-HbNKvK2oRwVp:-1;...

Have someone some ideas how to fix it?

A: Do you have any embedded links to other sites/applications in the same domain ?
May be that application is changing the JSESSIONID cookie - causing the portal app to invalidate.
Usually if we have multiple servers running on the same system or domain - we change the name of the JSESSIONID.


text:
Q: Angular 12 curly braces within braces text interpolation with conditional operator expression Here I'm trying to to use *ngFor="let i of dataL;let k = index | async", now what I'm trying to achieve is in the following code.

    {{ i.id }}
    {{ i.details }}

      Article : {{ i.links.article == null ? "N/A" : Article_{{k+1}} }}

      Reddit : {{ i.links.reddit == null ? "N/A" : reddit_{{k+1}} }}

      Wikipedia : {{ i.links.wikipedia == null ? "N/A" : wikipedia_{{k+1}} }}

Changed from this Article_{{k+1}} to this  Article_{{k+1}} still it shows.
Angular Error
Update 1:
It shows result and I've fixed its position.
Article : {{ i.links.article == null ? "N/A" : Article_1 }}

Now I only require Article : N/A or with URL

A: You have your async pipe being applied in the wrong place. The async pipe is for subscribing to observables (your data) not the index position as you loop through the array.
Edit: in response to my comment below

    {{ i.id }}
    {{ i.details }}

      Article:
      <ng-container
      *ngIf="i.links.article == null">N/A</ng-container>
      <ng-container *ngIf="i.links.article != null">
         Article_{{k+1}}
      </ng-container>


text:
Q: Wrong title for election related notifications I have some strange titles when I get comment notifications for my nomination on [SO] there stands something like "6|rekire" in the title. I guess that comes from the 6 in the URL https://stackoverflow.com/election/6
I'm pretty sure that this does not happen often however this is a small bug :-)
Edit: The "dublicated" question Missing links to responses to comments on nomination posts is about links in the web. I'm talking about the app. So that question is related, but not a dublicate at all.


text:
Q: Why is my CSP header middleware not working? I've written a simple middleware function to add the Content-Security-Policy header to my API routes, I've tried using multiple policies (default-src, img-src, frame-ancestors) pointing to either 'self' or explicitly to "http://localhost:port" but none of these seem to work.
This is my simple middleware:
(defn wrap-content-type-security
  [handler]
  (fn [req]
    (let [resp (handler req)]
      (header resp "Content-Security-Policy" "default-src 'self'"))))

I am able to see the correct header set in my routes:

However I'm still getting the usual favicon.ico route error, I do have a dummy route for /favicon.ico just returning some text and this also returns the CSP header.
There's obviously something I'm missing/doing wrong, any help is appreciated.
Thank you.
Edit: Looking more into this, seems like this is a Firefox related issue? I tried to replicate the issue in Chrome and everything seems to be working fine as the favicon does show in the browser tab.

However in Firefox, still showing the same issue:

Which makes me thing that it's got something to do with that "FaviconLoader.jsm" script? being loaded/shown on the console.

A: It seems that your middleware is working (adding the CSP header) but you don't have a proper csp header value.
Try adding img-src 'self' and see if it helps.
Btw. you can try Content-Security-Policy-Report-Only until you tune your CSP header.


text:
Q: Репликация DNS записей с удаленного сервиса Есть "DNS-провайдер" хостинга в интернете. Там 100 с лишним записей. Подняли windows-dns для внутренних нужд (Win 2016). Есть ли быстрый способ скопировать все записи для определенного домена (а не забивать ручками)?

A: Если вы не можете получить эту информацию от DNS (например, у вас нет прав), то одной из альтернатив является использование Wolfram Alpha.

*

*Введите домен в поле поиска и запустите поиск. Пример: google.com

*В 3-ей секции сверху (под названием "Web statistics for all of google.com") нажмите кнопку "Subdomains"

*В разделе Subdomains нажмите кнопку "More"
Вы сможете увидеть список поддоменов. Внизу есть кнопка Plaintext, с помощью которой этот список можно сохранить. Хотя я подозреваю, что он не показывает всех поддоменов.

A: Выгрузите в файл, а затем на сервере DNS у себя по пути c:\windows\system32\dns отредактируйте файл с новыми записями источник

A: Напишите краулер для веб-интерфейса DNS-провайдера.
Если есть доступ к DNS серверу провайдера, то можно использовать способ передача зоны DNS, но это должно быть разрешено DNS сервером.
Вам необходимо в windows server включить и разрешить передачу зоны для зоны, которую вы хотите перенести. Вы можете настроить это на вкладке «Zone Transfers» на страницах свойств зоны.


text:
Q: URL Encoding - Chinese Charcters When i paste 圆通速递 into a website and check the POST using FIREBUG ,it gave me the following
%D4%B2%CD%A8%CB%D9%B5%DD

申通E物流 is becomeing 鐢抽€欵鐗╂祦 after i URL encode and the website decodes it obviously  urlencode($trackingname); didn't work out well :(
How do i encode my Chinese character to that same format as the website is doing?My chinese character is stored in mysql. I tried decoding using some format but cant return it to that Chinese character pasted.
Any help would be greatly appreciated! Thank you

A: Your website must use UTF-8. In HTML5 that would be (HTML):
<meta charset="UTF-8">

When you connect to your Database, be sure to use (PHP):
$mysqli->set_charset("utf8");

Finally, your table definition that stores Chinese characters must also have UTF-8 collation (SQL):
`column name` TEXT CHARACTER SET utf8


text:
Q: Derivative and Taylor Series In higher dimensions, is the derivative (jacobians,gradients etc.) defined using taylor series or taylor series formula proved through derivatives ?

A: In fact, we'll have to ask Taylor himself.
But I can tell you that Taylor's Series is a Theory, and originally it is based on linear approximation which is one of the derivatives applications, and he developed it to give a general approximation with the same derivatives concept (based on the equation of a straight line $y=mx+c$).
In fact when I first learned it, I was as curious as you, so I kept searching and trying until I could find an Algebraic solution, if you're interested I can add it to the answer.
However, I'm almost sure it's based on the graphical analysis.
I advise you to read the wikipedia artice about it, it's really useful and understandable.
I hope I answered your question :)


text:
Q: React Router Link, onClick Action Not Firing I'm using React Router Dom Link. I'd like to fire an action before I render a new page. The new page's componentDidMount() lifecycle method depends the action firing when a user clicks a username of a post.
code example:
 <Link to={`/Profile/${post.uid}`}
    onClick={(e) => this.handleItemClick(post.uid)}>{post.name}</Link>

handItemClick
handleItemClick = (uid) => {changeUserUidState(uid)}

changeUserUidState is the action creator being dispatched. I am using in line mapStateToProp and mapDispatchToProp like below
export default connect(({posts, userData}) => ({posts, userData}), ({changeUserUidState}))(Feeds);

Action Creator
const changeUid = (uid) => {return uid}
export const changeUserUidState = uid => ({
  type: 'UPDATE_UID', payload: changeUid(uid),
});

My payload should only return the uid, which I can simply return rather than invoking changeUid. But, I'm including this code to say that I can console.log() inside of changeUid once the user clicks on a user name, but my redux tools never fire 'UPDATE_UID' and my store never updates the uid.
How can I invoke an action, but the type of action never fires?
my reducer
import initialState from './initialState';

export default function (userUid = initialState.userUid, action) {
  switch (action.type) {
    case 'UPDATE_UID':
      return action.payload;
    default:
      return userUid;
  }
}

and intialState for userUid is an empty string.

A: It looks like you're just invoking the function without calling dispatch.
What sends the action to the reducer is to call dispatch.  So you'll have to structure what your sending as mapDispatch to props and a function that takes dispatch and returns an object that uses it.  Like this:
const mapDispatch = dispatch => ({
  dispatchChangeUID: (uid) => {
    dispatch(changeUserUidState(uid))
  }
})

export default connect(({posts, userData}) => ({posts, userData}), mapDispatch)(Feeds);

Then you'd call props.dispatchChangeUID in the onClick for the link.


text:
Q: Recovering from a 'corrupt' theme installation on Debian I recently installed a new theme on my Debian Stretch machine, however after rebooting, I am unable to get past the login screen. If I enter the incorrect log in details, the systems tells me that the wrong credentials were provided, however if I enter the correct details, nothing happens for a few seconds, then the screen flashes black then goes back to the login screen.
Theme in question: Flat Remix Gnome
I followed the terminal installation instructions, and everything seemed to be fine until after a reboot.
I can still login view terminal (switching to a terminal session when I hit the login screen), however I do not know how I can remove this theme and get back to the default one, which will hopefully allow me to log in via the gnome login screen.
Any suggestions?
I've looked at how to change theme from terminal however my settings.ini file only very little information in it, and does not contain what the answer suggests.

A: This is a little strange and desperate, but you can remove all of your personal configurations - themes, browser history, e-mails... - if you remove all files that starts with a dot in your home folder:
rm -rf .*

Please, note that DOT
If you want to keep, for example, your browser history, and you uses Firefox, just rename the folder:
mv .mozilla mozilla

And back with the original name when you done.


text:
Q: Initializing UIView init AFTER its superclass init? Looking at the a lecture slide in the Stanford iOS 9 course here, he is creating a new UIView with two initializers (one if the UIView was created from storyboard, and one if it was created in code). The following code is written at the bottom of that particular slide:
    func setup() {....}  //This contains the initialization code for the newly created UIView

    override init(frame: CGRect) {  //Initializer if the UIView was created using code.
        super.init(frame: frame)
        setup()
    }
    required init(coder aDecoder: NSCoder) {  //Initializer if UIView was created in storyboard
        super.init(coder:aDecoder)
        setup()
    }

The rule is that you must initialize ALL of your own properties FIRST before you can grab an init from a superclass. So why is it that in this case he calls his superclass init super.init BEFORE he initializes himself setup()? Doesn't that contradict the following rule:

Safety check 1 A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.
As mentioned above, the memory for an object is only considered fully initialized once the initial state of all of its stored properties is known. In order for this rule to be satisfied, a designated initializer must make sure that all its own properties are initialized before it hands off up the chain.

A: I haven't seen all the rest of the code in this example, but the rule is only that your properties have to be initialized (i.e. the memory they occupy has to be set to some initial value) before calling super.init(), not that you can't run extra setup code.
You can even get away with sort of not-really-initializing your properties by either declaring your properties lazy var, or using var optionals which automatically initialize to nil.  You can then set them after your call to super.init().
For example:
class Foo: UIView {
    var someSubview: UIView!  // initializes automatically to nil

    lazy var initialBackgroundColor: UIColor? = {
        return self.someSubview.backgroundColor
    }()

    init() {
        super.init(frame: .zero)
        setup()          // do some other stuff
    }

    func setup() {
        someSubview = UIView()
        someSubview.backgroundColor = UIColor.whiteColor()
        addSubview(someSubview)
    }
}


text:
Q: How to know that login credential is wrong or right in selenium TestNG ?how to do negative testing? If I trying to login in selenium with multiple credential and it is login successfully. But How I confirmed that those credential are right? or how to do negative testing in selenium? please help!!

A: This you can do in several ways.

*

*Define DataProvider with three inputs (username, password, isValidCreds). As you already know creds are valid or invalid, just pass true for isValidCreds in case of valid else false.

*As we know, in case of invalid attempt, that would be failed login. Define dataProvider with two inputs (username and password). Enter both and click on Login.
Wait for 20-30 seconds using ExplicitWait to get HomePage title or any element loaded specific to home page. If not loaded, treat that username and password combo is invalid..


text:
Q: grok pattern to parse the logs in logstash I'm trying to parse various logs from grok, but it's too difficult, so I'm asking for your help.
I want to analyze url and mapping information in the log, but it doesn't work well because of other logs.
I tried this way but I don't think it was properly parsed.
"\[%{TIMESTAMP_ISO8601:logtime}\]\[%{DATA:thead_id}\]\[%{DATA:level}\]\[%{DATA:method}\]%{SPACE}%{WORD:http}/%{WORD:https}%{SPACE}%{WORD:request}%{SPACE}:%{SPACE}%{WORD:aop}.RequestInfoModel\(url\=%{WORD:url}%{GREEDYDATA:param}"

please help.
log example :
[21-03-17 08:23:57][scheduled-task-1][DEBUG][c.f.a.b.CleanExpiredAccessInfo.cleanExpiredAccessInfo()] [batch] Clear expired accessInfoStore : store_size=0 (CleanExpiredAccessInfo.java:23)

[21-03-16 00:11:49][http-nio-0.0.0.0-8080-exec-10][INFO ][c.f.a.c.a.GuardianAOP.onAroundHandler()] HTTP/HTTPS Request : GuardianAOP.RequestInfoModel(url=/api/v3/me/extra/key, mapping=GET, parameter=AccessToken(userKey=test@mail.com, clientKey=da3ac9db59dfa32002e7fae6849d06, userType=User, accessibleClient={1daec78593214e6b53ce9803ded5916=Manager, da3ac9db59dfa32002e7fae6849d06=User})) (GuardianAOP.java:57)

[21-03-11 16:54:11][http-nio-18080-exec-8][ERROR][c.f.c.biz.v3.UserBiz.getValidMemberInfoVo()] BizException : [rt_code:9999] not found user (UserBiz.java:228)

A: [21-03-16 00:11:49][http-nio-0.0.0.0-8080-exec-10][INFO ][c.f.a.c.a.GuardianAOP.onAroundHandler()] HTTP/HTTPS Request : GuardianAOP.RequestInfoModel(url=/api/v3/me/extra/key, mapping=GET, parameter=AccessToken(userKey=test@mail.com, clientKey=da3ac9db59dfa32002e7fae6849d06, userType=User, accessibleClient={1daec78593214e6b53ce9803ded5916=Manager, da3ac9db59dfa32002e7fae6849d06=User})) (GuardianAOP.java:57)

For the above mentioned log,
\[%{TIMESTAMP_ISO8601:logtime}\]\[%{DATA:thread_id}\]\[%{WORD:level}( )\]\[%{DATA:method}\]%{SPACE}%{WORD:HTTP}/%{WORD:HTTPS}%{SPACE}%{WORD:Request}%{SPACE}:%{SPACE}%{WORD:aop}.RequestInfoModel\(%{GREEDYDATA:api_info}\)%{SPACE}\(%{DATA:file_name}:%{NUMBER:line_number}\)

This works perfectly. If you want to slpit the api_info into more parts, that's upto you and as per your requirements.
Please use this for more debugging.
Now, the other two log samples that you have provided are different.
Either you have to write an extremely generic pattern, or you can write multiple patterns and match with either.
Have a look at the accepted answer on this question. It explains it quite neatly.


text:
Q: Run su -s with arguments I run to run a command using the su -s command to start a process. Since I do not want the root user to own the process.
I try to do this by issuing the command
su -s "$CATALINA_HOME/bin/catalina.sh run" tomcat
which returns su: /opt/apache-tomcat/bin/catalina.sh run: No such file or directory
How can I run the su -s command along with arguments to not generate this error?

A: If you're running su as root, you can use -s to specify a different shell (running as root is necessary here since your tomcat user doesn't have a valid shell), and -c to specify the command to run:
su -s /bin/sh -c "$CATALINA_HOME/bin/catalina.sh run" tomcat

You might find start-stop-daemon useful; it has a whole slew of options to specify the user and group to use, how to start the daemon etc. The tomcat8 initscript used in Debian might provide useful inspiration. Or you could look at writing a systemd unit or whatever is appropriate for your system's init.

A: The -s switch for su command is to change the shell of the specified user. The command you want to run must be preceded by -c switch.
So the command you are looking for is something like this:
su -s /bin/bash -c "$CATALINA_HOME/bin/catalina.sh run" tomcat

A: Your other questions at https://stackoverflow.com/questions/37753783/ and Is there any way to tell if a shell script was killed with signal 9 indicate that what's missing from your question is that you are trying to run Tomcat under upstart.
In such a case:

*

*start-stop-daemon is not appropriate.

*Nor is su.

*Nor are Poor Man's Daemon Supervisor gyrations to do PID file management in shell script.

All of those are attempting to duplicate stuff that upstart does directly.  The use of su is particularly bad, because it isn't a tool for dropping privileges.  It is a tool for adding privileges, in a login session.  It nowadays has involvement under the covers with various login session management subsystems that makes it particularly inappropriate for the (much simpler) task of dropping superuser privileges in a dæmon.  start-stop-daemon is just supererogatory.  And upstart knows the process IDs of its children.
In the upstart job file, use the setuid and (if appropriate) setgid stanzas to drop privileges to an unprivileged user: setuid tomcat
And if you do invoke catalina.sh via sh -c, which isn't really necessary, don't wander into systemd House of Horror territory.  (It's only marginally less horrendous when these sorts of things are done with upstart.)  Do things the daemontools way and have the shell chain to the script, invoking it via the shell's exec command so that upstart sees the dæmon as its direct child process.  (And make sure that upstart knows this with the correct expect stanza, too.)
An explicit shell isn't necessary in the first place, though, because upstart can invoke catalina.sh directly itself, just as systemd and other service management tools can.  You furthermore thus don't have the worry of ensuring that /bin/bash is actually the right interpreter for that script.  exec $CATALINA_HOME/bin/catalina.sh run
Further reading

*

*James Hunt and Clint Byrum (2014).  "setuid".  Upstart Cookbook.

*James Hunt and Clint Byrum (2014).  "setgid".  Upstart Cookbook.

*James Hunt and Clint Byrum (2014).  "console log".  Upstart Cookbook.

*Jonathan de Boyne Pollard (2014).  Don't abuse su for dropping user privileges.  Frequently Given Answers.

*Jonathan de Boyne Pollard (2015). Wrapping Apache Tomcat in many pointless extra layers  The systemd House of Horror.

*Jonathan de Boyne Pollard (2015).  The systemd House of Horror.  Frequently Given Answers.

*https://superuser.com/a/723333/38062

*https://superuser.com/questions/683855/


text:
Q: Difference between `uiop/package:define-package` and `defpackage`? In Common Lisp with ASDF what is the difference between the define-package in uiop/package and the defpackage macro?

A: UIOP's one has more clauses.
https://common-lisp.net/project/asdf/uiop.html#UIOP_002fPACKAGE

define-package supports the following keywords: use, shadow, shadowing-import-from, import-from, export, intern -- as per cl:defpackage.

those are the same ones. But the rest of the docstring introduces more of them: recycle, mix, reexport…
I have used reexport which makes the following easier: you don't want to fully use package A (for example, Alexandria). You want to import a couple symbols (easy, with import-from), and you also want to export them (easy too, with export). But in doing so, you had to write the symbols twice. reexport saves duplication.
I heard some complains that defpackage would fail to reload a package in some situations, and define-package worked fine, but I didn't encounter this situation.
(edit): another difference: let's say you ":use" a package in your defpackage definition. Now you erase that line and you compile the package definition again. Your Lisp gives you a warning, telling that your package "also uses the following packages" and lists the one you removed from the definition. You removed the line, but the package still "uses" what you wanted to remove. You can check with (describe (find-package :my-package)).
Do the same with UIOP's define-package: you don't have warnings and your package doesn't "use" the one you removed from the definition anymore, as expected.


text:
Q: Build ASP Core (ASP 5) Project with Msbuild I am super new in MSBuild and ASP Core and I have problem in configuring MSBuild with ASP Core (ASP 5).
My last error is:

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\DNX\Microsoft.DNX.targets (126): The Dnx Runtime package needs to be installed.

But Dnx is installed.
Main steps that I did with research in web:

*

*Installed latest version of dnvm

*Installed latest version of dnx

*I had added DNX_FEED enviroment variable to windows user variables with https://www.nuget.org/api/v2 value

*I had modified PATH enviroment variable in windows user variables to C:\Users\OAG\.dnx\runtimes\dnx-clr-win-x86.1.0.0-rc1-update1\bin;C:\Program Files (x86)\MSBuild\14.0\Bin;C:\Users\OAG\.dnx\bin
By the way my tfs version is 2013 for msbuild operations.

A: My problem finally solved
First of all thanks for answers guides me to result
I had used Teamcity instead of TFS Msbuild but the same error that dnx does not installed still exists.
Something that was interesting for me was that I had check it in couple of computers and in some of them all things was working correct and in some another error still exists.
In some cases, I had this error but after adding new Agent to build made error resolved.
After all with this link Specify that MSBuild v14 use CoreClr RC1 for build and adding this line of code to Command Line Parameters:

/verbosity:minimal
  /p:RuntimeToolingDirectory="C:\Users\Administrator.dnx\runtimes\dnx-clr-win-x86.1.0.0-rc1-update1"

That error disappeared and the error of package can't be find run dnu restore raised which seems to be easy to resolve, but that was not easy because packages already exists in my dnx folder and in error mentioned that package does not exists (what's happened?).
By help of Microsoft link Build and Deploy your ASP.NET 5 Application to an Azure Web App that Patrick also mentioned on that I had Added a PowerShell level before main build operation and add Prebuild.ps1 file (exists in link) , that solved dnu restore problem and now Command Line Parameters can be empty in main build operation.
But what is going on?
I found that in build operation (in some cases that I don't know) Build agent is making separate area for building and use dnx items of its own, in my case build agent works in this folder

C:\Windows\SysWOW64\config\systemprofile\

That contains its own runtimes and packages, and finally I understood what was happened , dnx runtime is not exist error is cause of runtime version doesn't exists in that area and dnu restore problem is because it's looking in its own area not user dnx packages.
By the way my target OS is windows server 2008 R2

A: Make sure you have update the global.json to point at the newer runtime.
{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-rc1-xxxx",
    "runtime": "coreclr"
  }
}

Here is a similar question:https://github.com/aspnet/Tooling/issues/71
Moreover, below article explains what powershell scripts you need to add and how to configure your build. And check the following steps in the link whether to solve the problem.
Build and Deploy your ASP.NET 5 Application to an Azure Web App

A: For your issue,

*

*Please the DNX version you installed match the version you used in your project. You can check the installed DNX version by "dnvm list" command and change the version by "dnvm use" command.

*When you install or use DNX from DNVM, added -g or -global argument to make sure the DNX can be used by all users.

And when you install dnx from dnvm, DNX bin has been added to user PATH environment variable automatically. So you don't need to add it manually.
Instruction about DNVM: Version Manager


text:
Q: Question about bijections Determine whether or not the following functions from real numbers to real numbers are bijections. If they are
bijections, then find the inverse. If they are not bijections, then explain why not.
I am trying to determine whether some of these function listed below are bijections or not. I understand that the functions are from real to real numbers. Any input on how to go about figuring this out? Thanks!
the two functions are
$f\left(x\right) = 5x$
and
$f\left(x\right) = \left|4x-12\right|$
thanks in advance!

A: You need to ask yourself in each case: Is the function an injection (one-one)? is it a surjection (for every real number $y$, is there an $x$ such that $f(x) = y$?

*

*The answer to both questions for $f(x) = 5x$ is evidently positive -- why?

*Note that in the second case every value of $f$ is positive: how does that impact on the question of surjectivity?

A: f^{-1}\left(x\right)=\frac{x}{5}
For both $x=2$ and $x=4$ there's equal values of function $f\left(x\right)=4$ so there's no inverse function - because then you would have two different values for $f^{-1}\left(4\right)$.

A: $f(x) = 5x$
If you can find $g$ so that $g(f(x))=x$ then $f$ is a bijection. To do this, you express $x$ in terms of $f(x)$.
$f(x) = 5x$
Divide both sides by $5$: $x=\frac{f(x)}{5}$
So $g(x)=\frac{x}{5}$ works which means $f$ is a bijection.

Then there are more complicated cases where you need to prove it is a bijection (or not) but don't have to explicitly give a inverse function. In those base, you use the fact that $f$ is bijective iff it is injective and surjective.
$f(x) = |4x-12|$
If you think about $x\mapsto |4x-12|$, you see that it obviously isn't a bijection since the image is positive for any given number. Therefore, you can just pick any negative number such as $-1$ and say that it doesn't have any antecedent by $f$ so $f$ is not surjective and therefore not bijective.

A: As said in the comments, you have to check injectivity and surjectivity.
For injectivity you must show that for every $x,y\in\mathbb{R}$, if $x\neq y$ then also $f(x)\neq f(y)$, i.e. it maps different values to different values.
For surjectivity you must show that for every $y\in\mathbb{R}$ you can find an $x\in\mathbb{R}$ such that $f(x)=y$, i.e. you can hit everything with $f$.
Let's take $f(x)=5x$. Suppose $x\neq y$. Is it then true that also $f(x)=5x\neq 5y=f(y)$? This answers the injectivity. Furthermore if $y\in\mathbb{R}$ is arbitrary, can you find an $x\in\mathbb{R}$ such that $5x=f(x)=y$. Hint: solve the equation $5x=y$ for $x$. This answers the surjectivity.


text:
Q: Corrupted Lenovo Ideapad 3 15IIL05 Touchpad Driver A few months ago, I used Driver Booster 10 to update my drivers on my Lenovo Ideapad 3 15IIL05 running Windows 11. I didn't make a backup because I did not have the pro version. After I updated my drivers using the program, I immediately noticed that my touch pad was completely unresponsive - even after multiple restarts.
After some research, I decided the best move would be to delete my touchpad driver (I believe it's called HID-Compliant Touch Screen or HID-Compliant Touch Pad) and hope that it was automatically reinstalled when I restarted my laptop again. It was not.
After that, I was stuck without a touchpad driver. I found out that this problem has happened to many people on similar machines through more research, and combed through forum posts like these:

*

*My touchpad drivers are missing in Microsoft Answers -forum

*Lenovo Touchpad Not Working After Driver Booster in Lenovo forum

*Driver booster 9 broke my touchpad in reddit

I tried using Lenovo's official tools:

*

*Automatic driver update

*Lenovo system update 5.07.0131
None of these tools worked. My final hope was to install the driver manually. For my model, the only drivers under the "Mouse, Touchpad, Keyboard and Pen" section are Fn and Function Keys drivers.
I tried both of these anyway, and neither of them worked. My sister also has a Lenovo laptop with the exact same model (my mom bought us both 2 of the same laptop). I used MajorGeeks Double Driver to export the driver from my sister's laptop, then sent the exported driver to my device using a file sharing service and used Double Driver to install it. However, it said the driver failed to install (probably because Double Driver only exported drivers compatible with the machine they were exported from, due to registry keys or something like that).
After that, I gave up. I had no other ideas. About half of the people I found on forums were able to solve the issue by Rolling back the driver within Driver Booster 10. However, I had already deleted the driver and restarted my machine, and it wasn't showing up in Driver Booster 10 after I scanned again. Again, I had not backed it up because I did not have the pro version of Driver Booster 10.
My laptop's warranty is expired, and I have given up. I've been using a mouse for months, and I hate it. It decreases my productivity when doing things such as programming. If someone could help me, it would be amazing!


text:
Q: How can I convert type uintptr to *string? I'm trying to make a conversion from  uintptr to *string that doesn't seem to be working so far. I get the value as uintptr and need to pass it on as a *string.
The value I'm working represents an address in the file directory
here's what I've tried so far:
if x is uintptr
and y is *string
y = string(x)

*

*cannot use string(x) (value of type string) as type *string in assignment

y = *string(x)

*

*cannot indirect string(x) (value of type string)

*y = string(x)

*

*conversion from uintptr to string yields a string of one rune, not a string of digits (did you mean fmt.Sprint(x)?)

A: You must use unsafe.Pointer to turn a uintptr into a Go pointer value.
Example:
import (
    "fmt"
    "unsafe"
)

func main() {
    var s *string
    var p uintptr = 1

    s = (*string)(unsafe.Pointer(p))
    fmt.Println(s)
}

Output:
0x1

Read the documentation of unsafe and particularly unsafe.Pointer to ensure correct usage.

Pointer represents a pointer to an arbitrary type. There are four special operations available for type Pointer that are not available for other types:

*

*A pointer value of any type can be converted to a Pointer.

*A Pointer can be converted to a pointer value of any type.

*A uintptr can be converted to a Pointer.

*A Pointer can be converted to a uintptr.

Pointer therefore allows a program to defeat the type system and read and write arbitrary memory. It should be used with extreme care.
The following patterns involving Pointer are valid. Code not using these patterns is likely to be invalid today or to become invalid in the future. Even the valid patterns below come with important caveats.
[ ... ]


text:
Q: which type does pthread_create need on the third argument this is the right use of pthread_create with no warning:
#include <pthread.h>
#include <stdio.h>
void  *check(void *temp) {
    int* i = (int *)temp;
    printf("%d\n", *i);
}
int main(void) {
    pthread_t check_thread;
    int i = 1;
    pthread_create(&check_thread, NULL, check , (void  *)&i);
    pthread_join(check_thread, NULL);
    return 0;
}

but the following code can also run well, just change void *check to void check:
#include <pthread.h>
#include <stdio.h>
void check(void *temp) {
    int* i = (int *)temp;
    printf("%d\n", *i);
}
int main(void) {
    pthread_t check_thread;
    int i = 1;
    pthread_create(&check_thread, NULL, check, (void  *)&i);
    pthread_join(check_thread, NULL);
    return 0;
}

if i change check to &check, it can also run well
#include <pthread.h>
#include <stdio.h>
void check(void *temp) {
    int* i = (int *)temp;
    printf("%d\n", *i);
}
int main(void) {
    pthread_t check_thread;
    int i = 1;
    pthread_create(&check_thread, NULL, &check, (void  *)&i);
    pthread_join(check_thread, NULL);
    return 0;
}

i see the thrid argument of pthread_create is: void *(*start_routine) (void *)
can someone tell me what does it mean?

A: The deal of the C standard is to write portable code, that could run on any conforming platform. The fact that this runs on your platform without visible errors, does not mean that it would on other platforms. Reasons for failure could e.g be that pthread_join could try to access a hardware register with the return value.

A: It is nothing but a function pointer. Lets break it down.
void *(*start_routine) (void *)
void* -> return type of function
start_routine -> function pointer name
void* -> argument type

the address of the function you pass will be assigned to function pointer start_routine and start_routine will be invoked as new thread from kernel.

A: Per the POSIX standard for pthread_create():

SYNOPSIS
#include <pthread.h>

int pthread_create(pthread_t *restrict thread,
       const pthread_attr_t *restrict attr,
       void *(*start_routine)(void*), void *restrict arg);

That means that the third argument to pthread_create() must be a function pointer of the form void *(*start_routine)(void*).  The function pointer passed must refer to a function
declared and defined as
void *start_routine( void *arg )
{
    void *ptr = ...;

    ...
    return( ptr );
}

Period.  End of discussion.  Full stop.
You are invoking undefined behavior by not passing a function of the type void *(*start_routine) (void *) as the third argument to pthread_create().
Per J.2 Undefined behavior, paragraph 1 of the C standard:

The behavior is undefined in the following circumstances:
...

*

*A pointer is used to call a function whose type is not compatible with the referenced type.

"Works with no observed issue" is covered by "undefined behavior".  "Program crashes" is also covered.


text:
Q: Returning Json Data From Controller to View ASP.NET MVC I am trying as the title says to return a Json message from the Controller to the View after it validates.
I have made a breakpoint, and I know that the code works from Controller side, and that my JavaScript calls with success the ActionResult now. How do I display that message in the View?
There are two buttons, stamp in and stamp out. If the user stamps in twice, it should get a message, same with stamp out. I have two ActionResults who are indentical except some message and string changes.
Controller:
[HttpPost]
    public ActionResult CreateStamp(Stamping stampingmodel)
    {
        var validateMsg = "";
        stampingmodel.Timestamp = DateTime.Now;
        stampingmodel.StampingType = "in";

        if (stampingmodel.User == null || ModelState.IsValid)
        {
            var idValidated = db.Users.Find(model.UserId);

            if (idValidated != null)
            {
                var stamp =
                    db.Stampings.Where(s => s.UserId == stampingmodel.UserId)
                        .OrderByDescending(s => s.Timestamp)
                        .FirstOrDefault();

                if (stamp.StampingType == stampingmodel.StampingType)
                {
                    if (stampingmodel.StampingType == "in")
                    {
                        validateMsg = "Stamped Twice In A Row!";
                    }
                }

                else
                {
                    if (stampingmodel.StampingType == "in")
                    {
                        validateMsg = "Stamped In, Welcome.";
                    }
                }
            }

            db.Stampings.Add(stampingmodel);
            db.SaveChanges();
        }

        return Json(new {Message = validateMsg });

JavaScript:
$(document).ready(function () {

$("#stampInBtn").click(function () {

    var userId = $("#userId").val();

    $.ajax({
        url: "ComeAndGo/CreateStamp",
        type: "POST",
        dataType: "json",
        data: {
            userId: userId,
        }
    });

});

View:
    <input type="text" id="idUser" class="form-control" />
    <br />
    <input type="submit" value="IN" id="stampInBtn" />

I have more code inside the View of course; divs, head, body, title and scripts. But it's perhaps a little irrelevant.
What should I do to successfully show those messages?
Regards.

A: Add a success function to the ajax call
$.ajax({
  url: "ComeAndGo/CreateStamp",
  type: "POST",
  dataType: "json",
  data: { userId: userId },
  success: function(data) {
    // data contains the value returned by the server
    console.log(data);
  }
});

So if the controller returns
return Json("This is a message");

the value of data will be "This is a message". Note the return value can be a complex type or a partial view

A: You are getting the value of $("#userId"), but your input has an id of idUser.
Try making your input:
<input type="text" id="userId" class="form-control" />

Also it would be a good idea to provide your Stamping model structure as it seems that you only pass the user id in your post and nothing else.

A: Change your javascript code as following:
            $(document).ready(function () {

        $("#stampInBtn").click(function () {

        var userId = $("#userId").val();

            $.ajax({
                url: "ComeAndGo/CreateStamp",
                type: "POST",
                dataType: "json",
                data: {
                    userId: userId,
                },
                success: function(data) {
                var objData= jQuery.parseJSON(data);
                alert(objData.Message );
                },
                error: function (request, status, error) {
                    alert(request.responseText);
                }

            });

        });
    });


text:
Q: domain-search value on my clients computer I need help with configure my DNS and DHCP server - I have spent some time searching on google but have not got any informations regarding my problem.
I have an Ubuntu 12.04 server running and use BIND as the DNS server.
In my client Ubuntu 13.10 computer I get my domain in the search value
search example.com

So when I type in something in the address bar in Firefox then I am redirected to example.com instead of google.com for example.
So what information do I need to change in my DNS or DHCP server so that my clients will get google.com as my default search (domain-search) value in resolv.conf ?

A: This is not what search in resolv.conf does.
It specified the DNS servers that your PC will use for DNS lookups, and the search domain used for hostname-only lookups.
Example:
nameserver 192.168.50.11
nameserver 192.168.50.12
search mynet.local

In the above snippet, the servers 192.168.50.11 and 192.168.50.12 will be used for lookups, with the mynet.local domain being appended to requests with no domain (e.g. nslookup myhost).
For a typical network using DNS and DHCP, these values will be contained within your DHCP configuration, and resolv.conf will be populated automatically by your network configuration once your machine obtains a DHCP lease.
To actually do what you want (make Google the default search engine in Firefox), check out this link (though YMMV).


text:
Q: Global transversals of a codimension one foliation EDIT: changes to the question are in bold.

Suppose I have a smooth ($C^1$) codimension one foliation $\mathscr{F} \subset P$, the open subset of $R^n$ consisting of points with all positive components. The leaves of $\mathscr{F}$ are connected and proper and each is the graph of a function $f$ defined on some domain $D$ contained in $Q$, the open subset of $R^{n-1}$ consisting of points with all positive components ($D$ may depend on the leaf). Further, at every point $p \in P$, the normal to the tangent plane of the leaf $L$ passing through $p$, at that point, is non-negative with last coordinate strictly positive. If I now define the diagonal $\Delta \equiv R^n \bigcap \{ x: x_1 = x_2 = \cdots = x_n \} \subset P$ then I know that through every point $t$ of $\Delta$ passes a leaf $L$ (integral surface) of the foliation and, furthermore, $\Delta$ is transversal to $L$ (because of the normal condition).
Can I then conclude that $\Delta$ passes through every leaf of $\mathscr{F}$? If not, does there exist some transversal in the positive direction passing through every leaf? I have researched this question; i.e. the existence of a global transversal for a foliation of this type, every way I know. The paper "Foliations and global inversion" by E. Cabral Bereira seems to suggest (Lemma 4.3) that we can always find a such a curve by "standard means", but I may not be applying that result correctly. But Danny Calegari (Section 1.2 of Chapter 4 of notes on his book) states that there only exists a finite collection of transversals which together pass through every leaf of a foliation, which of course is not what I need.
I would appreciate any ideas you might have for further research.
Edit: After discussion with Sam Nead and some more thought it is also apparent that if we denote by $\delta$ the (orthogonal) projection of $\Delta$ into $Q$ then $\Delta$ does not intersect a leaf $L$ only if the domain of $L$, say $D_L$, does not intersect $\delta$. However, more is necessary as the closure of $D_L$ cannot be contained entirely in $Q \setminus \delta$ as $L$ must separate $P$ into two connected components.

A: Trying to answer the new version of the question.

We claim that, yes, the diagonal $\Delta$ meets all leaves.
Let $R$ be the plane spanned by $(0, 0, 0, \ldots, 0, 1)$ and $(1, 1, 1, \ldots, 1, 1)$. Note that $R$ contains the ray $\Delta$.  Let $\Gamma = R \cap Q$ - that is, $\Gamma$ is the orthogonal projection of $\Delta$ "down" to $Q$.
Suppose that $L$ is a leaf of the given foliation $\mathcal{F} \subset P$.  Let $D$ be the image of the orthogonal projection of $L$ into the hyperplane $Q$.  We are told that the "inverse" of this projection is a continuous map $f \colon D \to L$. Let $x$ be any point of $D$.  Define $R_x$ to be the two-dimensional plane which (1) contains $x$ and (2) is parallel to $R$. Define $D_x = D \cap R_x$ and $L_x = L \cap R_x$.  Finally define $f_x = f|D_x \colon D_x \to L_x$.  It is an exercise to show that $f_x$ is non-strictly monotonically decreasing.  So we have shown the following.
Lemma: If $D$ meets $\Gamma$, then $L$ meets $\Delta$.
[Now things become a bit vague.]
If $D$ has no boundary, then $D = Q$ and we are done.  Suppose that the boundary $\partial D$ is non-empty and "nice" (a smooth codimension-one submanifold of $Q$, properly embedded in $Q$).  Let $y$ be a point of $\partial D$ and let $n_y$ be the unit vector at $y$ which (1) is normal to $\partial D$, (2) is tangent to $Q$, and (3) points into $D$.  Note that the last coordinate of $n_y$ is zero.
Note that $f$ either blows up, or vanishes, at $y$.  I claim that if $f$ blows up at $y$ then all coordinates of $n_y$ (except the last) are positive.  On the other hand, if $f$ vanishes at $y$ then all coordinates of $n_y$ (except the last) are negative.  Thus $\partial D$ has a "convexity property", and so meets $\Gamma$, and we win.

Below we answer a previous version of the question - see the edit history.

Yes, $\Delta$ meets all leaves.  Let $R$ be the plane spanned by $(0, 0, 0, \ldots, 0, 1)$ and $(1, 1, 1, \ldots, 1, 1)$. Note that $R$ contains $\Delta$.  Every leaf meets $R$ and its intersection with $R$ is a graph over $Q \cap R$. By your hypotheses these graphs are (non-strictly) monotonically decreasing.  So by the intermediate value theorem they meet $\Delta$.


text:
Q: How to configure Apache drill within eclipse data source explorer I successfully configured apache drill in squirrel sql client. But would like to use eclipse datasource explorer. It allows me to create connection but when it connects seems to be hung. I use drill 1.6 and eclipse mars. Please help or suggest

A: You can use Drill JDBC driver as any other JDBC driver with Eclipse Datasource Explorer. You can find all other configs in Drill docs.


text:
Q: Как передать значения двумерного массива из теста (Junit) в тестируемый метод Есть метод, который переворачивает массив на 90 градусов.
public int[][] rotate(int[][] array) {
    for (int i = 0; i < array.length / 2; i++) {
        for (int j = 0; j < array.length - 1; j++) {
            int tmp = array[i][j];
            array[i][j] = array[j][array.length - 1 - i];
            array[j][array.length - 1 - i] = array[array.length - 1 - i][array.length - 1 - j];
            array[array.length - 1 - i][array.length - 1 - j] = array[array.length - 1 - j][i];
            array[array.length - 1 - j][i] = tmp;
        }
    }
    return array;

При написании теста ругается на синтаксис
public class RotateArrayTest {
@Test
public void whenRotateTwoRowTwoColArrayThenRotatedArray() {
    RotateArray rotateArray = new RotateArray();
    int[][] resultArray = rotateArray.rotate(new int[][] {1, 2}{3, 4});
    int[][] expectArray = new int[][] {3, 1}{4, 2};
    assertThat(resultArray, is(expectArray));
}

конкретно на строчки
int[][] resultArray = rotateArray.rotate(new int[][] {1, 2}{3, 4});
int[][] expectArray = new int[][] {3, 1}{4, 2};

Хотя, для одномерного массива запись
int[] resultArray = turn.back(new int[] {1, 2, 3, 4, 5});

вполне допустима и правильна.

A: Объявление нужно еще в одни скобки обернуть и запятую между вложенными массивами не забыть:
int[][] resultArray = rotateArray.rotate(new int[][] { {1, 2}, {3, 4} });
int[][] expectArray = new int[][] { {3, 1}, {4, 2} };


text:
Q: Converting JSONObject to JSONArray I'm currently learning some android programming with JAVA. My teacher shared this piece of code which will consume an API, get its JSON file, and convert it to a JSONArray file. Then he will Iterate through that JSONArray and put them into an ArrayList before displaying them onto an activity.
The problem is that the API that I'm consuming returns a JSONObject file instead, and I do not know how to properly convert this to JSONArray.
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {

String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONArray jObj = null;
StringBuilder sbParams;
String paramsString;

public JSONArray makeHttpRequest(String url, String method) {

    sbParams = new StringBuilder();

   if(method.equals("GET")){
        // request method is GET

        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }

        try {
            urlObj = new URL(url);

            conn = (HttpURLConnection) urlObj.openConnection();

            conn.setDoOutput(false);

            conn.setRequestMethod("GET");

            conn.setRequestProperty("AccountKey", "pVU56+0hI26DNLeTzlU/Dw==");
            conn.setRequestProperty("UniqueUserId", "33c07f2f-b4c0-4151-acd3-e0829b303d2c");
            conn.setRequestProperty("accept", "application/json");

            conn.setConnectTimeout(15000);

            conn.connect();

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

    }

    try {
        //Receive the response from the server
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        Log.d("JSON Parser", "result: " + result.toString());

    } catch (IOException e) {
        // e.printStackTrace();
    }

    conn.disconnect();

    // try parse the string to a JSON object
    try {

        jObj = new JSONArray(result.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;
}

}
API URL and its custom headers:
URL: http://datamall2.mytransport.sg/ltaodataservice/TaxiAvailability

headers-
AccountKey: pVU56+0hI26DNLeTzlU/Dw==
UniqueUserId: 33c07f2f-b4c0-4151-acd3-e0829b303d2c
accept: application/json

EDIT2: I use this to get my raw data with custom headers.
http://requestmaker.com/
EDIT: This is the JSON that I get.
{
  "odata.metadata": "http://datamall2.mytransport.sg/ltaodataservice/$metadata#TaxiAvailability",
  "value": [
    {
      "Longitude": 103.84009,
      "Latitude": 1.35989
    },
    {
      "Longitude": 103.84679,
      "Latitude": 1.35544
    },
    {
      "Longitude": 103.76928,
      "Latitude": 1.4419
    }
    ....
    ]
    }

A: Add this in place of jObj = new JSONArray(result.toString());
JSONObject obj = new JSONObject(result.toString());
JSONArray arr = obj.getJSONArray("value");

Now you can use JSONArray arr the way you want.

A: JSONObject Jobj = new JSONObject(result.toString());
JSONArray Jarray = obj.getJSONArray("value");

What you need is Jarray.
And then iterate Jarray to get the objects and values Longitude,Latitude in the objects.


text:
Q: Why eclipse couldn't be launched? It shows error log in configuration I am using eclipse 3.7.2 for developing Android applications ... every thing worked fine until I installed a new update for from help tab and also I installed Subversive plugin for code management.
The error is as following:

I opened the error file that mentioned in the above path but I couldn't guess what the missing file, the file contains something like the following:
     !SESSION 2012-08-14 11:23:27.945 -----------------------------------------------
     eclipse.buildId=M20120208-0800
     java.version=1.6.0_30
     java.vendor=Sun Microsystems Inc.
     BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US
     Framework arguments:  -product org.eclipse.epp.package.java.product
     Command-line arguments:  -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product

      !ENTRY org.eclipse.osgi 2 0 2012-08-14 11:23:28.945
      !MESSAGE One or more bundles are not resolved because the following root constraints are not resolved:
      !SUBENTRY 1 org.eclipse.osgi 2 0 2012-08-14 11:23:28.945
      !MESSAGE Bundle  reference:file:plugins/org.eclipse.ui.navigator.resources_3.4.300.v20110928-1505.jar was  not resolved.
      !SUBENTRY 2 org.eclipse.ui.navigator.resources 2 0 2012-08-14 11:23:28.945
      !MESSAGE Missing required bundle org.eclipse.jface_[3.6.0,4.0.0).
      !SUBENTRY 1 org.eclipse.osgi 2 0 2012-08-14 11:23:28.945
      !MESSAGE Bundle reference:file:plugins/org.eclipse.compare.win32_1.0.200.I20110510-0800.jar was not resolved.
       !SUBENTRY 2 org.eclipse.compare.win32 2 0 2012-08-14 11:23:28.945
       !MESSAGE Missing required bundle org.eclipse.jface_[3.5.0,4.0.0).
          !SUBENTRY 1 org.eclipse.osgi 2 0 2012-08-14 11:23:28.945
       !MESSAGE Bundle reference:file:plugins/org.eclipse.ui.workbench_3.7.1.v20120104-1859.jar was not resolved.
       !SUBENTRY 2 org.eclipse.ui.workbench 2 0 2012-08-14 11:23:28.945
       !MESSAGE Missing required bundle org.eclipse.jface_[3.5.0,4.0.0).
       !SUBENTRY 1 org.eclipse.osgi 2 0 2012-08-14 11:23:28.945
       !MESSAGE Bundle reference:file:plugins/org.eclipse.mylyn.commons.ui_3.7.1.v20120425-0100.jar was not resolved.
        !SUBENTRY 2 org.eclipse.mylyn.commons.ui 2 0 2012-08-14 11:23:28.945
        !MESSAGE Missing required bundle org.eclipse.jface_0.0.0.
        !SUBENTRY 1 org.eclipse.osgi 2 0 2012-08-14 11:23:28.945
        !MESSAGE Bundle reference:file:plugins/org.eclipse.mylyn.commons.notifications_0.9.1.v20120412-0100.jar was not resolved.

          ...etc etc

So does anybody can help with this?
Appreciate your help and thanks in advance.

A: Check the plugin org.eclipse.jface. It seems to be of an older version. The plugins complain because they require version 3.5+, or 3.6+.
You can use Eclipse plugin registry view to examine the plugin or the OSGI console. Check out an answer I did earlier for a similar question for more details on the console.

A: OK if you don't want to reinstall(actually resetup seems more correct) the eclipse then download
org.eclipse.jface.databinding_1.5.0.I20100907-0800.jar
org.eclipse.jface.text_3.7.2.v20111213-1208.jar
org.eclipse.jface_3.7.0.v20110928-1505.jar

and place them in eclipse_installed_directory/plugins/ and enjoy ;)
Let me know if error is still coming


text:
Q: Converting a string to an integer Java I am looking to convert the string to an integer so that I can ask the user for input and then count down accordingly.
Code:
String bottle = "bottles";
String num = "";
request.getParameter(bottles);
int number = bottles;

A: I would use Integer.parseInt and enclose in a try / catch for a NumberFormatException (input String does not represent an integer).
I'd also add a null check in case you have no control over the String you're parsing.
// null check
if (bottles != null) {
    try {
        int foo = Integer.parseInt(bottles);
    }
    catch (NumberFormatException nfe) {
        // bottles does not represent an integer
        nfe.printStackTrace();
    }
}

A: You can use Integer.valueOf like so,
String bottles = request.getParameter("bottles"); // Get the parameter as a String

int number = Integer.valueOf(bottles); // Returns Integer type, and un-boxes.

or, you can use Integer.parseInt like so,
int number = Integer.parseInt(bottles); // Returns primitive type.

Both of the options to get the int value may throw a NumberFormatException, so you need a to either add that to the throws signature of your method or use a try catch block.


text:
Q: The progress bar cannot be dragged forward to skip ahead I am using video.js as a video player, loading videos from Django static files. It can play the video, but when I try to skip ahead, it starts the video from 0 seconds.The values of videoP1 - videoP4 are retrieved from the database and have values of 1 and 0. It seems that when you test playing the video on iPhone and iPad, it can be played forward, but it cannot be played forward on Windows and Android devices.

var videos = [
  {
    id: 1,
    name: "1",
    src: "{% static '/frontend/video/t1_1.mp4' %}",
    videoP1: {{ video_db.videoP1 }},

  },
  {
    id: 2,
    name: "2",
    src: "{% static 'frontend/video/t2_1.mp4' %}",
    videoP2:  {{ video_db.videoP2 }},
  },
  {
    id: 3,
    name: "3",
    src: "{% static 'frontend/video/t3_1.mp4' %}",
    videoP3:  {{ video_db.videoP3 }},
  },
  {
    id: 4,
    name: "4",
    src: "{% static 'frontend/video/3_2.mp4' %}",
    videoP4:  {{ video_db.videoP4 }},
  }
  ]
  var player = videojs("videoP");

function light(Cvideo) {
    for (let i = 0; i < videos.length; i++) {

        let video = videos[i];
        if (videos[i].id === Cvideo) {

            document.getElementById("nameV").innerHTML = videos[i].name;
            player.src({ type: "video/mp4", src: videos[i].src });

            player.load();
            console.log(videos[i].id);

            if (!video["videoP" + (i + 1)]) {

                player.controlBar.progressControl.hide();
                console.log(video["videoP" + (i + 1)]);

                player.on("timeupdate", function() {
                    if(player.currentSrc() !== videos[i].src) {
                        return;
                    }

                    var percentage = (player.currentTime() / player.duration()) * 100;

                    document.getElementById("percentage").innerHTML = Math.round(percentage) + "%";
                    if (percentage === 100) {
                        video["videoP" + (i + 1)] = 1;
                        var videopro = video["videoP" + (i + 1)] = 1;
                        var u_id = {{video_db.u_id}};
                        console.log(u_id);
                        $.ajax({
                            type: "POST",
                            url: "/update-video-progress/",
                            data: {
                                video_id: videos[i].id,
                                videopro: u_id,
                            },
                            success: function(response) {
                                console.log("Video progress updated");
                            },
                            error: function(xhr, textStatus, errorThrown) {
                                console.error("Failed to update video progress");
                            },
                        });

                        return;
                    }
                });
            }

            player.on("ended", function() {
                var nextVideo = videos[i+1];
                if (nextVideo) {
                    light(nextVideo.id);
                }
            });
        }
    }

}
<video id="videoP" class=" video-js vjs-fluid" controls data-setup='{}' preload="auto">
  <source src="{% static '/frontend/video/0_0.mp4' %}" type="video/mp4">
</video>

1

2

3

 4

This code defines a variable called "videos" which contains an array of objects. Each object in the array represents a video and contains properties such as an ID, name, source URL, and the user's progress for the video.
The code also initializes a video player using Video.js and sets it to the HTML element with ID "videoP".
The function "light" is defined which takes in a video ID as a parameter. The function iterates through the "videos" array to find the video with the matching ID. Once the video is found, the function updates the video player with the new video source, sets the name of the video, and loads the video.
If the user has not made any progress in the video (as indicated by the "videoP1", "videoP2", etc. properties), the progress bar is hidden and a time update listener is added to the player. When the video is finished, the progress is updated in the database via an AJAX POST request.
The code also contains HTML elements which are used to display the video player and links to switch between different videos. When a link is clicked, the "light" function is called with the corresponding video ID.


text:
Q: Plotting multiple dataframes in one chart In the following code, in each iteration a dataframe is read from a dictionary and is plotted. My intention is see all plots in one chart, but I see multiple charts in separate windows.
def plot(my_dict):
    for key in my_dict:
        df = my_dict[key]
        df.plot.line(x='c', y='i')
    plt.show()

I see some tutorials about that, e.g. here, but it seems that they work when I want to call df.plot() with different columns. Here in my code, I am plotting different dataframes. Any idea on how to fix the code?
P.S: I am running the command from Linux terminal.

A: Consider concatenating all data together to plot data frame once. Specifically, horizontally merge with pandas.concat on the c (i.e., shared x-axis variable), renaming i (i.e., y-axis and legend series) for each dict key, and then call DataFrame.plot only once:
def plot(my_dict):
    graph_df = pd.concat(
        [
            df[['c', 'i']].rename({'i': k}, axis=1).set_index('c')
            for k, df in my_dict.items()
        ],
        axis=1
     )

    graph_df.plot(kind="line")

    plt.show()

A: Pandas uses matplotlib.pyplot as its default backend to create plots. Therefore, one possible solution would be to use matplotlib.pyplot.plot directly. Here's a possible implementation:
from __future__ import annotations
import matplotlib.pyplot as plt

def plot(
    my_dict: dict,
    xcol: str,
    ycol: str,
    grid: bool = True,
    labels: bool | tuple | list = True,
    figsize: tuple | None = None,
    legend: bool | list | tuple | None = True,
    title: str | bool | None = True,
):
    """Plot a dictionary of dataframes.

    Parameters
    ----------
    my_dict : dict
        Dictionary of dataframes.
    xcol : str
        Name of the column to use as x-axis.
    ycol : str
        Name of the column to use as y-axis.
    grid : bool, default=True
        If True, show grid.
    labels : bool | tuple | list, default=True
        If True, use xcol and ycol as labels each axis labels.
        If tuple or list, use `labels[0]` as x-label and `labels[1]` as y-label.
    figsize : tuple | None, optional
        Size of the figure. First value from tuple represents the
        width, and second value the height of the plot. Defaults to (10, 10)
    legend : bool | list | tuple | None, optional
        If True, use keys of `my_dict` as legend.
        If list or tuple, use list or tuple as legend.
    title : str | bool | None, optional
        If True, use `xcol` and `ycol` as title.
        If you specify a string, use the specified value instead.
        Set it to None, or False if you don't want to display the
        plot's title.
    """
    if figsize is None:
        figsize = (10, 10)

    plt.figure(figsize=figsize)
    plt.plot(*[[_df[xcol], _df[ycol]] for _df in my_dict.values()])

    if legend == True:
        plt.legend(my_dict.keys())
    elif isinstance(legend, (list, tuple)):
        plt.legend(legend)

    if grid:
        plt.grid(True)

    if labels == True:
        plt.xlabel(xcol, fontsize=16)
        plt.ylabel(ycol, fontsize=16)
    elif isinstance(labels, (list, tuple)):
        plt.xlabel(labels[0], fontsize=16)
        plt.ylabel(labels[1], fontsize=16)

    if title == True:
        plt.title(f'${xcol} \\times {ycol}$', fontsize=20)
    elif isinstance(title, str):
        plt.title(title, fontsize=20)

    min_x = min(_df['c'].min() for _df in my_dict.values())
    min_y = min(_df['i'].min() for _df in my_dict.values())
    max_x = max(_df['c'].max() for _df in my_dict.values())
    max_y = max(_df['i'].max() for _df in my_dict.values())

    plt.xlim(min_x, max_x * 1.01)
    plt.ylim(min_y, max_y * 1.01)
    plt.show()

Example

import numpy as np
import pandas as pd

d = {
    char: pd.DataFrame(
        {"c": np.random.randint(0, 100, 20), "i": np.random.randint(0, 100, 20)}
    )
    for char in "abcdef"
}

plot(d, 'c', 'i')

Output:

Simplified Version
If you want a stripped down version of the plot function, you could write it like so:
def plot2(my_dict: dict):
    """Plot a dictionary of dataframes.

    Parameters
    ----------
    my_dict : dict
        Dictionary of dataframes.
    """
    plt.plot(*[[_df['c'], _df['i']] for _df in my_dict.values()])
    plt.show()

Example

import numpy as np
import pandas as pd

d = {
    char: pd.DataFrame(
        {"c": np.random.randint(0, 100, 20), "i": np.random.randint(0, 100, 20)}
    )
    for char in "abcdef"
}

plot2(d, 'c', 'i')

Output:

A: According to these docs you can pass an matplotlib axes object to df.plot.line() (which passes it to df.plot(). I think something like this might work:
def plot(my_dict, axes_obj):
    for key in my_dict:
        df = my_dict[key]
        df.plot.line(x='c', y='i', ax=axes_obj)
    plt.show()

There are several ways to obtain an axes object, for example:
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)

or to get the current axes:
plt.gca()


text:
Q: How can I generate an NSDate object that represents the current time in UTC? I'm new to iOS and I'm trying to understand how to use dates and formatters to create a date object that represents the current time, but in the UTC time zone. That is, if my local time on my device is 3pm PST, I want to create a date object that represents the time 3pm UTC. I do NOT want to convert 3pm PST to the UTC equivalent, but instead create the 3pm UTC date using the 3pm PST local time date. My current code is...
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
[dateFormatter setTimeZone:utcTimeZone];
NSString *nowInUTCString = [dateFormatter stringFromDate:[NSDate date]];

...but this essentially converts my local time to UTC time, which is what I do NOT want. I'm still reading up on the docs, but I thought I'd post this in the meantime. Any help?
Thanks so much in advance for your wisdom!

A: You should let the system do all the date math for you. Doing date math yourself may lead to bugs.
We can use NSCalendar to convert dates to date components and back. NSDateComponents has a timezone property that we can set. We'll get back the date that represents it's timezone and components.
// grab the current calendar and date
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];

// create UTC date components
NSDateComponents *utcComponents = [cal components: NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit fromDate: now];
utcComponents.timeZone = [NSTimeZone timeZoneWithName: @"UTC"];

// get the UTC date
NSDate *utcDate = [cal dateFromComponents: utcComponents];

I'm in Pacific time and got the following printout.
NSLog(@"%@", utcDate); // 2013-08-29 12:09:52 +0000 (my time converted to UTC)
NSLog(@"%@", now);     // 2013-08-29 19:09:52 +0000 (right now in UTC)


text:
Q: Moment.js + TypeScript. Cannot find name moment I develope web application with knockout in VisualStudio. I just installed knockout via bower, included d.ts file in project, included script to html page and now i can get access to ko.
Now i try to use moment.js. Like with knockout: install, include d.ts, include script to page and i get an error cannot find name 'moment'. Adding reference to d.ts does not help, import * as moment from 'moment' get an error can not find module moment.
I know that it's a stupid problem, but i can't fix it. What am i doing wrong?

A: I had the same error today.
The fix was to downgrade the "moment" package from "2.25.0" to "2.22.1" in package.json
My application is an angular 8 version and "typescript": "3.5.3

A: This seems to solve the problem for me (the other solutions in this thread didn't work):
import * as moment from 'moment/moment.js';
I still seem to be getting the correct typescript definitions even referencing the js file directly. I suspect the reason is that the 'moment' folder under node_modules does not have an index.js file but I'm not a typescript typings/compiler expert.

A: For me, error comes from moment version 2.25.0.
A workaround for the moment is to downgrade to 2.24.0.
In moment@2.25.0 - package.json :
"typesVersions": {
    ">=3.1": {
      "*": [
        "ts3.1-typings/*"
      ]
    }
  }

But folder 'ts3.1-typings' does not exist. If your typescript version is 3.1 or higher you'll have error :
Cannot find module 'moment'

Github issue : https://github.com/moment/moment/issues/5486

A: Try adding the below code, it worked for me
import * as MomentD from "node_modules/moment/moment.d";

A: What I'd recommend is using some tool for managing your definitions. Some popular options (you don't need both, just pick one):

*

*tsd - npm i -g tsd

*typings - npm i -g typings
These work in a similar fashion as package managers. You can install your definitions like npm/bower installs your dependencies.
Once you have one of these installed, go to your project and install moment + its definition
npm install moment --save

And one of these:
tsd install moment --save
typings install moment --save --ambient

Both of these will create a folder with your definitions in it (both call it typings), and both have an "umbrella" definition file in it, which you should reference in the entry point of your application (first is for tsd, second for typings):
/// <reference path="typings/tsd.d.ts" />
/// <reference path="typings/index.d.ts" />

After this is done, you can use moment (or any other module) as you would:
import * as moment from 'moment'
moment.isDate("I'm not a date")

I suggest checking out these:
https://github.com/DefinitelyTyped/tsd
https://github.com/typings/typings

A: In my case, finally get this error solved by doing the following:

*

*Adding this option "allowSyntheticDefaultImports": true, in the compilerOptions section of the tsconfig.json file (EDITED: As the moment doc. sais in the Note: If you have trouble importing moment, try add "allowSyntheticDefaultImports": true in compilerOptions in your tsconfig.json file.)

*Also add "moduleResolution": "node" in the same compilerOptions section. (Found this option looking around the web)

*Importing moment module like this import * as moment from 'moment';

A: In angular you can do:
declare const moment: any;

after imports.

A: I have fixed it to add "allowSyntheticDefaultImports": true property in tsconfig.app.json file and remove "angularCompilerOptions": { "enableIvy": false}. also set below dependecy in package.json "moment": "^2.28.0", "ngx-daterangepicker-material": "4.0.1", "tslib": "^2.0.0",

A: Declare below in the typings.d.ts file which needs to be created at the root level of the project.
declare module 'moment' {
    const moment: any;
    export = moment
}


text:
Q: FireStore draws Charts overlapping display I want to draw a chart, fill the chart with data from firestore, but it overlaps as shown in the picture
I use the library https://github.com/danielgindi/Charts to create charts, using swift.. Sorry for the unclear description

What I want is to populate the Charts in chronological order, this is my FireStore

I am just new at this so if anyone can help me with this it would be great.
func LiveChart() {
        db.collection("Admin").document("AiSmartRobot").collection("AiDailyProfit").addSnapshotListener({ [self] (querySnapShot, error) in

            for document in querySnapShot!.documents{

                if let quantity = document.data()["quantity"] as? Double{
                    if let datetime = document.data()["date"] as? String{

                        let barChartView = BarChartView(frame: live.bounds)
                        barChartView.delegate = self
                        barChartView.xAxis.labelPosition = .bottom

                        let xValues = [datetime]
                        barChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: xValues)
                        self.live.addSubview(barChartView)
                        var values = [BarChartDataEntry]()
                        let numbers : [Double] = [quantity]
                        for i in 0..<numbers.count {
                            let value = BarChartDataEntry(x: Double(i), y: numbers[i])
                            values.append(value)
                        }
                        let ds = BarChartDataSet(values: values, label: "")
                        let data = BarChartData(dataSets: [ds])
                        ds.valueColors = [UIColor(red: 57.0/255.0, green: 176.0/255.0, blue: 158.0/255.0, alpha: 1)]
                        barChartView.data = data
                        barChartView.chartDescription?.text = ""
                        barChartView.animate(yAxisDuration: 2)
                        barChartView.notifyDataSetChanged()

                    }

                }

            }
        })
    }
}


text:
Q: 2013 - Powershell Enable columns I'm creating sites, subsites and lists via PS. And I need to "enable" the version/size columns, in lists I created.
I don't want to create them because they already exist. In graphical mode, I just have to check the column's box I want, then the column appear in lists.
But in PS, I can't find a way to do it.
I find things like this : (sources)
  $myCustomList = $myTestWeb.Lists[$ListName]

    #Add columns

    $spFieldType = [Microsoft.SharePoint.SPFieldType]::Text

    $myCustomList.Fields.Add("TextField",$spFieldType,$false)

But it does not work. If someone can rescue me :)
Thanks in advance,
Nico.
P.S : I apologize for my bad english :(


text:
Q: Windows Live Contacts API Error on Getting E-Mail hashes - JavaScript The following codes for the Window Live Contacts API to Get all email address from. Its works fine in login, log-out, and other authentications. I can collect all user information of logged in user with Get Data function call, but am getting email hashes of users, rest of the email hashes are blank. I have 10 email address in my contact book.
How do i get the email addresses of my contacts using this api?

    signUserIn

    signUserOut

    Check User Status

    Get Data

    <textarea rows="10" cols="100" id="lists"></textarea>

A: I had the same problem and I find the solution, all you need to do is add the following scope to your list of scopes you're requesting: "wl.contacts_emails"
WL.login({scopes: ["wl.contacts_emails"]});

After did that, I had to remove my application from my profile to reset all scope and add a second time my application. (But if you don't want to ask all people who alerady use your apps, I can just reset secret token to force user to add again your app).

A: Microsoft does not allow you to get your contacts emails via API. They only issue email hashes used to match emails on your end.
Sorry to break it to you, but you are out of luck.
I have spent 5 days now trying to get Hotmail contacts and I can't figure it out.


text:
Q: Thousands grouping in python on MacOS The following 4 lines of code work as expected on Windows and Linux, but don't seem to work on MacOS (Python 3.8.9):
>>> import locale
>>> language_code, encoding = locale.getdefaultlocale()
>>> locale.setlocale(locale.LC_NUMERIC, (language_code, encoding))
'en_US.UTF-8'
>>> locale.format_string("%.8f", 100000000.1, grouping=True)
'100,000,000.09999999'

On MacOS, the grouping=True parameter seems to be ignored, even when the default locale is well defined. The string is formatted like this: 100000000.09999999
I tried it on various machines, and the problem was confirmed by all of my MacOS users.
Is there a way to print a number with thousands separator on MacOS?


text:
Q: UTF-8 Unicode Error in Latex Document I was wondering if someone can help me with that latex error.
Package inputenc Error: Unicode char \u8:̈ not set up for use with LaTeX.
The Latex compiler can't compile and stops at a line, with an umlaut.
Thank you.

A: I figured out what the error was.
The problem was that I just copied some pdf text into the Latex document. Luckily the compiler told me, where exactly the problem was. As I mentioned above it's an umlaut. So I just retyped it and that's it.
Hope it helps someone.


text:
Q: How to configure nginx with multiple server Im new with nginx as well as load balancing, rediction etc. I have 2 tornado web servers running on port 8000 and 8001 and 2 geoserver instance running on tomcat7 servelet with ports 8080 and 8081. Can someone teach me in such a way that nginx could listen to port 80 and base_url/tornado will be redirected to the tornado servers and base_url/geoserver will be redirected to the tomcat7 servelet.
Thanks to those who would help me. :)

A: This should be a good lead for you towards the solution:
upstream tornado {
  server 127.0.0.1:8000;
  server 127.0.0.1:8001;
}

upstream geoserver{
  server 127.0.0.1:8080;
  server 127.0.0.1:8081;
}
server {
  server_name _;
  listen 80;
  location = /tornado {
    proxy_pass http://tornado;
  }

  location = /geoserver {
    proxy_pass http://geoserver;
  }
}

Hope it helps!


text:
Q: Is there a link between Elliott-Halberstam and weak Hardy-Littlewood-Goldbach conjectures? Let $\theta$ be such that $EH(\theta)$ holds, where $EH$ stands for Elliott-Halberstam. Can one get an explicit lower bound $\delta_{\theta}$ for the quantity $\delta$ appearing in the weak Hardy-Littlewood-Goldbach stated in https://www.sciencedirect.com/science/article/abs/pii/S0022314X21002031? In particular, would Elliott-Halberstam conjecture imply the weak Hardy-Littlewood-Goldbach conjecture for some $\delta$ close to $1$?
Indeed it is known that the greater $\theta$ is, the smaller the quantity $l_{k}(\theta):=\lim\inf p_{n+k}-p_{n}$ gets.
Define $r_{0}(m)$ as the smallest non negative integer $r$ such that both $m-r$ and $m+r$ are prime and $k_{0}(m):=\pi(m+r_{0}(m))-\pi(m-r_{0}(m))$. I call such an integer $r$ a primality radius of $m$.
Say also that an integer $m$ is $k$-central if $k_{0}(m)=k$ and denote by $\mathbb{N}_{k}$ the set of $k$-central integers.
Then one has $l_{k}(\theta)=2\lim\inf_{m\in\mathbb{N}_{k}}r_{0}(m)$, so the greater $\theta$ is, the smaller $r_{0}$ and very likely the more numerous primality radii of an integer of given magnitude get.


text:
Q: Attach a post type to other one I have 2 custom post types, I want to add a select input in one of custom post type (when I add or edit a post) to select the other custom post type.
I looked at this function : add_meta_box, but I am not sure it's the correct way to do it ? Can I use more simple thing from Wordpress ?


text:
Q: I want to install a new gem to my engineyard development environment for http://rubygems.org/gems/wolcanus-simple_captcha I want to install a new gem i.e http://rubygems.org/gems/wolcanus-simple_captcha to my engineyard development environment.
Is there a simple process how, I can install the same.
I use Mongodb and need to run the mongodb scripts for the above to install.

A: write in your terminal gem 'wolcanus-simple_captcha', '~> 0.1.6'
then bundle install


text:
Q: Conditional rendering comments count React I am trying to show comments count of the post inside my React Component. I managed to show the amount, but some posts have zero comments. In this situation I want to render '0'. Right now my condition looks like this, but I don't understand what to put inside 'i want to show count here' part :(
{this.props.post.comments_count == null ? 'i want to show count here' : '0' }

A: Try:
{ this.props.post.comments_count || 0 }


text:
Q: Scala object and trait having same name In Scala, a class and an object can be companion(same name, same file)
I came across Scala source code, with a file having a trait and object defined in it and both having same name, but object is not extending trait.
Is this style ok?

A: Yes, In both the case trait or object same name object become a companion object you can see below code you can access private members in class and trait both situations
trait
trait Simple {
private def line = "Line"
}

object Simple {
val objTrait = new Simple{}
def lineObj=objTrait.line
}

Simple.lineObj

class
class Simple {
private def line = "Line"
}

object Simple {
val objTrait = new Simple{}
def lineObj=objTrait.line
}

Simple.lineObj

A: A typical use case for object is for methods and fields that you would mark as static in Java, if that helps.
The object doesn't extend the trait / class, it accompanies it, hence the term companion object.


text:
Q: How do i safely remove a secondary mounted root in the fstab file On my computer i have 2 drives, a 128GB SSD and a 1.8TB HDD. I mount the HDD on "/home/___/mountpoints/HDD" but today i found that leads me back to "/"
The "fstab" file contains this
# / was on /dev/sda1 during installation UUID=e20ffb34-68e3-4d48-ba53-5913d8b11d4a   /                          ext4   errors=remount-ro   0 1
# swap was on /dev/sda5 during installation UUID=575c62d0-f74d-4d80-9682-f2a491c4ab38   none                       swap   sw                  0 0  /dev/sdb1                              /home/____/mountpoints/HDD   ext4   users               0 0

Is it safe to remove the second line and remount my HDD there or do i need to do it another way? (if it helps i use debian 11)

A: Your /etc/fstab should look more like this:
# / was on /dev/sda1 during installation
UUID=e20ffb34-68e3-4d48-ba53-5913d8b11d4a   /    ext4   errors=remount-ro   0 1
# swap was on /dev/sda5 during installation
UUID=575c62d0-f74d-4d80-9682-f2a491c4ab38  none  swap   sw                  0 0
/dev/sdb1           /home/____/mountpoints/HDD   ext4   users               0 0

The lines beginning with the # character are comment lines and have no technical effect: your current comment lines were created by the Debian OS installer to describe the system configuration at the time of installation.
You apparently have added the fifth line.
Since on modern systems disks can be hot-plugged, the device names can sometimes vary from one boot to the next. Because of this, the current best practice is to not use device names, but identifiers that are written to the actual disk/partition/filesystem you wish to refer to. Here, the UUID= refers to a filesystem UUID (or an equivalent swap partition UUID).
The comment line says your root filesystem was on /dev/sda1 during installation, but since you say your /home/____/mountpoints/HDD now leads you back to /, the detection order must have changed at some point, and now your root filesystem is at /dev/sdb1. Because of this, the 5th line of your /etc/fstab causes the root filesystem to be mounted a second time to your /home/____/mountpoints/HDD.
You should be able to simply unmount the extra mount of the root filesystem, with e.g.
umount /home/____/mountpoints/HDD

Deleting (or commenting out) the 5th line of your /etc/fstab will also work. However, instead of deleting the line, you might want to use e.g. lsblk -o +UUID to find out the filesystem UUID of your HDD, and change the /dev/sdb1 on that /etc/fstab line to the appropriate UUID=... string instead.


text:
Q: Modifying java array within a JSP input form I am trying to modify a java array within an <input> tag in JSP
String[] userProperties = {"one", "two", "three"};
String[] propValues = new String[userProperties.length];
.
.
.

<% for(int i = 0; i < userProperties.length; i++) { %>
    <tr>
        <td>
            <input type="text" size="30" maxlength="150" name="<%=propValues[i]%>" value="somevalue">
        </td>
    </tr>
<% } %>
.
.
.

I would like for there to be 3 input forms in this example, and for each form, the value entered by the user would be bound to the appropriate position in the propValues array once the submit button is clicked. I am modifying this based on older code that had name set to a local Java variable, and it was successful in being able to modify that variable. Is this not possible with arrays in JSP? I am aware that JSTL has a <c:forEach> tag that makes this simpler, but since I am working with a single file in a fairly aged codebase I want to keep the libraries it has access to consistent. Is this possible using <%> Java code blocks?

A: //length will 3 but initialize with default value null.
 String[] propValues = new String[userProperties.length];

what you are trying to do is you are initializing variable userProperties and try to access array Variable propValues which actually contains null.
name="<%=propValues[i]%>" // set your name as a null.

So, all your three input have same name as a null. better to try this code
<input type="text" size="30" maxlength="150" name="<%=userProperties[i]%>" value="somevalue">

instead of
 <input type="text" size="30" maxlength="150" name="<%=propValues[i]%>" value="somevalue">


text:
Q: Emulate an older version of chrome within the dev tools I need to emulate an older version of chrome. I want to avoid the solution where I have to uninstall the current version and install the desired one each time I need to test my app. I came across this article but it doesn't quite answer my question. Thank you!

A: It's not possible to emulate older versions of Chrome from within DevTools, as is possible in IE. It's not very reliable to emulate them anyway. I've used IE 8 emulator in the past, and on occasion it has provided different results from the version I installed on an XP VM.
In theory, it should be possible to install multiple Chrome instances side-by-side because the installation directory is OS user based. However, I don't think the installations are fully isolated from one another. At least in Windows, the application would likely write to the same registry keys. In OSX, you might be alright, provided you modify the user directory path.
An alternative solution would be trying the portable versions of Chrome that appear over the Internet, usually illegally. Everything is self contained in a directory, but it will likely perform differently from normal installations. Check out PortableApps.
I think the best solution would be to set up some VMs for the different environments and browsers you want to test with. You can manually set up these, using VirtualBox or similar. Many hosted providers will allow you to spin up fresh VMs with automated tasks to install applications and services. You have to pay for these though.

A: If you just need to check what server returns for old browsers (not full emulation), you can set User-Agent in Network Conditions (for now, chrome 67).

A: Just for completeness, here is a link (September 2021) that provides historical snapshots of the 'chromium' browser, sorted per operating system and per 'position'. I needed this when I had to test on an 8-year old version of Chrome(~ium)
https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html

The URL looks legit (googleapis.com) to me, but please check for yourself before downloading. At your own risk.

A: Updated on 21/03/2019
I have found the following link which contains links to previous Google Chrome Versions (32bit, 64bit and Linux).
https://www.slimjet.com/chrome/google-chrome-old-version.php
Old post
Just found out that different versions of Google Chrome can be installed.

*

*You will have to uninstall your existing version.

*Download the package from here - https://www.chromium.org/getting-involved/dev-channel

*Follow the instructions and install.

Hope this helps someone. The downside is you have to uninstall your current version.
Cheers!

A: Today you can run Windows Sandbox to avoid installing malicious programs. (Windows Professional or Enterprise Edition is required).
more info:
Windows Sandbox Doc

A: While I don't have a way to emulate a different version, I did find a way to have a current and an old version installed at the same time. For the 'current' version I installed Chrome Beta. Then I set the regular version of Chrome to the older version I needed.
Google's docs didn't put all the information in one place, so here are the steps for a normal Chrome user in Windows 10:

*

*Download the Google Update policy template (alternatively Chrome Enterprise also contains the files you'll need) and unzip it.

*Copy the .admx and .adml files into %systemroot%/PolicyDefinitions (.admx files go there and .adml in the language subfolder (en-US) as found in the zip you downloaded)

*Open Group Policy editor and the required settings now exist

*In Computer Configuration->Administrative Templates->Google->Google Update->Applications->Google Chrome,

*

*set Rollback to target version to enabled

*set the Target version prefix override to enabled and your desired version
(e.g. 86. for version 86)

*Finally open Chrome, go to Settings->About and let it check for updates. Chrome will automatically download the target version and prompt you to restart.

Do note that this deletes local user profiles and recreates them from remote including redownloading browser extensions, so use with caution. Remember to go back to the normal version of Chrome by unsetting the Group Policy settings and letting Chrome update itself when you're done.


text:
Q: Does the definition of the fundamental group implicitly assume the Axiom of Choice? Okay, I'm a little foggy around the axiom of choice, so help me out here.
The standard way the fundamental group of a connected space $X$ is defined is as follows. You consider the set of all loops based at some point $x$. You define an equivalence relation called homotopy on the elements of this set, and the equivalence relation partitions the set into equivalence classes. Now you impose a group structure on these classes by identifying identity and defining multiplication this way: to multiply to classes $A$ and $B$, you pick out an element $a$ from $A$, and an element $b$ from $B$, and multiply the loops $a$ and $b$ and call the product of $A$ and $B$ as the equivalence class of $ab$
$$A \circ B = [a\cdot b]$$
However, picking out $a$ from $A$ and $b$ from $B$ sounds a lot like the statement of axiom of choice, which talks about picking out representative elements from disjoint sets.
So what's the deal here. I'm getting something wrong about the axiom of choice (very likely) or fundamental groups do require the axiom of choice.
Much obliged for your time and help.

A: This is a known issue, and the way we go around it is in fact by showing that the operation of the group does not depend on the choice of representatives. This allows us to make all sort of computations with only choose two elements, at a time.
And choosing two elements from two non-empty sets is hardly a choice at all. It is simply repeating two instances of "existential instantiation", where we replace an existential quantifier by an object.
The axiom of choice is needed when you have infinitely many choices to make at once. And even this is just a general rule of thumb.

You can find similar definitions when defining the real numbers as equivalence classes of Cauchy sequences, or when defining cardinal arithmetics, or just when you usually define any type of function on a set and show that you can define an equivalence relation that this function can be "pulled" to the quotient set.

A: No, it's not using AC. You're just making two "choices" here - don't need AC for that, just the fact that a nonempty set has an element. You need AC when you need to make infinitely many "choices" "simultaneously".
Formally, AC says this: Say $X$ is a set, $P(X)$ is the power set, $F:S\to P(X)$ and $F(s)\ne\emptyset$ for every $s\in S$. Then there exists $f:S\to X$ such that $f(s)\in F(s)$ for all $s\in S$.
If $S$ is finite you don't need AC, that statement follows from the other axioms of set theory.

EDIT: At least one person has been confused by the connection between the formalisms here and in the OP. To be explicit, if not pedantic:
Suppose $A$ and $B$ are as in the OP. Rats, another notation conflict. Let's say the OP is talking about a topological space $\Omega$. Let $X$ be the set of all loops in $\Omega$ based at $x$. Then $A$ and $B$ are nonempty subsets of $X$.
Define $F:\{0,1\}\to P(X)$ by $F(0)=A$, $F(1)=B$. AC says there exists $f:\{0,1\}\to X$ with $f(j)\in F(j)$, $j=0,1$. But we don't need AC for that, we can say "let $f(0)=a\in A$ and let $f(1)=b\in B$".
Here $S=\{0,1\}$. If $S$ is infinite we can't define $f$ one element at a time, takes too long.