text:
Q: No Scaling/Fixed Output Resolution support? I'm writing a Win32 C++ program to change screen resolution and scaling mode of various machines. I'm running Windows 7 but targetting Windows XP. The program works on my Windows 7 laptop, in terms of enumerating compatible display modes:
if (listModes)
{
    DEVMODE dmPossibleMode = { 0 };
    ZeroMemory(&dmPossibleMode, sizeof(dmPossibleMode));
    dmPossibleMode.dmSize = sizeof(dmPossibleMode);

    cout << "Key: BD = Bit density/Bits per pixel, SM = Scale mode" << endl;
    cout << "+-----+-----------+-------+----+----+" << endl;
    cout << "|  ID |   Dims    | Freq. | BD | SM |" << endl;
    cout << "+-----+-----------+-------+----+----+" << endl;
    for(int iModeNum = 0; EnumDisplaySettings(dd.DeviceName, iModeNum, &dmPossibleMode) != 0; iModeNum++)
    {
        ostringstream resString; resString << dmPossibleMode.dmPelsWidth << "x" << dmPossibleMode.dmPelsHeight;
        ostringstream freqString; freqString << dmPossibleMode.dmDisplayFrequency << "Hz";
        ostringstream bbpString; bbpString << dmPossibleMode.dmBitsPerPel;
        ostringstream scaleString; scaleString << dmPossibleMode.dmDisplayFixedOutput;
        cout << "|" << setw(4) << iModeNum << " ";
        cout << "|" << setw(10) << resString.str() << " ";
        cout << "|" << setw(6) << freqString.str() << " ";
        cout << "|" << setw(3) << bbpString.str() << " ";
        cout << "|" << setw(3) << scaleString.str() << " |" << endl;
    }
    cout << "+-----+-----------+-------+----+----+" << endl;
}

Gives me:
+-----+-----------+-------+----+----+
|  ID |   Dims    | Freq. | BD | SM |
+-----+-----------+-------+----+----+
|   0 |   640x480 |  59Hz |  8 |  0 |
|   1 |   640x480 |  60Hz |  8 |  0 |
|   2 |   640x480 |  60Hz |  8 |  2 |
|   3 |   640x480 |  60Hz |  8 |  1 |
|   4 |   640x480 |  73Hz |  8 |  0 |
|   5 |   640x480 |  75Hz |  8 |  0 |
|   6 |   640x480 |  75Hz |  8 |  2 |
|   7 |   640x480 |  75Hz |  8 |  1 |
|   8 |   640x480 |  59Hz | 16 |  0 |
|   9 |   640x480 |  60Hz | 16 |  0 |
|  10 |   640x480 |  60Hz | 16 |  2 |
[ etc.                              ]

But over on the Windows XP desktops, the output is like:
+-----+-----------+-------+----+----+
|  ID |   Dims    | Freq. | BD | SM |
+-----+-----------+-------+----+----+
|   0 |   640x480 |  59Hz |  8 |  0 |
|   1 |   640x480 |  60Hz |  8 |  0 |
|   2 |   640x480 |  60Hz |  8 |  0 |
|   3 |   640x480 |  60Hz |  8 |  0 |
|   4 |   640x480 |  73Hz |  8 |  0 |
|   5 |   640x480 |  75Hz |  8 |  0 |
|   6 |   640x480 |  75Hz |  8 |  0 |
|   7 |   640x480 |  75Hz |  8 |  0 |
|   8 |   640x480 |  59Hz | 16 |  0 |
|   9 |   640x480 |  60Hz | 16 |  0 |
|  10 |   640x480 |  60Hz | 16 |  0 |
[ etc.                              ]

I.e. scaling mode all says '0'. Can anyone offer some insight as to why this might be? Much appreciated!

A: You forgot to check the dmPossibleMode.dmFields against DM_DISPLAYFIXEDOUTPUT. If that bit is not set, the value you use at dmPossibleMode.dmDisplayFixedOutput has not been initialized, so it is worthless checking it.

If DM_DISPLAYFIXEDOUTPUT is not set, this member must be zero.

from http://msdn.microsoft.com/en-us/library/windows/desktop/dd183565%28v=vs.85%29.aspx
If I remember correctly however these "stretching" values have meaning only on laptop screens, but this might be wrong, don't base on it.


text:
Q: SharePoint Subsite data Import into Power BI How to SharePoint Site Content in Subsite list Data Import into Power BI.
And How  to Insert Many difference Subsite List data insert into Power BI
Example :

A: There's no difference between a SharePoint Site and a Subsite. To import data in PowerQuery you just have to enter the root URL of the subsite instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Hostile" network in the company - please comment on a security setup I have a little specific problem here that I want (need) to solve in a satisfactory way. My company has multiple (IPv4) networks that are controlled by our router sitting in the middle. Typical smaller shop setup. There is now one additional network that has an IP Range OUTSIDE of our control, connected to the internet with another router OUTSIDE of our control. Call it a project network that is part of another companies network and combined via VPN they set up.
This means:

*

*They control the router that is used for this network and

*They can reconfigure things so that they can access the machines in this network.

The network is physically split on our end through some VLAN capable switches as it covers three locations. At one end there is the router the other company controls.
I Need / want to give the machines used in this network access to my company network. In fact, it may be good to make them part of my active directory domain. The people working on those machines are part of my company. BUT - I need to do so without compromising the security of my company network from outside influence.
Any sort of router integration using the externally controlled router is out by this idea
So, my idea is this:

*

*We accept the IPv4 address space and network topology in this network is not under our control.

*We seek alternatives to integrate those machines into our company network.

The 2 concepts I came up with are:

*

*Use some sort of VPN - have the machines log into VPN. Thanks to them using modern windows, this could be transparent DirectAccess. This essentially treats the other IP space not different than any restaurant network a laptop of the company goes in.

*Alternatively - establish IPv6 routing to this ethernet segment. But - and this is a trick - block all IPv6 packets in the switch before they hit the third party controlled router, so that even IF they turn on IPv6 on that thing (not used now, but they could do it) they would get not a single packet. The switch can nicely do that by pulling all IPv6 traffic coming to that port into a separate VLAN (based on ethernet protocol type).

Anyone sees a problem with using he switch to isolate the outer from IPv6? Any security hole? It is sad we have to treat this network as hostile - would be a lot easier - but the support personnel there is of "known dubious quality" and the legal side is clear - we can not fulfill our obligations when we integrate them into our company while they are under a jurisdiction we don't have a say in.

A: This is a situation I've run into often, and I pretty much always do the same thing: IPSec.
Whether it works for you is dependent on whether there's an IPv4 overlap between their network and yours, which you don't say.  But I know you have clue, and if there was this additional hurdle I think you'd've mentioned it, so let's assume for now that there isn't any overlap.
Set up an IPSec tunnel between their core router and yours, using PSK authentication.  Most good routers will speak it, and it's not hard to do.  Once you have a tunnel in place, you can trust the identity of any packets that come down it (note: I'm not saying you can trust the content of the packets, only that you can be sure they really do come from Potentially-Hostile Partner).
So then you can apply access filters to traffic coming out the tunnel, and precisely restrict what hosts on your network they have the capability to access, and on what ports, and from which machine(s) at their end (though that latter restriction is less useful as you have no control over whether devices on their network are maliciously changing ther IP addresses to elevate their access rights to your end).
Linking the networks, rather than having any random trusted client at their end use an individual VPN client, works better in my experience, not least because you'll either end up with a full-time job managing client access tokens - issuing new ones, revoking old ones, grumbling about people copying them or dealing with the fallout of mandating that any token can only be used once - or you'll issue one token that everyone will use, and you'll have lost any control over who's using it and where they're using it from.  It also means that the complexity is in the core, where it's best managed.
I've had some such tunnels, between my networks and those of the PHPs, running for a decade, and they just Do Their Thing.  From time to time someone needs a new machine on their end able to access some new dev box or other resource on our end, and it's a simple change to an interface access list, a one-line fix to my own kit that I can do in seconds, and everything is working.  No client installs.  No endpoint complications at all.
I find the v6 idea fascinating, but I suspect that it'll run onto the rocks when some v4-only client, or something riddled with v6 bugs because it's so untested, comes along and really-really-really-pretty-please needs access to your network resources.


text:
Q: Analog Switch cannot provide 0V output when OFF I'm trying to simulate in LTSPICE the following simple circuit, and I cannot get 0V output when the analog switch is open.
Can anyone please explain why?

A: The datasheet is not clear on this it guarantee's leakage current, but it stops short at 1V. There are no figures that would suggest the leakage decreases or increases, but I suspect that it would increase because the fet's cant turn fully off if the switch voltage and the Vdd voltage are equal.
The leakage below is for 5V to 0V which is a similar situation as 8V.

Source: https://www.analog.com/media/en/technical-documentation/data-sheets/ADG1611_1612_1613.pdf


text:
Q: Spring java based config ResourceLoader I am new to java-based configuration in spring.  I am trying to convert the xml based configuration found here: https://github.com/sps/mustache-spring-view
My problem is the ResourceLoader used by MustacheViewResolver is throwing a null pointer exception.  How can I properly load the resource loader provided by spring into this configuration?
@Configuration
@ComponentScan(basePackageClasses = Application.class, includeFilters = @Filter(Controller.class), useDefaultFilters = false)
class WebMvcConfig extends WebMvcConfigurationSupport {
    @Bean
    public MustacheViewResolver viewResolver() {
        MustacheViewResolver resolver = new MustacheViewResolver();
        resolver.setPrefix("/WEB-INF/views/mustache/");
        resolver.setSuffix("hbs");
        resolver.setCache(true);

        resolver.setTemplateFactory(new MustacheJTemplateFactory());
        return resolver;
    }
}

Exception:
Caused by: java.lang.NullPointerException
    at org.springframework.web.servlet.view.mustache.java.MustacheJTemplateFactory.getReader(MustacheJTemplateFactory.java:71)

And the line from MustacheJTemplateFactory
Resource resource = resourceLoader.getResource(resourceName);

Please Note: I believe this to be a general question about spring java configuration, and not a specific question about the library I am using.  I could be wrong though!

A: Autowire in the Spring resource loader:
@Autowired
ResourceLoader resourceLoader;

Then set it in your viewResolver() function:
MustacheJTemplateFactory factory = new MustacheJTemplateFactory();
factory.setResourceLoader(resourceLoader);
resolver.setTemplateFactory(factory);


text:
Q: Fody.PropertyChanged - Could not inject EventInvoker method I have a ConfigurationViewModel which inherits from BaseViewModel. BaseViewModel is placed in a separate project and has an INotifyPropertyChanged interface implemented. This separate project does not have Fody.PropertyChanged installed.
When I try to build solution I have exception:
Failed to execute weaver C:\Users\Rafal\.nuget\packages\propertychanged.fody\2.6.0\build\..\netclassicweaver\PropertyChanged.Fody.dll
Type:
System.Exception
StackTrace:
   at InnerWeaver.ExecuteWeavers() in C:\projects\fody\FodyIsolated\InnerWeaver.cs:line 186
   at InnerWeaver.Execute() in C:\projects\fody\FodyIsolated\InnerWeaver.cs:line 109
Source:
FodyIsolated
TargetSite:
Void ExecuteWeavers()
Could not inject EventInvoker method on type 'Designer.VVM.ConfigurationViewModel'. It is possible you are inheriting from a base class and have not correctly set 'EventInvokerNames' or you are using a explicit PropertyChanged event and the event field is not visible to this instance. Either correct 'EventInvokerNames' or implement your own EventInvoker on this class. If you want to suppress this place a [DoNotNotifyAttribute] on Designer.VVM.ConfigurationViewModel.
Type:
Fody.WeavingException
StackTrace:
   at ModuleWeaver.InjectMethod(TypeDefinition targetType, InvokerTypes& invokerType)
   at ModuleWeaver.AddOnPropertyChangedMethod(TypeDefinition targetType)
   at ModuleWeaver.FindMethodsForNodes()
   at ModuleWeaver.Execute()
   at InnerWeaver.ExecuteWeavers() in C:\projects\fody\FodyIsolated\InnerWeaver.cs:line 182
Source:
PropertyChanged.Fody
TargetSite:
Mono.Cecil.MethodDefinition InjectMethod(Mono.Cecil.TypeDefinition, InvokerTypes ByRef)

When I move BaseViewModel to the same project as ConfigurationViewModel then everything is ok.
Is it standard behaviour? Is it a bug? Am I doing something wrong? How to use Fody.PropertyChanged having BaseViewModel in a separate project?

A: when the base View Model is in the same project, then the "OnPropertyChanged" method can be injected into that class. When referencing the base View Model from another project, then that project has to have an "OnPropertyChanged" that matches the convention or customise the method name using EventInvokerNames https://github.com/Fody/PropertyChanged/wiki/EventInvokerSelectionInjection
in summary, try adding this to your base view model
public virtual void OnPropertyChanged(string propertyName)
{
    var propertyChanged = PropertyChanged;
    if (propertyChanged != null)
    {
        propertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}


text:
Q: jQuery UI Sortable linked elements I have two columns, each with many rows/divs.  I'm trying to get jQuery UI Sortable to work in a way that if I drag a div in the left column, the associated row/div in the right column will be sorted as well.
For example,

content 1

content 2

content 3

content 1

content 2

content 3

As for the jQuery, right now I have,
function linkedSort() {
  $('.left-column').sortable({
    axis: 'y',
    stop: function(event, ui) {
      $('.left-column .field').each(function(i, field) {
        var fieldName = $(field).attr('id');
        var fieldNumber = fieldName.substr(fieldName.indexOf('_')+1);
        // do something here to place it in the right area
      });
    }
  });
};

If I drag .left-column .field_2 below .field_3, the respective divs in .right-column should rearrange themselves as well.
Thanks!

A: I think this might be what you are looking for:

content 1

content 2

content 3

content 1

content 2

content 3

$('.left-column').sortable({
    axis: 'y',
    stop: function(event, ui) {
        $('.left-column div[name^=field_]').each(function(i, v) {
            $('.right-column').find("[name=" + $(v).attr('name') + "]").appendTo($('.right-column'));
        });
    }
});
$('.right-column').disableSelection();


text:
Q: Cross-domain request in Firefox I am developing an OpenSocial gadget (JavaScript language) for RQM (Rational Quality Manager) that gets information from DWA (Doors Web Access). The gadget is running on RQM (https://:9443/) and I want to make request to the DWA (https://:8443/).
The gadget runs correctly in IE, but when I run in Firefox I get the following error:
> Cross-Origin Request Blocked: The Same Origin Policy disallows reading
> the remote resource at https://<host>:8443/xxxx. (Reason: CORS header
> 'Access-Control-Allow-Origin' missing). <unknown> Cross-Origin Request
> Blocked: The Same Origin Policy disallows reading the remote resource
> at https://<host>:8443/xxxx. (Reason: CORS request failed). <unknown>

What could be the issue and what can I do? Is there anything I can do on the client side?
Thanks in advance!

A: CORS stands for Cross Domain Resource Sharing. Because of the same origin policy you are not allowed to make requests to other URI schemes, port number, hostname etc (https://en.wikipedia.org/wiki/Same-origin_policy). You are trying to make a request to another portnumber. Solutions to this are CORS, JSONP and web sockets. But the best thing you could do is use CORS. For more information you on how to implement is you can look at http://www.html5rocks.com/en/tutorials/cors/ or https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS


text:
Q: Combination of Specific special character causes Error When I am sending a TextEdit data as a JSON with data as a combination of  "; the app fails every time.
In detail if I am entering my username as anything but password as "; the resultant JSON file looks like:-
{"UserName":"qa@1.com","Password":"\";"}

I have searched a lot, what I could understand is the resultant JSON data voilates the syntax which results in throwing Default exception. I tried to get rid of special symbol by using URLEncoder.encode() method. But now the problem is in decoding.
Any help at any step will be very grateful.
Logcat:
I/SW_HttpClient(448): sending post: {"UserName":"qa@1.com","Password":"\";"}
I/SW_HttpClient(448): HTTPResponse received in [2326ms]
I/SW_HttpClient(448): stream returned: <!DOCTYPE html PUBLIC ---- AN HTML PAGE.... A DEFAULT HANDLER>

A: Hi try the following code
String EMPLOYEE_SERVICE_URI = Utils.authenticate+"?UserName="+uid+"&Email="+eid+"&Password="+URLEncoder.encode(pwd,"UTF-8");

A: The JSON you provided in the Question is valid.
The JSON spec requires double quotes in strings to be escaped with a backslash.  Read the syntax graphs here - http://www.json.org/.
If something is throwing an exception while parsing that JSON, then either the parser is buggy or the exception means something else.

I have searched a lot, what I could understand is the resultant JSON data voilates the syntax

Your understanding is incorrect.

I tried to get rid of special symbol by using URLEncoder.encode() method.

That is a mistake, and is only going to make matters worse:

*

*The backslash SHOULD be there.

*The server or whatever that processes the JSON will NOT be expecting random escaping from a completely different standard.

But now the problem is in decoding.

Exactly.

A: Following provided JSON can be parsed through GSON library with below code
private String sampledata = "{\"UserName\":\"qa@1.com\",\"Password\":\"\\\";\"}";

Gson g = new Gson();
g.fromJson(sampledata, sample.class);

public class sample {

    public String UserName;
    public String Password;
}

A: For decoding the text I got the solution with..
 URLDecoder.decode(String, String);


text:
Q: facebook registration birthday mysql returning 0000-00-00 I have 1 problem to fix with my facebook registration plugin for a website.
im trying to insert the birthday into the db, facebook format is dd-mm-yyyy...im getting a result 0000-00-00,
<code>
$sql = "INSERT INTO users(facebook,
                          email,
                          username,
                          country,
                          gender,
                          dob,
                          password,
                          profile,
                          activated,
                          ip)
        VALUES(?, ?, ?, ?, ?, ?, ?, 'images/default_profile.png', 1,  ?

$data = array($fbId, $register['email'],
                     $register['username'],
                     $location,
                     $register['gender'],
                     $register['birthday'],
                     md5($register['password']),
                     $_SERVER['REMOTE_ADDR']
             );

any help would be great, thanks

A: You need to correctly format the date. In one of my previous tutorials, I used something like this (hopefully it's still working):
$fb_birthday = date("Y-m-d" , strtotime($fb_birthday));

A: Yes, for MySQL you have to submit it as a string in 'YYYY-MM-DD' format, if it's not it's treated as in invalid entry and the field gets set to '0000-00-00'  Convert it in php before sending.   If you're sure of the format from Facebook is always  dd-mm-yyyy  I'd just explode the string on the dash separator and rearrange the order of values.
$fbDate =  $register['birthday'];
$dateArray = explode("-", $fbDate);

$newDate = $dateArray[2]."-".$dateArray[1]."-".$dateArray[0];

Then use the $newDate in your data array for the prepared statement.
$data = array($fbId, $register['email'],
                 $register['username'],
                 $location,
                 $register['gender'],
                 $newDate,
                 md5($register['password']),
                 $_SERVER['REMOTE_ADDR']
         );


text:
Q: Google Drive API with PHP - Problems with refresh token getting message 'refresh token must be passed in or set as part of setAccessToken' I'm trying to refresh token on my PHP script but It's not working yet. I'm using Google Drive API with PHP, my script works great in browser until token expires, checking in other sites I changed the code in this way:
index.php
<?php
require_once 'vendor/autoload.php';
if (!file_exists("client_id.json")) exit("Client secret file not found");
$client = new Google_Client();
$client->setAuthConfig('client_id.json');
$client->addScope(Google_Service_Drive::DRIVE);

if (file_exists("credentials.json")) {
$access_token = (file_get_contents("credentials.json"));
$client->setAccessToken($access_token);
//Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
    $refreshTokenSaved = $client->getRefreshToken();
    $client->fetchAccessTokenWithRefreshToken($refreshTokenSaved);
    $accessTokenUpdated = $client->getAccessToken();
    $accessTokenUpdated['refresh_token'] = $refreshTokenSaved;
    file_put_contents("credentials.json", json_encode($accessTokenUpdated));

     //I also tried in this way but it's also not working:
    //$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    //file_put_contents("credentials.json", json_encode($client->getAccessToken()));
}

$drive_service = new Google_Service_Drive($client);
$files_list = $drive_service->files->listFiles(array())->getFiles(); //http://stackoverflow.com/questions/37975479/call-to-undefined-method-google-service-drive-filelistgetitems
echo json_encode($files_list);
} else {
  $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/drive/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>

oauth2callback.php
<?php
require_once 'vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfigFile('client_id.json');
$client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . '/drive/oauth2callback.php');
$client->addScope(Google_Service_Drive::DRIVE); //::DRIVE_METADATA_READONLY
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
 $client->authenticate($_GET['code']);
 $access_token = $client->getAccessToken();
 file_put_contents("credentials.json", json_encode($access_token));

 $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/';
 header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>

But I still receive the message in logs:

PHP Fatal error:  Uncaught exception 'LogicException' with message 'refresh token must be passed in or set as part of setAccessToken' in /var/www/drive/vendor/google/apiclient/src/Google/Client.php:266\nStack trace:\n#0 /var/www/drive/index.php(14): Google_Client->fetchAccessTokenWithRefreshToken(NULL)\n#1 {main}\n  thrown in /var/www/drive/vendor/google/apiclient/src/Google/Client.php on line 266

I have to delete credentials.json and generate a new one executing index.php and being redirected to oauth2callback.php each hour, but that's not the idea.
How can I fix it?
I'd like to receive your help.

A: Finally the token refresh works, I had to add this line $client->setAccessType("offline"); in oauth2callback.php, also delete and generate a new client_id.json to avoid errors.
<?php
 require_once 'vendor/autoload.php';
 $client = new Google_Client();
 $client->setAuthConfigFile('new_client_id.json');
 $client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . '/drive/resp.php');
 $client->addScope(Google_Service_Drive::DRIVE); //::DRIVE_METADATA_READONLY

 $client->setAccessType("offline");

 if (! isset($_GET['code'])) {
   $auth_url = $client->createAuthUrl();
   header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
 } else {
   $client->authenticate($_GET['code']);
   $access_token = $client->getAccessToken();
   file_put_contents("credentials.json", json_encode($access_token));

   $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/drive';
   header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
 }
 ?>


text:
Q: How can gravitational waves be detected when spacetime bends the instruments? Apologies for the naive question, hoping someone with a proper physics background can explain this in layman's terms (as opposed to the more detailed answers at LIGO flawed by the identical expansion of laser wavelength and arms in presence of a gravitational wave?)
If gravitational waves affect spacetime itself, how can we detect changes since the instruments themselves are bent?
For example- I imagine spacetime like a piece of celluloid film. It might be bent or rippled, but inside of the frame everything is still relatively the same- it only looks different from the outside. How is this analogy wrong? i.e. how could a bend in the celluloid be detected from "within" the frame (ok that gets a little weird- like as a character in the movie? but hopefully this demonstrates my confusion on the topic well enough to elicit clarification, hehe)
UPDATE: Seems it has to do with my confusion of lightwaves being a measurement of space rather than a measurement of time. Some helpful links are at http://stuver.blogspot.co.il/2012/09/q-if-light-is-stretchedcompressed-by-gw.html and http://www.americanscientist.org/issues/pub/2004/11/wavy-gravy

A: Because the speed of light does not change.
So if the length between 2 mirors change, the time of flight will change.
In practice this can be mesured at very high precision using interferences between the long-path light and a short-path light.


text:
Q: What is the best way to learn about Modular Forms? I am a senior Mathematics Major, and I am interesting in learning about Modular Forms. I have a layman's general sense of what they are but I was wondering if there is a lecture(I am willing to pay) or a book that explains Modular forms in Layman terms to in mathematical terms. I understand it's not the easiest topic in the world so I was hoping I can have it be explained in Layman's terms and then built from there.  Any advice or suggestions would be greatly appreciated!
Thank you for your time.


text:
Q: how to set delay between each tests in a testng.xml file i'm new to testng.i want to run a test on a parallel execution mode.i'm using
selenium grid,
selenium webdriver,
testng.
my testng.xml file is:
`<?xml version="1.0" encoding="UTF-8"?>
<suite name="WebDriver Suite" verbose="1" parallel="tests" thread-count="5">
<test name="WebDriver Test" >
    <parameter name="browser" value="firefox" />
    <parameter name="port" value="5555" />
<classes>
   <class name="BootUpTest" >
        <methods>
            <include name = "testBootUp"/>
        </methods>
    </class>
</classes>
</test>
<test name="WebDriver Test for IE" >
    <parameter name="browser" value="chrome" />
    <parameter name="port" value="5556" />
<classes>
   <class name="BootUpTest" >
        <methods>
            <include name = "testBootUp"/>
        </methods>
    </class>
</classes>
</test>
</suite>`

in the above xml file i supposed to run the testBootUp method in afirefox as well as chrome.i was able to run the above scenario.but my scope is i want to run the "WebDriver Test  test as first and then i need some delay after that only my WebDriver Test for IE test should have to run..
is it possible to achieve that in the testng.xml file?.

A: You can't do that in testng.xml but why not put a sleep() in one of the before methods? (probably @BeforeMethod)?


text:
Q: How to do url routing in angular js with $urlRouterProvider Can anybody provide a simple angular js page which implements the ui-view and url Routing using  $urlRouterProvider attribute
Regards,
Seshi

A: There is a whole lot of documentation and examples on UI-Router homepage.
https://github.com/angular-ui/ui-router
There is a sample app
http://angular-ui.github.io/ui-router/sample/#/


text:
Q: Odd keyboard behavior I recently started having problems with my system. I am running Ubuntu 22.10 Kinetic with Linux sxkd 5.19.0-26-generic #27-Ubuntu SMP PREEMPT_DYNAMIC Wed Nov 23 20:44:15 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux.
It was working fine for some time [couple of weeks] but a few days ago started giving me grief. The keyboard behaves as if someone is pressing up and down arrows or page up/down or something like that.
Basically,

*

*in any website as I scroll down while reading, it jumps back to the top.

*numpad keys work sometimes and sometimes not - when I press them, the entry [like the text entry box here] blink.

*sometimes none of the keys register in the browser but if I click on a terminal and type, that works.

*Scrolling to the top only happens in browsers, especially firefox. Geany doesn't do that.

*Text entry in firefox also seem to lag quite a lot.

*Problem persists with external keyboard and the built-in laptop keyboard.

*Problem persists with or without external wireless mouse.

*Problem does not happen in Windows.

*Happens with and without external keyboard, with and without USB hub

xev shows the following when I press numpad 4.

*

*FocusOut event, serial 37, synthetic NO, window 0x3000001, mode NotifyNormal, detail NotifyNonlinear

*PropertyNotify event, serial 37, synthetic NO, window 0x3000001, atom 0x173 (_NET_WM_STATE), time 123563870, state PropertyNewValue

*PropertyNotify event, serial 37, synthetic NO, window 0x3000001,atom 0x1ce (_GTK_EDGE_CONSTRAINTS), time 123563870, state PropertyNewValue

I am a longtime Manjaro user who recently switched back to Ubuntu d/t Manjaro refusing to boot after an update. I am not sure what I did wrong here but would love to dig in deeper with guidance.
Any help on where to look will be greatly appreciated.
My suspicion is on the focus from GTK etc. I have been searching the net but the posts I came across are different enough. I tried some of the settings in firefox but then realized the problems are wider than firefox.


text:
Q: AJAX log show success but no data posted to php I used ajax to post html data-attr value but when i post i get following log in console
in console log, i get this result
   success
   posted_ads:201 array(0) {
                     }

As log states AJAX success, so i thought there might be error in php so used var_dump() method to find there are any data passed form request but no dump data.
Any solution why i don't get any data on php.
PHP
<?php
header('Content-type: application/json');
include("$_SERVER[DOCUMENT_ROOT]/include/config.php");
var_dump($_POST);
?>

here is my code
       $(document).ready(function () {
            $('#myModal').on('show.bs.modal', function (e) {
                e.preventDefault();
                const action = $(this).attr('data-act');

                var hash = $(e.relatedTarget).data('hash');
                var para = $(e.relatedTarget).data('para');
                var ref = $(e.relatedTarget).data('ref');
                $.ajax({
                    //data :{action: "showroom"},
                    url: '/include/ajax/dashboard_get_single_card.php', //php page URL where we post this data to view from database
                    type: 'POST',
                    data: {"action": action, "hash": hash, "para": para}, //Pass $id
                    dataType:'text',
                    success: function (data, status) {
                        //window.location.href = data;
                        console.log(status);
                        console.log(data);
                        $("#fetched").html(data);
                    },
                    error: function (xhr, textStatus, error) {
                        $("#fetched").html(xhr.responseText);
                        console.log(xhr.responseText);
                        console.log(xhr.statusText);
                        console.log(textStatus);
                        console.log(error);
                        //window.location.href = '/404.php';
                    }
                });

            });
            return false;
        });

HTML
local_offerMark as sold

can some one explain why am facing this problem, because console log show success but no data is received in php


text:
Q: Using audiere library with C Can I use audiere in C, the man page doesn't mention that afresh.. and the main header file has "vector" included, which is certainly not a standard C lib.

How can I go?

A: You can't ...
Judging by these lines in audiere.h:
#ifndef __cplusplus
  #error Audiere requires C++
#endif

You're supposed to use C++. Its whole API uses C++ anyway.


text:
Q: php кодировка в терминале Windows Есть php обработчик, который выполняет в цикле exec команды вида
exec(icacls "\\\\10.0.7.41\\project\\1111_Проект\\01_Подраздел\\19.09.2018_альбом" /inheritance:e /T, $systemMessage);

Кодировка файла скрипта utf8 без BOM

В цикле перебирается около сотни папок.
Результаты выполнения в помещаю в systemMessage.
Подскажите как правильно работать с кодировкой в которой windows возвращает $systemMessages,
Пример того что я получаю выполняя в командной строке:

А вот что я получаю когда пытаюсь вывести данные на экран в браузере или записать в файл логов
foreach ($systemMessages as $message){
            echo $message;
            file_put_contents($fileName , $message . PHP_EOL, FILE_APPEND);
        }

На экране:

Вроде бы все хорошо, но когда заглядываешь в файл, там:

Что делать с элементом $message в массиве $userMessages, что бы он корректно записался в файл?
Пробовал iconv("windows-1251","utf-8",$message)

не помогает.


text:
Q: Do these Lagrange equations of 1st kind exhibit numerical instabilities? I followed the lead of "Theoretische Physik", 1e, 2015 by Bartelmann et al. (pp. 171 - 174) to form the set of constituting Lagrange equations of the 1st kind for the double pendulum: eight 1st order ODEs of the form
$$ \dot{x} = f(x, \lambda(x)), $$
where $x$ are states, and $\lambda$ are lagrange multipliers.
The defining equations for the lagrange multipliers are
$$
\sum_{i=1}^{2N} \frac{1}{m_i} \frac{\partial f_a}{\partial x_i} \sum_{b=1}^r \lambda_b \frac{\partial f_b}{\partial x_i} = g_a - \sum_{i=1}^{2N}\frac{1}{m_i} \frac{\partial f_a}{\partial x_i} F_i, \; \; a = 1..n
$$
where $n$ is the number of constraints, $N$ is the number of mass points, $f_a$ are the (holonomic) constraints, and $g_a$ are terms obtained from taking the $2^{\text{nd}}$ total time derivative of the constraints:
$$
0 = \ddot{f_a} = \sum_{i=1}^{2N} \frac{\partial f_a}{\partial x_i} \ddot{x_i} - g_a(t, x, \dot{x}).
$$
Dynamics are then computed using
$$
m_i \ddot{x}_i = \sum_{a=1}^{r} \lambda_a \frac{\partial f_a}{\partial x_i} + F_i, \; \; i = 1..2N.
$$
I observed the following:
While the integration of the mass points' ODEs yielded plausible results, the two masses were slightly off the constraints of circular motion about the pivot points which I stated as constraints.
Given my equations are right, could approximation errors in the ODE solver, or the linear equations involving the lagrange multipliers, be the cause of the non-circular motion? Could the constraints being considered only as second deriatives over time be the reason?

The constraints are as follows:
$$
\begin{eqnarray}
f_1 & = & x_1^2 + y_1^2 - (l_1/2)^2 = 0 \\
f_2 & = & (x_2 - 2x_1)^2 + (y_2 - 2y_1)^2 - (l_2/2)^2 = 0
\end{eqnarray}
$$
They state that mass $m_1$ is on a circle about $(0, 0)$ with radius $l_1/2$, and that mass $m_2$ is on a circle about the joint at position $(2x_1, 2x_2)$ with radius $l_2/2$.
The intial conditions are
$$
\begin{eqnarray}
x_0 & = & (x_{10}, \; \dot{x}_{10}, \; y_{10}, \; \dot{y}_{10}, \; x_{20}, \; \dot{x}_{20}, \; y_{20}, \; \dot{y}_{20}) \\
& = & (0, \; 0, \; -l_1/2, \; 0, \; l_2/2, \; 0, \; -l_1, \; 0),
\end{eqnarray}
$$
which are consistent with the constraints.
The below given trajectory of $m_1$ in the $(x, y)$ plane shows that $m_1$ is off the circle about $(0, 0)$. For completeness, a time series plot of $m_1$'s $x$- and $y$-coordinates are shown.
Parameters for integration are $l_1 = l_2 = m_1 = m_2 = g = 1$.

Strangely, a similar drifting effect occurs when the movement of the two masses is constrained by the following set of equations. They represent a crossbar movement of point masses where mass $1$ moves horizontally, mass $2$ moves vertically, and both masses are connected by a rigid rod of length $L$:
$$
\begin{eqnarray}
f_1 & = & x_1^2 + y_2^2 - L^2 = 0 \\
f_2 & = & x_2 = 0 \\
f_3 & = & y_1 = 0
\end{eqnarray}
$$
Again, the initial conditions are consistent with the constraints:
$$
\begin{eqnarray}
x_0 & = & (x_{10}, \; \dot{x}_{10}, \; y_{10}, \; \dot{y}_{10}, \; x_{20}, \; \dot{x}_{20}, \; y_{20}, \; \dot{y}_{20}) \\
& = & (-L, \; 0, \; 0, \; 0, \; 0, \; 0, \; 0, \; 0).
\end{eqnarray}
$$
Below is a plot showing the change of the length of the rod over time which clearly violates the first constraint $f_1$:

A: Yes, integration of the crossbar system with Runge-Kutta scheme of order 4 and 5 does result in numerical instabilities. One can tell by removing the constant states $x_2$ and $y_1$ (and its timely derivatives) from the set of ordinary differential equations. Integrating the reduced system
$$
\begin{eqnarray}
m_1 \ddot{x}_1 & = & - \frac{\dot{x}_1^2 + \dot{y}_2^2 - y_2g}{x_1^2/m_1 + y_2^2/m_2}x_1, \\
m_2 \ddot{y}_2 & = & - \frac{\dot{x}_1^2 + \dot{y}_2^2 - y_2g}{x_1^2/m_1 + y_2^2/m_2}y_2 - m_2 g,
\end{eqnarray}
$$
with $\textbf{x}_0 = (-L, \; 0, \; 0, \; 0)$, and $m_1 = m_2 = g = L = 1$ makes a better approximation, but still violates constraint $f_1$ (blue: full order system, orange: reduced order system):

Important to note that the choice of the integration method Radau reduced the error an order of magnitude of 3:

This is surprising, since the two masses oscillate with the same frequency. Hence, no stiff behavior and no need for a stiff solver.
As for the double pendulum system, it is clear that the full set of eight ordinary differential equations somehow overdetermines the dynamics, since only four are required (two angles and angular velocities).
But it is still an open question to me what exactly goes wrong here.


text:
Q: Is there a way to iterate through a range in using the excel javascript api? Is there a way to iterate through a range in using the excel javascript api? I have two columns and rows of data. In each row if one column has data in it the other should not. The other column should be 0 or null. I would like to highlight rows where both the columns have data. I have added an image of what I want to achieve.

A: If you clean this up as need be, you should be able to do what you need to do.
const sheet = context.workbook.worksheets.getActiveWorksheet();

let dataRange = sheet.getRange("A1:B10").load(["rowCount", "values"]);
await context.sync();

for (var row = 0; row < dataRange.rowCount; row++) {
  let column1 = dataRange.values[row][0];
  let column2 = dataRange.values[row][1];

  dataRange.getRow(row).format.fill.clear();

  if (column1 !== "" && column2 !== "")
    dataRange.getRow(row).format.fill.color = "Red";
}

await context.sync();


text:
Q: C# Delay - delay in outputting to console while execution of program continues I'm trying to find a way of causing the program to not pause but for their to be a delay to execute certain tasks. I.e. I am trying to delay outputting 'Hello' to the console for 10 seconds for example, but the program will continue to execute the rest of the program.

A: Using TPL:
static void Main(string[] args)
{
    Console.WriteLine("Starting at " + DateTime.Now.ToString());

    Task.Run(() =>
    {
        Thread.Sleep(10000);
        Console.WriteLine("Done sleeping " + DateTime.Now.ToString());
    });

    Console.WriteLine("Press any Key...");

    Console.ReadKey();

}

output:
Starting at 2/14/2017 3:05:09 PM
Press any Key...
Done sleeping 2/14/2017 3:05:19 PM

just note that if you press a key before 10 seconds, it will exit.

A: There are 2 typical ways to simulate a delay:

*

*an asynchronous task-like: Task.Delay

*or a blocking activity: Thread.Sleep
You seem to refer to the first situation.
Here it is an example
    public static void Main(string[] args)
    {
        Both();
    }
    static void Both() {
        var list = new Task [2];
        list[0]  = PauseAndWrite();
        list[1]  =  WriteMore();
        Task.WaitAll(list);
    }
    static async Task PauseAndWrite() {
        await Task.Delay(2000);
        Console.WriteLine("A !");
    }
    static async Task WriteMore() {

        for(int i = 0; i<5; i++) {
            await Task.Delay(500);
            Console.WriteLine("B - " + i);
        }
    }

Output
B - 0
B - 1
B - 2
A !
B - 3
B - 4

A: Start a new thread:
Task.Factory.StartNew(new Action(() =>
{
    Thread.Sleep(1000 * 10); // sleep for 10 seconds
    Console.Write("Whatever");
}));

A: You could use a combination of Task.Delay and ContinueWith methods:
Task.Delay(10000).ContinueWith(_ => Console.WriteLine("Done"));

A: You could use 'Thread.Sleep(10000);'
See:
https://msdn.microsoft.com/en-us/library/d00bd51t(v=vs.110).aspx


text:
Q: how to modify my Core Data attributes of an entity but on all the elements of my database hello community I am a novice and this is my first question.
how to change all the attributes of an entity and be able to change all my Core Data elements,
because I can only change the first attribute of an entity but not all my data records.
Here in this function I can only change the name
and then I get this following error has the line:
let objectUpdate = test[0] : Thread 1: Fatal error: Index out of range

func updateData() {

    var newName = ""
    var newPrenom = ""

    newName = name.text!
    newPrenom = prenom.text!

    let managedContext =  AppDelegate.viewContext
    let fetchRequest : NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "Person")
    fetchRequest.predicate = NSPredicate(format: "name = %@", newName)
    do {
        fetchRequest.predicate = NSPredicate(format: "prenom = %@", newPrenom)

        let test = try! managedContext.fetch(fetchRequest) as! [NSManagedObject]
        let objectUpdate = test[0]

        objectUpdate.setValue(newName,forKey: "name")
        objectUpdate.setValue(newPrenom, forKey: "prenom")
        do {
            try managedContext.save()
        }
        catch {
            print(error)
        }
    } catch {
        print(error)
    }
}

A: There are a number of ways we can avoid this error.
Unwrapping optional .first value
Swift's Collection gives us safe way to get first item, simply by accessing the first property on a given collection. It will return an Optional<Element> value so we need to unwrap it first either by using if let of guard let
if let object = test.first {
    // do something with object
}

or
guard let object = test.first else { return }
// do something with object

Checking if value at index exists
It's often a good idea to check for a specific index within the indices property before accessing the value behind it.
if test.indices.contains(0) {
    let object = test[0]
    // do something with object
}

These hints should prevent your code from crashing again.
Other Suggestions
This is not really safe or clean:
var newName = ""
var newPrenom = ""

newName = name.text!
newPrenom = prenom.text!

We can make it much cleaner and most importantly safer by using a guard statement
guard let newName = name.text, let newPrenom = prenom.text else { return }

Two important things happened here:

*

*No more force-unwrapping the optional values of text [which could cause a crash]

*The properties are now immutable, meaning we can be sure that what we are saving to the CoreDate is what was retreived at the beginning of the function

Since the line:
let test = try! managedContext.fetch(fetchRequest) as! [NSManagedObject]

is already wrapped in the do-catch clause, you can safely remove forced try! and replace it with try.
let test = try managedContext.fetch(fetchRequest) as! [NSManagedObject]

Let's use types! On this line you create a NSFetchRequest object for some entity named "Person".
let fetchRequest : NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "Person")

I am guessing CoreData have generated for you a NSManagedObject subclass, named Person. If this is true, you could rewrite it like this:
let fetchRequest = NSFetchRequest<Person>(entityName: "Person")

With the previous tip implemented, we can now get rid of as! [NSManagedObject] from this line:
let test = try managedContext.fetch(fetchRequest) as! [NSManagedObject]

Since the NSFetchRequest object is now nicely typed, we can take advantage of it by rewriting it like this:
let test: [Person] = try managedContext.fetch(fetchRequest)

So we are using proper types now? cool! Lets now improve this:
objectUpdate.setValue(newName,forKey: "name")
objectUpdate.setValue(newPrenom, forKey: "prenom")

by rewriting this and using properties on Person object
objectUpdate.name = newName
objectUpdate.prenom = newPrenom

No need for introducing second level of do-catch clause, since we are already in one!
do {
    try managedContext.save()
}
catch {
    print(error)
}

you can easily replace it with just the save() call, like this:
try managedContext.save()

Are you sure these predicates are what you want?
fetchRequest.predicate = NSPredicate(format: "name = %@", newName)
fetchRequest.predicate = NSPredicate(format: "prenom = %@", newPrenom)

What I can read from them is that you are fetching Person object where the name is newName and prenom is newPrenom and then you update it with the same exact values? Are you using some kind of identification of users? like id: Int or id: UUID? It would make much more sense to write something like this
let id: Int = // ID of the user you are currently editing
fetchRequest.predicate = NSPredicate(format: "id == \(id)")

if you are not using any id's, you could try storing the initial values of name and prenom
// in cell declaration - set when you configure your cell
var initialName: String?
var initialPrenom: String?
// then in your function:
fetchRequest.predicate = NSPredicate(format: "name = %@", initialName)
fetchRequest.predicate = NSPredicate(format: "prenom = %@", initialPrenom)

But I just noticed you also override you first predicate with the second one. You need to use NSCompoundPredicate
fetchRequest.predicate = NSCompoundPredicate(
    type: .and, subpredicates: [
        NSPredicate(format: "name = %@", initialName),
        NSPredicate(format: "prenom = %@", initialPrenom)
    ]
)

Suggested version
func updateData() {
    guard let newName = name.text, let newPrenom = prenom.text else { return }
    let managedContext = AppDelegate.viewContext
    let fetchRequest = NSFetchRequest<Person>(entityName: "Person")

    fetchRequest.predicate = NSCompoundPredicate(
        type: .and, subpredicates: [
            NSPredicate(format: "name = %@", initialName),
            NSPredicate(format: "prenom = %@", initialPrenom)
        ]
    )
    do {
        let objects: [Person] = try managedContext.fetch(fetchRequest)
        guard let object = objects.first else { return }
        object.name = newName
        object.prenom = newPrenom
        try managedContext.save()
    } catch {
        print(error)
    }
}

A: If the index 0 is out of range, it means that the array is empty. Before accessing it, add
if test.isEmpty{
   return //the fetch request didn't return any values
}


text:
Q: Create a branch in a repo without cloning I am doing some grading for a intro web class and we are using GitHub to host their files. Unfortunately for me we forgot to tell the students about gh-pages to so that they could view their code online (everyone was just viewing locally). I do not want to clone all their repos onto my computer nor do I want to add the branch manually online. Does anyone know a terminal command to create a branch on a remote repository if you do not have the repo? (I am a owner of all of their repos). What I want to do is just write a script that will run this command on all the the student repos and create the gh-pages branch.

A: If you'll write a script in any case, so what's the problem? Pseudocode:
for repo in repos
    git clone repo .
    git branch gh-pages
    git push origin gh-pages
    rm -rf .

A: you can't, github doesn't provide feature for creating branch online.


text:
Q: What's the best way to diff blocks of text between two files? What flags for diff or other tools could I use to compare two files for differences in blocks of text. EX:
file1
record {
data1
data2
}

file2
record {
data1
data2
}

record {
data3
data4
}

and the output would be like
record {
data3
data4
}

A: You can use diff command as
diff -a --suppress-common-lines file2 file1

(Or) Use grep as
grep -Fxvf file1 file2

With the following flags,
-F, --fixed-strings
              Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.
-x, --line-regexp
              Select only those matches that exactly match the whole line.
-v, --invert-match
              Invert the sense of matching, to select non-matching lines.
-f FILE, --file=FILE
              Obtain patterns from FILE, one per line.  The empty file contains zero patterns, and therefore matches nothing.

Another way using awk
awk 'NR == FNR {unique[$0]++; next} !($0 in unique)' file1 file2


text:
Q: Replacing Ubuntu package with ppa I would like to replace Ubuntu's default Firefox package on my desktop with the "Developer Edition" available as a PPA (I am pretty new to package management).
I expected instructions found on PPA's page to be all I needed ..
$ sudo add-apt-repository ppa:ubuntu-mozilla-daily/firefox-aurora
$ sudo apt-get update
$ sudo apt-get upgrade
# "apt-get install --reinstall firefox" just re-install the original package.

Okey, Firefox Developer Edition is not getting installed (the original Firefox package is not replaced). And as you can see, apt policy does not show relevant ppa source candidate either.
$ sudo apt policy firefox
firefox:
  Installed: 51.0.1+build2-0ubuntu0.16.04.2
  Candidate: 51.0.1+build2-0ubuntu0.16.04.2
  Version table:
 *** 51.0.1+build2-0ubuntu0.16.04.2 500
        500 http://fr.archive.ubuntu.com/ubuntu xenial-updates/main amd64 Packages
        500 http://security.ubuntu.com/ubuntu xenial-security/main amd64 Packages
        100 /var/lib/dpkg/status
     45.0.2+build1-0ubuntu1 500
        500 http://fr.archive.ubuntu.com/ubuntu xenial/main amd64 Packages

Following that thread I tried to elevate priority of ppa's package in /etc/apt/preferences.d with the following snippet:
Package: firefox
Pin: origin ppa.launchpad.net
Pin-Priority: 800

but apt policy still the same and executing apt-get update with apt-get upgrade did not changed anything.
/etc/apt/sources.list.d contains two files related to Firefox's PPA:
» ubuntu-mozilla-daily-ubuntu-firefox-aurora-xenial.list which contains
deb http://ppa.launchpad.net/ubuntu-mozilla-daily/firefox-aurora/ubuntu xenial main
deb-src http://ppa.launchpad.net/ubuntu-mozilla-daily/firefox-aurora/ubuntu xenial main
#deb-src http://ppa.launchpad.net/ubuntu-mozilla-daily/firefox-aurora/ubuntu xenial main

» ubuntu-mozilla-daily-ubuntu-firefox-aurora-xenial.list.save contains
deb http://ppa.launchpad.net/ubuntu-mozilla-daily/firefox-aurora/ubuntu xenial main

Thank you for helping me sorting this out.

A: I looked into the ppa, and there seems to be build failures (the red X),
launchpad.net/~ubuntu-mozilla-daily/+archive/ubuntu/firefox-aurora/+packages
I suggest that you wait until there is a successful build, and try again (or try another version of Firefox).


text:
Q: Algorithms used in GraphPlot and GraphPlot3D Coppied from Mathematica's help:

Algorithms to be used in GraphPlot and GraphPlot3D can be specified
using the Method option, either as Method->"name" or
Method->{"name",Subscript[opt, 1]->Subscript[val, 1],[Ellipsis]},
where Subscript[opt, i]-> Subscript[val, i] are method-specific
options, described in separate sections.

"SpringElectricalEmbedding"   invoke the spring-electrical embedding
method, in which neighboring vertices are subject to an attractive
spring force that is proportional to their physical distance, and all
vertices are subject to a repulsive electrical force that is inversely
proportional to their distance; the overall energy is minimized

"SpringEmbedding" invoke the spring embedding method, in which a
vertex is subject to either attractive or repulsive force from another
vertex, as though they are connected by a spring; the spring has an
ideal length equal to the graph distance between the vertices; the
total spring energy is minimized

I would like to have also "ElectricalEmbedding" in which only repulsive electrical force would take place. The points of vertices could move only on the surface of unit sphere (to not allow them to go infinitely apart because of the repulsion).
Is it possible to simulate such "ElectricalEmbedding" scenario with existing methods implemented in Mathematica or a new implementation is needed?
PS: You can see how such graph that uses "SpringEmbedding" may look at my other question.


text:
Q: App.config Data Source Relative Path? This is the connection string to a local database on my pc:
<connectionStrings>
<add name="DataEntities"
   connectionString="metadata=res://*/Data.csdl|res://*/Data.ssdl|res://*/Data.msl;
   provider=System.Data.SqlServerCe.4.0;provider connection string="
   Data Source=C:\Users\User\Documents\GitHub\incidentapp\incidentapp\Database\Data.sdf""
  providerName="System.Data.EntityClient"/>
</connectionStrings>

However I want to move the project back-and-forth between computers. How can I set a relative path to my database if the database is in the project location which is incidentapp.

A: I got it. It's because I'm running debug, therefore the 'default' location is at the debug folder. So I just needed to move the database location to the debug folder when I'm developing.
Thanks.


text:
Q: Redirect Gnuplot Error Messages I'd like to redirect gnuplot error messages (that are normally displayed in the gnuplot terminal) to a file for logging. Is there any way to do this?
Example: if I type
gnuplot> Hi!

in the gnuplot terminal, Then I get
gnuplot> Hi!
         ^
         invalid command
gnuplot>

Is there any way to redirect "^\ninvalid command" into another file, e.g. err.txt?
Context: I'm using gnuplot embedded in a c++ application using gnuplot-iostream by Dan Stahlke. It works great! But I have no idea how to get error messages from this pipe, so this would be a good work-around.

A: I don't know exactly if this applies on your c++ application (probably not), but I thought I'd mention anyway. If you do:
[user@server]$ gnuplot 2> err.txt
gnuplot> Hi!
gnuplot> exit
[user@server]$ cat err.txt

G N U P L O T
Version 5.0 patchlevel 1    last modified 2015-06-07

Copyright (C) 1986-1993, 1998, 2004, 2007-2015
Thomas Williams, Colin Kelley and many others

gnuplot home:     http://www.gnuplot.info
faq, bugs, etc:   type "help FAQ"
immediate help:   type "help"  (plot window: hit 'h')

Terminal type set to 'aqua'
     ^
     invalid command

Maybe you could incorporate something like this. Hope it helps!

A: I don't think one can achieve this internally within Gnuplot without tinkering with the source code.
The message "invalid command" is produced in command.c by calling the function int_error (defined in util.c) within which is stderr specified explicitly...

A: It seems gnuplot redirects by default both stdout and stderr to stderr.
Instead, terminal file output is send to stdout. Here is an example to check. The content of tmp.gnu.
print 'some text';
set terminal postscript;
set out
pl sin(x)

gnuplot tmp.gnu 2>tmp.txt  1>sin.ps

tmp.txt contains the stdout and sin.ps the postscript file.
Check also this answer https://stackoverflow.com/a/27375957/11769765 to use
set print "-", set print "/dev/fd/2" or set print "filename" to redirect stdout.


text:
Q: Unable to login with MD5 encypted password in core php I want to login with saved credentials in user table using core php, my password is saved in encrypted form in MD5 in database user table, i want to login with email and password, but when i encrypted my password while login password do not match with database table password,
please help me, how can i login with encrypted md5 password. here is my code.
index.html

     <form action="login_admin.php" method="POST">

                                        Username

                                            <input type="email" class="form-control" placeholder="email" name="email">

                                        Password

                                            <input type="password" class="form-control" placeholder="*********" name="pwd">

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

                                </form>

login_admin.php
<?php

    include('connection.php');

    if(isset($_POST['submit'])){

        $email = $_POST['email'];
        $password = $_POST['pwd'];
        $password = md5($_POST['pwd']);
        $_SESSION['email'] = $email;
        $_SESSION['password'] = $password;
        $admin= $_SESSION['email'];

        $query = "SELECT * FROM `user` Where (email = '$email' && role_id = 'admin' )";
        $result = mysqli_query($conn, $query);
        $row = mysqli_fetch_assoc($result);
        if($row > 0){
                if($admin == $row['email'] && $password == $row['password']){
                    echo "test"; die;
                }
        }

    else{
        echo "Login Failed";
    }

    ?>

connection.php

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "example_user";
    $conn = new mysqli($servername, $username, $password, $dbname);
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
    ?>

A: How to Unhash a Password?

Read my comment First.

To hash
 password_hash ( string $password , mixed $algo , array $options = ? ) : string|false

Usage :
<?php echo password_hash('Hello world', PASSWORD_BCRYPT ) ?>

Values:
$password = "password";;
$algo = "password algorithm";
For more info:
https://www.php.net/manual/en/password.constants.php
Compare a password with a hashed version##
  password_verify ( string $password , string $hash ) : bool

Usage :
<?php $text = "I am a php master!"; $hashed = password_hash($text, PASSWORD_BYCRIPT); echo $text . "
". $hashed . "
";
   // password_verify returns a Boolean
   if(password_Verify($text, $hashed)) echo "Correct";
  ?>

Values:
password
The user's password.

hash
A hash created by password_hash().

For more info:
https://www.php.net/manual/en/function.password-verify.php


text:
Q: Could not load file or assembly 'msshrtmi, Version=2.7.0.0 - what SDK installs it? I'm trying to run an webapp that is using some Azure SDK (and storage) apis but when I try to run it, I always get this runtime error.
I have the project on a Windows 7 box with Visual Studio installed and a bunch of SDKs and it works but on this new Win10 machine I'm starting it doesn't work.
msshrtmi.dll is present on the new machine on C:\Program Files\Microsoft SDKs\Azure\.NET SDK\v2.9\bin\runtimes\base\x86 (and x64 and in runtimes\net45\base) but on the old machine it is also on
c:\windows\Microsoft.net\assembly\GAC_XX\msshrtmi and I can see on IIS that is from it's loaded.
If I manually copy msshrtmi.dll to my bin folder the project works just fine. I also know this file is required form Microsoft.WindowsAzure.ServiceRuntime.
On this new machine I'm trying to avoid installing Visual Studio and using only Jetbrains Rider to build and run the project. It can build the project fine but now it doesn't run because of this.
Does the file really need to be on my windows\microsoft.NET folder? What installer puts it there? Or should I just include msshrtmi.dll as a dependency on my project?
Any other solutions for this problem?
I tried a lot of the solutions on other answers I encountered for this similar problem with no luck.
Edit: tried on ISS express 8 and 10

A: There are several possible ways to solve this issue:
1.Copy the msshrtmi.dll manually to your project. For example in the \bin folder next to the WindowsAzure.Storage.dll.
2.Install the Windows Azure SDK on your server.
3.Change some configurations from app.config.
 <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>

  <runtime>
    <NetFx40_LegacySecurityPolicy enabled="false" />
  </runtime>

For more details, you could refer to this article and this one.


text:
Q: Draft mode for pgfplots I'm working on a fairly big document that has a lot of graphs of functions- so far it has around 200, by the end it will have around 1500. I use pgfplots for each graphic, and the functions are pretty basic: exponential, rational, polynomial, and trigonometric.
Once I am happy with each graph, I don't necessarily need to see it every time I compile, and would like to minimize compilation time for future drafts. Naturally, the document is already chopped up into chapter files, but each chapter contains around 100 figures.
Having studied the pgfplots documentation, I haven't found a draft mode, but I'm interested in knowing if one could be created.
I'm envisaging something similar to the draft mode of the graphicx package, in which graphics are not included, and blank boxes are put in their place.
Some things I've considered:

*

*the standalone documentclass; but with about 1500 figures, wouldn't this mean over-modulization?

*tikzexternalize, but this still requires an initial 'monster' compilation to get the images externalized before the draft option could be invoked

Here's a MWE to play with
\documentclass{article}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
    \begin{axis}
        \addplot {x^2};
    \end{axis}
\end{tikzpicture}

\end{document}

A: In the end I managed to spend a lot of time coming up with something that probably suits your needs less than all of the other options.  However, since I had fun making it, I might as well post it, at least for curiosities sake.  The basic idea is to build the graphics, write their dimensions to an external file and, when in "draft mode", rather than building the graphics replace each with a framed box of the correct dimensions.  The main disadvantage of this would be that the work done in building the graphics is lost because the result isn't saved.  Thus, the final document would need to be compiled from scratch to include the graphics.  In addition, it won't detect changes to earlier work without recompiling the entire document.  For at least those reasons it's not a great solution but might be useful as an example.
\documentclass{article}
\usepackage{pgfplots}
\usepackage{xparse}

\ExplSyntaxOn
\bool_new:N \g_draft_bool
\bool_new:N \g_set_dimens_bool
\iow_new:N \put_dimens_iow
\ior_new:N \get_dimens_ior
\box_new:N \l_my_box
\clist_new:N \g_my_dimens_clist
\int_new:N \g_num_dimens_int
\int_new:N \g_num_pics_int
\int_new:N \l_count_int

\cs_new:Npn \tikz_pic:w #1 \q_stop
    {
        \int_gincr:N \g_num_pics_int
        \bool_if:NTF \g_set_dimens_bool
            {%if rescanning, then box and write dimensions to file
                \tl_set:Nn \l_tmpa_tl { \begin{tikzpicture} #1 \end{tikzpicture} }
                \hbox_set:Nw \l_my_box \l_tmpa_tl \hbox_set_end:
                \iow_now:Nn \exp_args:No \put_dimens_iow {\dim_eval:n {\box_wd:N \l_my_box},\dim_eval:n {\box_ht:N \l_my_box}}
                %\box_use:N \l_my_box % uncomment to see pics on \SetDims run
            }
            {
                \bool_if:NTF \g_draft_bool
                    {
                        \int_compare:nTF {\g_num_pics_int > \g_num_dimens_int}
                            {%if new pics, add dimensions to clist and draw pic
                                \tl_set:Nn \l_tmpa_tl { \begin{tikzpicture} #1 \end{tikzpicture} }
                                \hbox_set:Nw \l_my_box \l_tmpa_tl \hbox_set_end:
                                \clist_gput_right:Nx \g_my_dimens_clist {\dim_eval:n {\box_wd:N \l_my_box},\dim_eval:n {\box_ht:N \l_my_box}}
                                \box_use:N \l_my_box
                            }
                            {%if not, then draw boxes
                                \clist_set_eq:NN \l_tmpa_clist \g_my_dimens_clist
                                \clist_pop:NN \l_tmpa_clist \l_tmpa_tl
                                \clist_pop:NN \l_tmpa_clist \l_tmpb_tl
                                \fbox{\rule{\dim_eval:n \l_tmpa_tl}{0pt}\rule{0pt}{\dim_eval:n \l_tmpb_tl}}
                            }

                    }
                    {%if not draft or scanning, do as normal
                        \begin{tikzpicture} #1 \end{tikzpicture}
                    }
            }
    }

%this will grab dimensions of all existing pics
\NewDocumentCommand \SetDims {}
    {
        \bool_gset_true:N \g_set_dimens_bool
        \iow_open:Nn \put_dimens_iow {dims.aux}
    }

%after setting dims, this will replace all pics with their bounding boxes.
%graphics added after setting dims (except the most recently added), will be
%replaced by their bounding boxes on subsequent compiles
\NewDocumentCommand \DraftOn {}
    {
        \bool_gset_true:N \g_draft_bool
        \ior_open:Nn \get_dimens_ior {dims.aux}
        \bool_until_do:nn { \ior_if_eof_p:N \get_dimens_ior }
            {%write saved dimensions to clist and count pics
                \ior_to:NN \get_dimens_ior \l_tmpa_tl
                \clist_gput_right:NV \g_my_dimens_clist \l_tmpa_tl
                \int_gincr:N \g_num_dimens_int
            }

        \ior_close:N \get_dimens_ior
        \clist_remove_all:Nn \g_my_dimens_clist {\par}%the above puts a par in the clist
        \int_gdecr:N \g_num_dimens_int%compensate for the par
    }

\NewDocumentCommand \tikzpic { +m }
    {
        \tikz_pic:w #1 \q_stop
    }

\AtEndDocument{
    \bool_if:NT \g_draft_bool
        {
        \int_compare:nT {\g_num_pics_int > \g_num_dimens_int+1}
            {%if more than one new pic
                \iow_open:Nn \put_dimens_iow {dims.aux}
                \int_until_do:nn {\l_count_int >= \g_num_pics_int-1}
                    {%re-write dims file, excluding last pic
                        \int_incr:N \l_count_int
                        \clist_pop:NN \g_my_dimens_clist \l_tmpa_tl
                        \clist_pop:NN \g_my_dimens_clist \l_tmpb_tl
                        \iow_now:Nn \exp_args:No \put_dimens_iow {\dim_eval:n \l_tmpa_tl,\dim_eval:n \l_tmpb_tl}
                    }
            }
        }
}

\NewDocumentCommand \makelotsoftikzpics {o}
    {
        \prg_replicate:nn {50}
            {
                \tikzpic{
                  \begin{axis}
                    \addplot {x^2};
                  \end{axis}
                }\par\noindent
            }
}
\ExplSyntaxOff
\fboxsep=0pt

\begin{document}
%first run with \SetDims switch
\SetDims
%comment \SetDims and uncomment \DraftOn to get bounding boxes
%\DraftOn
Here are some tikz pics...\par\noindent
\makelotsoftikzpics
%As additional pics are added (with \DraftOn) all but the most recent will be replaced by their bounding boxes
%on subsequent compiles
%\tikzpic{
    %\begin{axis}
        %\addplot {x^2};
    %\end{axis}
%}\par\noindent
%\tikzpic{
    %\begin{axis}
        %\addplot {x^2};
    %\end{axis}
%}\par\noindent

\end{document}

A: Some people tend to use the "todonotes" package which will be broken if one messes around with the tikzpicture environment. A more simple solution could be to use the "ifdraft" package like in this modified example:
% Pgfplots demo
% Author: Christian Feuersänger
% Source: Pgfplots manual:
% http://www.ctan.org/tex-archive/help/Catalogue/entries/pgfplots.html
\documentclass{article,draft}
%\documentclass{article}

\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{ifdraft}
\begin{document}

\begin{tikzpicture}
\begin{axis}[
    xlabel=$x$,
    ylabel=$y$]
\ifdraft{}{%the following is only done if draft mode is disabled
\addplot[smooth,mark=*,blue] plot coordinates {
    (0,2)
    (2,3)
    (3,1)
};
\addlegendentry{Case 1}

\addplot[smooth,color=red,mark=x]
    plot coordinates {
        (0,0)
        (1,1)
        (2,1)
        (3,2)
    };
\addlegendentry{Case 2}
}
\end{axis}
\end{tikzpicture}
\end{document}

A: Following a suggestion of @percusse, here's a (perhaps too) simple way:
\documentclass{article}
\usepackage{pgfplots}

\ifdim\overfullrule>0pt % draft option is active
  \usepackage{environ}
  \let\tikzpicture\relax
  \let\endtikzpicture\relax
  \NewEnviron{tikzpicture}{%
    \begin{pgfpicture}
    \pgfpathrectanglecorners{\pgfpointorigin}{\pgfpoint{3cm}{3cm}}%
     \pgfusepath{stroke}\end{pgfpicture}%
  }
\fi

\begin{document}

\begin{tikzpicture}
  \begin{axis}
    \addplot[thick] {x^2};
  \end{axis}
\end{tikzpicture}

\end{document}

The draft option sets \overfullrule to 5pt. A safer way would be to check whether draft appears in the global options, saved in \@classoptionslist:
\makeatletter
\@tempswafalse
\def\@tempa{draft}
\@for\next:=\@classoptionslist\do
  {\ifx\next\@tempa\@tempswatrue\fi}
\if@tempswa % draft option is active
  \usepackage{environ}
  \let\tikzpicture\relax
  \let\endtikzpicture\relax
  \NewEnviron{tikzpicture}{%
    \begin{pgfpicture}
    \pgfpathrectanglecorners{\pgfpointorigin}{\pgfpoint{3cm}{3cm}}%
    \pgfusepath{stroke}
    \end{pgfpicture}%
  }
\fi

Of course a really satisfying solution would draw a box as wide as the picture it represents, provided the information is available, instead of a fixed rectangle.

There's a problem with the former solution: all \tikz...; inline pictures will be transformed into boxes and some text would be lost. Here's a more complicated way to cope with this problem
\makeatletter
\@tempswafalse
\def\@tempa{draft}
\@for\next:=\@classoptionslist\do
  {\ifx\next\@tempa\@tempswatrue\fi}
\if@tempswa % draft option is active

  \usepackage{environ,etoolbox}

  \let\tikz@@tikzpicture\tikzpicture
  \let\tikz@@endtikzpicture\endtikzpicture
  \patchcmd\tikz@opt{\tikzpicture}{\tikz@@tikzpicture}{}{}
  \patchcmd\tikz@collectnormalsemicolon{\endtikzpicture}{\tikz@@endtikzpicture}{}{}
  \chardef\@tempa=\catcode`\;
  \catcode`\;=\active
  \patchcmd\tikz@collectactivesemicolon{\endtikzpicture}{\tikz@@endtikzpicture}{}{}
  \catcode`\;=\@tempa

  \let\tikzpicture\relax
  \let\endtikzpicture\relax
      \NewEnviron{tikzpicture}{%
        \begin{pgfpicture}
        \pgfpathrectanglecorners{\pgfpointorigin}{\pgfpoint{3cm}{3cm}}%
        \pgfusepath{stroke}
        \end{pgfpicture}%
      }
    \fi

We save the original meanings of \tikzpicture and \endtikzpicture, patching the relevant macros to use the aliases.

A: This answer is really just an application of zeroth's question & answer: Externalization to other format, Makefile. Add new rules to the makefile
\documentclass{article}
\usepackage{pgfplots}

\usetikzlibrary{external}
\tikzexternalize[mode=list and make]

\begin{document}

\begin{tikzpicture}
    \begin{axis}
        \addplot {x^2};
    \end{axis}
\end{tikzpicture}

\end{document}

This is awesome, because you can then run
make -f \jobname.makefile

to generate all of the images in one go- sweet!

A: Low tech solution: only sample the beginning and end point of the curve by adding this line in the preamble
\pgfplotsset{samples=2}


text:
Q: Is there way to make my code to do some actions in another site and return the results? I need to do an unordinary thing. I need to make my site to go to another site, write some words on the some input field, search results and get back the results of that search from another site.
Is there any way for it?

A: If you need automated tool then you have to code a script. With PHP you can use cURL. With cURL you can post data into forms and get content as you want. You can post data for exmaple:
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);

http://php.net/manual/en/book.curl.php

A: Use an API
Usually for stuff like this there should be an API for what you're trying to do.
If that is not the case check the following options AND make sure the owner of the website allows you to do what you want to do (or you could get blocked if you cause too much traffic or he doesn't like web-scraping in general)
Use direct HTTP requests
A web form is basically just a way to "build" a HTTP request to a certain endpoint. Look at the HTML of the website to figure out how the request is created:

*

*Check the "action" attribute of the form tag for the target url.

*Get the HTTP method by checking the value of the form tags "method" attribute

*Get the parameter names by checking the name attributes of all input tags.

If they change their website these values may change and your program may fail.
You can use cURL or any other HTTP library to do that.
Use a library simulating a web browser
Example: Symfony Browser-Kit
I don't want to provide a whole manual of how to use it, since the documentation on the linked page is pretty good. But an example taken from that page:
use Acme\Client; // Make sure to create this class as described in the documentation

// make a real request to an external site
$client = new Client();
$crawler = $client->request('GET', 'https://github.com/login');

// select the form and fill in some values
$form = $crawler->selectButton('Log in')->form();
$form['login'] = 'symfonyfan';
$form['password'] = 'anypass';

// submit that form
$crawler = $client->submit($form);

If they change their website this could fail too, depending on the changes they made. You would need to update your program accordingly.


text:
Q: How can I hide a django label in a custom django form? I have a custom form that creates a hidden input of a field:
class MPForm( forms.ModelForm ):
    def __init__( self, *args, **kwargs ):
        super(MPForm, self).__init__( *args, **kwargs )
        self.fields['mp_e'].label = "" #the trick :)

class Meta:
    model = MeasurementPoint
    widgets = { 'mp_e': forms.HiddenInput()  }
    exclude = ('mp_order')

I have to do this little trick to "hide" the label, but what I want to do is remove it from the form. I create the form like this:
forms.MPForm()

A: If you use the form.as_p or form.as_table method, Django shouldn't display the labels for your hidden fields anyway, so there's no need to change the label in your __init__ method.
{{ form.as_table }}

If you are customizing the form template, you can use the field.is_hidden attribute to check whether the field is hidden.
{% if field.is_hidden %}
   {# Don't render label #}
{% endif %}

Alternatively, you can loop over hidden and visible fields separately, and omit the label for hidden fields.

A: You need to give False and it will work:
self.fields['mp_e'].label = False

django version: 2.2

A: i found this useful and it works for me!
class CustomForm(forms.Form):
class Meta:
    ...  #other properties such as model, fields, widgets and help text
    labels = {
       'comment' : '',
    }

A: I wouldn't recommend removing the label as it makes the form inaccessible. You could add a custom CSS class to the field, and in your CSS make that class invisible.
EDIT
I missed that the input was hidden so accessibility isn't a concern.
You can render the form fields directly in your template:
<form ...>
    {% for field in form.hidden_fields %}
        {{ field }}
    {% endfor %}

    {% for field in form.visible_fields %}
        {{ field.label }} {{ field }}
    {% endfor %}
</form>

A: Now,(my django version is 2.1.4), you can solve in this way -> Edit forms.py file:
password = forms.CharField(label=False)

A: Go to your forms.py file and
add label = false
as
below
name = forms.CharField(required=True, max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Enter Name *'}), label=False)

A: Unless I'm misunderstanding your question, you just need to add the mp_e field to the exclude tuple under the meta class. is this not what you need?
class MPForm( forms.ModelForm ):
    def __init__( self, *args, **kwargs ):
        super(MPForm, self).__init__( *args, **kwargs )

    class Meta:
        model = MeasurementPoint
        exclude = ('mp_order','mp_e')


text:
Q: Response returning status but not data I have Jersey endpoint that is attempting to create a CSV file and return it via GET; however, all these attempts end up with the same result - the ok status (200) is returned but no file.
    @GET
    @Path("/research")
    @Produces(MediaType.TEXT_PLAIN)
    public Response dumpAllResearchAndSupportData() {
        QuickDumpBuilderService dumpBuilderService = getQuickDumpService();

        List<DevelopmentProposal> researchOtherProposals = dumpBuilderService.getAllResearchRecords();

        String csvLocation = dumpBuilderService.buildCSV(researchOtherProposals);

        File file = new File(csvLocation);
        String filename = "reserach_" + UUID.randomUUID().toString() + ".csv";
        return Response.ok(file, MediaType.TEXT_PLAIN).header("Content-Disposition", "attachment; filename=" + filename).build();
    }

My CSV file is properly created, but it fails to be returned along with the response.
Notice above, I'm writing the CSV to a temporary location in my tomcat folder and then passing the path to that file back and then attempting to read that from the location here.
Another attempt with the same result where instead of writing the CSV to temp location, I'm just trying to write the ByteArrayOutputStream to the response object.
    @GET
    @Path("/research")
    @Produces(MediaType.APPLICATION_JSON)
    public Response dumpAllResearchAndSupportData() {
        QuickDumpBuilderService dumpBuilderService = getQuickDumpService();
        // Step 1.  Retrieve all research and other proposals
        List<DevelopmentProposal> researchOtherProposals = dumpBuilderService.getAllResearchRecords();
        // Step 2.  Create CSV File
        ByteArrayOutputStream csvBaos = dumpBuilderService.buildCSV(researchOtherProposals);
        // Step 3.  Create spreadsheet
        ByteArrayOutputStream excelBaos = dumpBuilderService.createExcelSpreadsheet(csvBaos, servlet);
        // Step 4.  Return spreadsheet
        Response.ResponseBuilder response = Response.ok(excelBaos);
        return response.build();

Another attempt where I added this "writer" into the response.  This attempt generated an error that a "MessageBodyWriter for the ByteArrayStream was not found."  That prompted the attempt below.
    @GET
    @Path("/research")
    @Produces(MediaType.TEXT_PLAIN)
    public Response dumpAllResearchAndSupportData() {
        ....
        // Step 4.  Return spreadsheet
        return Response.ok(getOut(csvBaos.toByteArray())).build();
    }

    private StreamingOutput getOut(final byte[] csvBytes) {
        return new StreamingOutput() {
            @Override
            public void write(OutputStream out) throws IOException, WebApplicationException {
                out.write(csvBytes);
                out.flush();
            }
        };
    }

I've looked at the following similar answers, and I've attempted all of them with no success.
Not sure what I'm doing wrong - I suspect that it's something to do with how I setup my endpoint and defer to the Java REST API experts here.
File download/save from a Jersey rest api call using ANGULARJS . file is attached with response as "Content-Disposition"
Download CSV file via Rest
jersey - StreamingOutput as Response entity
Thanks for your help.


text:
Q: Reinforcement learning (Q-learning) under constraint I want know how to add a constraint to Q-learning. I have an action resulting in two rewards every time (reward 1= delivery cost , reward 2= delivery time). I want to minimize the cost while ensuring max delivery time limit is not violated. Is there a standard/formalized way to do this?

A:
Is there a standard/formalized way to do this?

Yes. There is no way to optimise across two independent variables, they must be combined into a single metric. This is typically done using a linear sum. If one value must be minimised and the other maximised, then typically in RL you express the value to be minimised as a negative reward value, because RL usually maximises reward (this is not a requirement, you can easily re-write any RL algorithm to minimise a long-term cost, just the literature mostly talks about maximising a long-term reward).
So you must combine the two metrics, decide the weights for the disparate rewards, perhaps based on monetary business value. Then you add them together. If there are strict constraints, either ensure action or state space does not allow the possibility of them, or if that is not feasible, then penalise an unacceptable result with a large negative reward. There is no requirement that you scale rewards linearly.


text:
Q: Software to duplicate external hard drive formatted ExFAT I have an external hard drive with a 2.9TB ExFAT partition that I keep my photos and other media on. (ExFAT so that I can also see and edit my media on Windows computers.) I just bought a second hard drive that I will set up the same way so that I can back up my media. Normally, I use SuperDuper! but that only works with Mac formats. Is there any Mac or command line software that can check for exact duplication? Due to the size of the drive (2.9TB with 1.8TB used), I don't want to do the duplication manually.

A: I'm assuming you have nothing on the new disk and essentially want to mirror what is on the old disk to the new disk.
You can use the following command line, substituting the proper names for Source-Disk (old) and Destination-Disk (new).
rsync -xavH /Volumes/Source-Disk/ /Volumes/Destination-Disk/

Note: The slash at the end of each path has significance, so don't forget to include it when changing the name of Source-Disk (old) and Destination-Disk (new).  Also, if there are spaces in them, make sure you either escape the spaces with a backslash \ or quote the pathnames, but not both.
Explanation of the options used:
-x, --one-file-system    don't cross filesystem boundaries
-a, --archive    archive mode; same as -rlptgoD (no -H)

    -r, --recursive    recurse into directories
    -l, --links    copy symlinks as symlinks
    -p, --perms    preserve permissions
    -t, --times    preserve times
    -g, --group    preserve group
    -o, --owner    preserve owner (super-user only)
    -D    same as --devices --specials
        --devices    preserve device files (super-user only)
        --specials    preserve special files

-v, --verbose    increase verbosity
-H, --hard-links    preserve hard links

Note: Because symlinks are being copied to the Destination-Disk volume the volume name of the Destination-Disk will need to be renamed identical to the Source-Disk, afterwards, for the links to files on the disk itself to track.  See the SYMBOLIC LINKS section in the rsync man page for additional options that can be used to modify how the symlinks can be treated.


text:
Q: Logstash Filter: aggregate - auto save on timeout I have a Lambda function in AWS which reports logs to an ELK instance. Each invocation of the lambda function generates a unique invocation_id that is sent with every log event, so the events from a single invocation can be identified in ELK. At the end of the operation, I send a "Done" event.
A Lambda function can fail, or timeout, and then the "Done" event is not sent.
I want to use the logstash aggregate filter to identify the failed invocations. Meaning - each invocation_id will be a task_id in the aggregation map, and the "Done" event will be the end_of_task.
And I need to tell it "on timeout (there was no done event received after X time) save the aggregated event with status=failed".
Is that possible with this filter? If so, what is the syntax? It's not clear from the docs..

A: Logstash aggregate filter supports timeout event generation since version 2.3.0. Here is how to achieve what you want using this feature:
if [action] == "BEGIN" {
  aggregate {
    task_id => "%{id}"
    code => "map['bytes'] = 0"
    map_action => "create"
  }
} elseif [action] == "DONE" {
  aggregate {
    task_id => "%{id}"
    code => "event['bytes'] += map['bytes']"
    timeout_code => "event.tag('failed')"
    map_action => "update"
    end_of_task => true
    timeout => 10
    push_map_as_event_on_timeout => true
} else {
    aggregate {
    task_id => "%{id}"
    code => "map['bytes'] += event['bytes']"
    map_action => "update"
    add_tag => [ "drop" ]
}


text:
Q: Relocate symfony config directory I have a new symfony project. In order to satisfy Debian's FHS I want to put the project's config/ directory under /etc and create a symbolic link pointing from the normal config/ location to the directory in /etc.
I have tried this but it does not work. I get errors from ProjectConfiguration.class.php complaining about not being able to find sfCoreAutoload.class.php.
require_once dirname(__FILE__).'/../lib/vendor/symfony/lib/autoload/sfCoreAutoload.class.php';

This makes sense since the original line no longer points at the correct location.
So I changed that line to an absolute path
require_once '/usr/share/myproject/lib/vendor/symfony/lib/autoload/sfCoreAutoload.class.php';

But now I get errors like
Uncaught exception 'InvalidArgumentException' with message 'The application "client" does not exist.'

Is there a robust way to relocate the config/ directory of a symfony project? (I realize that there are good reasons not to do this, and I wouldn't if I did not have to, so please keep that in mind.)

A: I think you'll find a better answer if you ask on Stack overflow.
I'm a symfony user, and I don't really get what you're trying to do.
First, you must (much more easy to maintain) create a symfony directory with all symfony component. You create symbolic link in your vendor.
If you've created a new project, then create a symbolic link in vendor to your symfony directory.
exemple :
\etc\home\Project_Symfony\Symfony\ (the symfony directory with all component)
\etc\home\Project_Symfony\Project_1\ (your project folder)
\etc\home\Project_Symfony\Project_2\ (your project folder)
In you Project_1 & Project_2 create a symbolic link in the vendor directory.
From what I understand with your errors, you must recreate the link from your new project to symfony. Go look here to find help : http://www.symfony-project.org/jobeet/1_4/Doctrine/en/01


text:
Q: Highlight one city at a time and remove color fill when other City is hovered on I want to remove the color fill on the old city when another city is hovered on. Currently when i hover over the map it highlights every city when hovered over.
$('area').hover(function () {

        var coordinates = $(this).attr("coords");

        canvas = document.getElementById("canvas");
        context = canvas.getContext("2d");
        v

    });

A: Ok, since you commented on my comment I'm gonna leave you the code which I think might fix you issue:
$('area').hover(function () {

        var coordinates = $(this).attr("coords");
        canvas = document.getElementById("canvas");
        context = canvas.getContext("2d");
        context.clearRect ( 0 , 0 , canvas.width, canvas.height );
        var points = coordinatess.split(",");
        context.moveTo(points[0], points[1]);
        for (var i = 0; i < points.length; i += 2) {
         var   x = parseInt(points[i]);
           var y = parseInt(points[i + 1]);
            context.lineTo(x, y);
            context.fillStyle = 'blue';
            context.fill();
        }
    });


text:
Q: Wordpress multisite condition for certain blog_id's I have a function in my network's footer:
<?php
$blog_id = get_current_blog_id();
if ( 446 == $blog_id ) {
?>
----my code-----
<?php } ?>

....How would this have to look if I want
1.) all blog IDs 446 and above to be included?
and
2.) only a certain part of the blog title to be included? (Let's say I only want this code to appear when the blog title contains the word 'test')?
Is that even possible?
Thanks!!

A: Sure, this is easy. The following condition is for all sites with ID equal or higher than 446 that at the same time have a blog title that contains the four letters test next to each other, whether they have intervals around them or not (so keep in mind it will include other words too, like testify or protest unless we change the code a little).
$blog_id = get_current_blog_id();
$blog_details = get_blog_details( $blog_id );
if ( strpos( $blog_details->blogname, 'test' ) !== false && $blog_id >= 446 ) {
    // Run some code here
}


text:
Q: In Zabbix how to separate data of the same type but from different sources? I have a machine that receives data from multiple sources. This machine forwards the data to the Zabbix Trapper.
I want to be able to view this data separately. One way of doing that is to send data from each source with a different fake hostname. But this is not ideal.
I can receive this data in more than one host. I would like to be able to see data from source 1 on host A separately from source 2 on host A and from source 1 in host B.
Also posted on: http://www.zabbix.com/forum/showthread.php?t=16503
Edit : I am currently doing this manually. I send:

*

*datatypeA[source1]

*datatypeA[source2]

I create a item per source. All the data shows separately in the host latest data. But what if I wanted to add a third source? I would have to create a third item manually, right? How to automatize this?

A: As far as I can see, your options are:

*

*Create multiple hosts, as you've suggested.  You can probably give them the same IP address, although I haven't tried this.  Each "host" will have a different set of items.

*Create multiple "Applications" within a single host.  From the "Latest Data" screen you can expand and collapse each application individually, which will effectively keep it separate.
Can you elaborate on what kind of data you're collecting and how it is being sent?  Is it SNMP queries, SNMP traps, Zabbix agent, custom script?

A: as noted on zabbix forum, adding new items isn't as easy. while that could be achieved by curl-scraping web frontend, better solution might be through the api - nelsonab (author of zabcon) was talking about getting trapper item adding for zabcon, i believe.
thus i'd suggest following or maybe even zabcon - http://www.zabbix.com/wiki/doc/zabcon


text:
Q: Why isn't $\mathbb Z_9 \cong \mathbb Z_3 \times \mathbb Z_3$ by the fundamental theorem of finite abelian groups? I was reading the answer to this question: Explicit descriptions of groups of order 45 and the accepted answer says the Sylow $3$-subgroup is either isomorphic to $\mathbb Z_9$ or $\mathbb Z_3 \times \mathbb Z_3$. But now my question is: Why isn't $\mathbb Z_9 \cong \mathbb Z_3 \times \mathbb Z_3$ by the fundamental theorem of finite abelian groups?
The fundamental theorem of finite abelian groups says: Every finite abelian group is the direct product of cyclic groups. (Herstein)
So isn't $\mathbb Z_9 \cong \mathbb Z_3 \times \mathbb Z_3$ by this theorem?

A: More to the point: How many elements of order $9$ does $\Bbb Z_3\times\Bbb Z_3$ have?

A: The theorem does indeed hold: $\Bbb Z_9$ is a "trivial" direct product; it's cyclic, and just itself! Or, you can think of it as $\Bbb Z_9 \times \{0\}$, the product of itself with the trivial group (which is also cyclic!).
Just because

Every finite abelian group is the direct product of cyclic groups

that doesn't mean that every finite abelian group is the direct product of cyclic groups of prime order.

A: In general, one needs $\mathrm{gcd}(m,n) = 1$ for $\mathbb{Z}_{mn}$ to be isomorphic to $\mathbb{Z}_m \times \mathbb{Z}_n$.

A: The other answers to this post have done a good job explaining this, but since you mentioned the Sylow theorems, you might want to look into at them to get the full picture here, particularly, the first, that reads:

If $G$ is a $p$-group of order $\#G=mp^k$, then it has $p$-subgroups of order $p^i$ for every $p^i | p^k$

meaning that

If $\# G$ is a multiple of $p^k$ then it has subgroups of orders equal to all possible powers of $p$ between $0$ and $k$ ($1, p, p^2, ... , p^{k-1}, p^k)$

So since $\# \mathbb Z_9=9=3^2$, a direct consequence of Sylow's 1st Theorem is that $\mathbb Z_3 \leq \mathbb Z_9$ (since we're talking about an abelian group, $\mathbb Z_3$ is a normal subgroup).
After that, the statement $\mathbb Z_9 \ncong \mathbb Z_3 \times \mathbb Z_3$ becomes ovious if you take into consideration this post for avaluating direct products of subgroups.

A: It is easy to see that $1$ is a generator of $\Bbb Z_9$
Now take any arbitary element of $\Bbb Z_3\times\Bbb Z_3$, say (a,b).
Then the span of ($a$,$b$) = {($a$,$b$), ($2a$,$2b$), ($0$,$0$)}
Hence |span of ($a$,$b$)| <= $3$ < $9$ = |$\Bbb Z_3\times\Bbb Z_3$| i.e there is no single element generator of $\Bbb Z_3\times\Bbb Z_3$. Thus, $\mathbb Z_9 \ncong \mathbb Z_3 \times \mathbb Z_3$


text:
Q: Change Column Name I have a table called xro_zips_import, which is located on a sql server database. It contain's millions of row of data. I have a column named 'City' and 'CityAliasName' within the table. I need to drop the city column and change the CityAliasName to City. I'm not sure how to use the sp_Rename procedure correctly in Python. This is what I currently have.
conn.cursor().execute('ALTER TABLE xro_zips_import DROP COLUMN City')
conn.commit()

conn.cursor().execute("{EXEC sp_RENAME} (?,?,?), ('xro_zips_import.CityAliasName', 'City', 'COLUMN')")
conn.commit()

This is the error that I receive after the execution of sp_RENAME

Traceback (most recent call last):   File
  "Z:\Projects\ZipCodes\ftpUpdate.py", line 274, in
      conn.cursor().execute("{EXEC sp_RENAME} (?,?,?), 'xro_zips_import.CityAliasName', 'City', 'COLUMN'") ProgrammingError:
  ('42000', '[42000] [Microsoft][SQL Server Native Client 10.0]Syntax
  error, permission violation, or other nonspecific error (0)
  (SQLExecDirectW)')

A: I ended up figuring it out. For anyone else that ever runs into this the syntax for sp_rename looks like this.
conn.cursor().execute("{call sp_rename(?,?,?)}",('xro_zips_import.CityAliasName', 'City', 'COLUMN'))
conn.commit()


text:
Q: How to select Default option (india) in Angular js? country names displaying using select box, select option coming from external json file. Based on selected country i am loading state json file into another select box,till every thing is ok, Now I need set Default selected country as INDIA, I tried bellow code.
html

         <select id="country" ng-init="state1 = options['IN']" style="width:250px;" class="" name="selectFranchise" ng-model="state1" ng-change="displayState(state1)">
             <option ng-repeat="(key,country) in countries"  value="{{key}}">{{country[0]}}</option>
          </select>

{{countries}}{{state1}}

         <select id="state" ng-model="cities">
             <option ng-repeat="(state,city) in states[state1]" value="{{city}}">{{city}}</option>
         </select>

script
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.states =  {
     "IN":[
       "Delhi",
       "Goa",
       "Gujarat",
       "Himachal Pradesh",
     ]
   };
   $scope.countries =  {
      IN: ["India"],
       ZA: ["South Africa"],
       AT: ["Austria"]
     }
    $scope.lastName = "Doe";
});

jsfiddle

A: Add this in the controller after defining your $scope.countries
$scope.state1 = Object.keys($scope.countries)[0];

Remove ng-init from Html page.


text:
Q: Like clause in JPA 2 TypedQuery works only for some name params and for others not I'm currently having a little issue with JPA 2 and Typed Query.
I'm creating a search feature in my project using LIKE clause, however when I try to search for a string like "marina" it no works, it works only when I type "marin", even when exists in the database the name marina.
This is my code:
StringBuilder builder = new StringBuilder("select u from User u"
                + " where (u.login LIKE :regex OR u.fullname LIKE :regex)"
                + " AND (u.status <> :status)"
                + " order by u.fullname");

        TypedQuery<User> query = jpaAPI.em().createQuery(builder.toString(),User.class);
        query.setParameter("status", statusTypeDeleted());
        query.setParameter("regex", "%"+regex+"%");
        query.setFirstResult(init);
        query.setMaxResults(end);

So, does anyone know where is the problem?

A: Ok. I solved this problem right now.
The problem is on this line:
query.setFirstResult(init);

The value I was passing to this method was 1 instead 0. How just exist only one entity with name "marina", the query result nothing, since the first result should be 0.


text:
Q: Map PHP named array to C# controller parameter I have a third party API with documentation for PHP, but I'm using C# and ASP.NET MVC.
One of API methods send as parameter Fields.
FIELDS is an array that contains field ID where int value is stored.
So in PHP it will be something like:
$fields=array(ID=>4);

What is the best way to get such a parameter to controller method in C#?
I'm doing it like this:
public class FieldsModel
{
    public int ID { get; set; }
}

[HttpPost]
public string Test(FieldsModel[] FIELDS)
{
   //some code goes here
}

This code is working, but maybe there is a better solution to map PHP named array to a C# controller parameter?
P.S. Actually FIELDS array always contains only one ID if it matters.

A: Due to php arrays can be used as key,value data structure, when it is serialized to JSON you get something similar to:
{
  "ID": 4
}

The easiest way to manage it in C# (knowing that C# is mainly used to write Object Oriented code), is to parse that JSON into an object, that contains a property for each JSON key. You can also, change use fields instead of properties like this:
public class FieldsModel
{
    public int ID;
}

However the second approach isnt' recommended.
I think that you are only going to get a "Field", so you can rewrite your Test endpoint to wait for a single FieldsModel, like this:
[HttpPost]
public string Test(FieldsModel fields)
{
   //some code goes here
}


text:
Q: Help translating this FH Bradley quote from English to Vulcan I'm confused at how to get the proper phrasing in Vulcan because the English grammar seems self-referencing for me to get the order right.
the quote by FH Bradley is:

The one self-knowledge worth having is to know one's own mind.

and wanted to translate it, but "worth having is" seems like three verbs in a row, then "one's own" seems like I could omit 'one's' and nam-tor can be stated by describing the noun.
Is it

Kerik ma fai-tukh t'shai goh fai-tor kashek t'du.

or am I missing it?