text:
Q: SQL Server on remote computer I have a SQL Server Express instance on a computer with IP 192.168.66 on a home network.
I have enabled TCP/IP on port 49170 and added the incoming rule on Windows firewall.
I have an application that I want to install on different computers inside my network. When I am testing my application in Visual Studio, I am not able to connect to my instance on the remote computer.
<connectionStrings>
    <add name="EquipamentoDal.Properties.Settings.ExtinguisherMngConnectionString"
         connectionString="Data Source=192.168.1.66,49170;Initial Catalog=ExtinguisherMng;Integrated Security=True"
         providerName="System.Data.SqlClient" />
 </connectionStrings>

The server name is DESKTOP-HU51203\EXPRESS.
What i have done wrong to not be able to connect?

A: Your connection string does not specify the Named Instance you're connecting to, it only specifies the IP address, which means any clients will connect to the default instance instead of a named instance.
By default SQL Server Express is configured differently to 'standard' versions of SQL Server (Standard, Workgroup, Developer, and  Enterprise Editions) as follows:

*

*Block incoming remote connections - this must be explictly enabled in the SQL Server Configuration Manager

*Use a Named Instance called SQLEXPRESS instead of being configured as the Default Instance

*SQL Server Express is also unique in supporting AttachDb and LocalDb - the other SKUs/Editions do not support the AttachDb and LocalDb features.

In your case, you've already enabled Remote Connections and you're not using AttachDb or LocalDb, so you just need to configure your client to connect to a named instance:
You specify the named instance in your connection string using the format <host>\<instance name>,<port> in the Data Source= or Server= parameter, e.g. Data Source=foo\SQLEXPRESS,1433, or in your particular case:
Data Source=192.168.1.66\SQLEXPRESS,49170;Initial Catalog=ExtinguisherMng;Integrated Security=True

You mentioned that you're doing this on a Home network, which means it's unlikely you're using an Active Directory or Kerberos, and given SQL Server Express does not expose the passwords it uses for its Service Identity (nor can users authenticate as NT AUTHORITY\NetworkService over the network it means you cannot use Integrated Security=True (or Integrated Security=SSPI which is equivalent, but SSPI is the preferred value), you will need to set an explicit SQL Server Login's username and password in your Connection String.

*

*Create a new Login object in the Server (you will need to login to the server first somehow, either locally or remotely using the sa account, if it exists)

*Specify the new Login's credentials by replacing Integrated Security=True with User Id=<userName>;Password=<password>;


text:
Q: How to display two decimal places when we type a value in a textbox? I would like to know how to display two decimal places when we type a value(money) in a text box.
private void txtAmountRecieved_TextChanged(object sender, EventArgs e)
{
    txtAmountRecieved.Text = Convert.ToDouble(txtAmountRecieved.Text)
        .ToString("#,0.00");
}

I tried above code. But when I type 1 value in textbox, cursor became in-front of value 1. So I cant type continuously in this textbox without interupt. And also an error occurred when I insert this value to database, which is

Input string was not in a correct format.

So how to solve this?

A: You can try this. Also you can specify the count after decimal you want
decimal amount= Math.Round(convert.todecimal(textbox.text)), 2);

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Developer Tool Log Window When export data in SQL Developer I get an extra pop up window that says "TOOL START" Export TOOL AT Date and Time. It does this for every export with a new window.

A: It's a bug.
For 18.4 you'll see complete export and other utilities information in the log panel.

It will show start time, number of records, stop time, and a link to the generated file.


text:
Q: Populate a select dropdown based on another select dropdown on Angular 14 so im trying to create a simple form with 2 select dropdowns.
one select for the countries.
one select for their states.
the idea is to display a list of countries and when one country is selected, the second select gets populated with its main states. ( and obv maintaining data-binding )
I tried to use a simple list of strings for the countries which i succeded to populate the first select dropdown ( although i could not do a placeholder for the select idk why )
after that i declared a second object list with the the cities of each country then do a filter function to filter out only the list of states that are matching the selected country but i could not get to populate the second select dropdown with it.
Here is a stackblitz demo which explains better.
Stackblitz

A: You are very close, you just need a proper filter function when the first dropdown has a value selected. Using an event like ngModelChange you can easily get the selected value and execute your filter to find the list of states.
component:
onCountrySelect(selectedCountry) {
    this.filteredStates = this.states.find(item => item.country === selectedCountry).stateList;
  }

html:
<form>
  <select name="countryName" [(ngModel)]="selectedCountry" (ngModelChange)="onCountrySelect($event)">
    <option *ngFor="let c of countries" value="{{ c }}">{{ c }}</option>
  </select>

  <select name="states" id="states" [(ngModel)]="selectedState">
    <option *ngFor="let s of filteredStates" value="{{ s }}">{{ s }}</option>
  </select>
</form>

Stackblitz demo


text:
Q: Google Drive API: The provided file ID is not usable What rules should I follow to set custom ID for File? I tried short "12345", "abcde", 44-character alphanumeric string, UUID.randomUUID().toString() (with/without dashes) - all attempts return "The provided file ID is not usable". I could not find any documented requirements. The code:
Drive drive = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credentials).build();
FileContent mediaContent = new FileContent("image/png", tempFile);
File body = new File();
body.setId(...);
body.setTitle(...);
body.setMimeType("image/png");
File result = drive.files().insert(body, mediaContent).execute();

The response:
400 Bad Request
{
    "code": 400,
    "errors":
    [{
        "domain": "global",
        "location": "file.id",
        "locationType": "other",
        "message": "The provided file ID is not usable",
        "reason": "invalid"
    }],
    "message": "The provided file ID is not usable"
}

The same code correctly uploads my file to Drive when I am not trying to set ID.

A: You can set the id, but you have to use a pre-generated id given to you by Google.
I had the same problem, so I dove into the javadoc, and stumbled upon the GeneratedIds Class. Here's the code that works for me:
    int numOfIds = 20;
    GeneratedIds allIds = null;
    try {
        allIds = driveService.files().generateIds()
                .setSpace("drive").setCount(numOfIds).execute();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    List<String> generatedFileIds = allIds.getIds();

A: You don't set the the ID, it is assigned by Google Drive at creation. The ID you are talking about is the string you see when you go to drive.google.com, right-click an object (folder/file), and select 'Get link'. You get something like:

https://drive.google.com/open?id=0B1blahblahblahblahfdR25i

and the string '0B1blahblahblahblahfdR25i' is the ID.
Test it. Get it from your drive.google.com, go to the bottom this page - TryIt!, paste the 0B1blahblahblahblahfdR25i into the fileId field.
Back to your problem. You are apparently trying to create a file, try this:
com.google.api.services.drive.Drive mGOOSvc:
...
/**************************************************************************
   * create file in GOODrive
   * @param prnId  parent's ID, (null or "root") for root
   * @param titl  file name
   * @param mime  file mime type
   * @param file  file (with content) to create
   * @return      file id  / null on fail
   */
  static String createFile(String prnId, String titl, String mime, java.io.File file) {
    String rsId = null;
    if (mGOOSvc != null && mConnected && titl != null && mime != null && file != null) try {
      File meta = new File();
      meta.setParents(Arrays.asList(new ParentReference().setId(prnId == null ? "root" : prnId)));
      meta.setTitle(titl);
      meta.setMimeType(mime);

      File gFl = mGOOSvc.files().insert(meta, new FileContent(mime, file)).execute();
      if (gFl != null)
        rsId = gFl.getId();
    } catch (Exception e) { UT.le(e); }
    return rsId;
  }

The return, the rsId is the ID you're looking for.
It is taken from an Android demo here (to explain the context), but the Api calls there should be pretty much the same. You can actually pull some CRUD primitives out of there.
Good Luck


text:
Q: Download file parts via FTP using VB.NET I need my program to download large files via FTP by specifying FTP username and password.
Also it must have "Pause" function, that's why I need my program to get file parts.
I use VB.NET and .NET 3.5 Framework. Is there any way to do it?

A: Download WinSCP from NuGet Package
Import WinSCP

Public Class fmbFtp

    Private Sub btnDownload_Click(sender As Object, e As EventArgs) Handles btnDownload.Click

        Try

            ' Setup session options

            Dim sessionOptions As New SessionOptions

            With sessionOptions
                .Protocol = Protocol.Sftp
                .HostName = "example.com"
                .UserName = "UserName"
                .Password = "Password"
                'telnet command to get key
                'ssh-keygen - l - f / etc / ssh / ssh_host_rsa_key
                .SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"

            End With

            Using session As New Session

                ' Connect

                session.Open(sessionOptions)

                ' Upload files

                Dim transferOptions As New TransferOptions
                transferOptions.TransferMode = TransferMode.Binary

                Dim transferResult As TransferOperationResult
                transferResult = session.GetFiles("/path/filename.txt", My.Computer.FileSystem.CurrentDirectory)
                ' Throw on any error
                transferResult.Check()
                ' Print results
                For Each transfer In transferResult.Transfers
                    Console.WriteLine("Upload of {0} succeeded", transfer.FileName)
                Next
            End Using
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class

A: You can use FtpWebRequest like this :
Dim request As System.Net.FtpWebRequest =   DirectCast(System.Net.WebRequest.Create("FTP Path along with destination file name"), System.Net.FtpWebRequest)
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile

request.Credentials = New System.Net.NetworkCredential("username", "password")

Dim file() As Byte = System.IO.File.ReadAllBytes("path of file to be copied")

Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()

This works for me.


text:
Q: linux Using system("ping") blocked in daemon process In my daemon process,I try to use ping to detect host is alive.
code:
sprintf(pingCmd,"ping -c1 -t%d %s",time,ip);
if (system(pingCmd)) {
    //fail
}
else {
    //success
}

but when I remove the destination host network cable.
My daemon process will blocking at system()
#0  0x00007f75362fbc7d in waitpid () from /lib/x86_64-linux-gnu/libc.so.6
#1  0x00007f7536281f5e in ?? () from /lib/x86_64-linux-gnu/libc.so.6
#2  0x00007f7536282370 in system () from /lib/x86_64-linux-gnu/libc.so.6

so  I write anthor program, not a daemon
the code not be blocking at sysem(),
even i remove the destionation host network cable,
how to using system("ping") at daemon process

A: The problem is that the ping command is blocking.  Try the exact same ping command from the command-line to see the result.
By the way, I highly recommend implementing the ping itself inside the daemon - you'll run into far fewer problems.  Running a command through the system() function introduces a lot of complexity that can confuse and cause incorrect results.
With that said, to get this working, find the right ping command, with the correct arguments, to do the job, by testing from the command-line.  Make sure to check for timeouts as well.


text:
Q: Double Integral Over A Cylinder Not Centered On The Origin Given the formula: $$x^2+y^2+z^2=a^2$$
Which is bounded by: $$x^2+y^2=ax$$ and $$z = 0$$
I need to find the surface area but I'm having trouble figuring out the domain. I'm using :$z=\sqrt{a^2-x^2-y^2}$ since that acounts for the bound of $z=0$. I know I need to use the forumula: $S(A)=\int\int\sqrt{F_x^2+F_y^2+1}\,\mathrm{d}A$. So, I've found $F_x=-x(a^2-x^2-y^2)^{1/2}$ and $F_y=-y(a^2-x^2-y^2)^{1/2}$. How do I figure out the domain? The $x$ times the constant $a$ is throwing me off in $x^2+y^2=ax$.
My Incorrect Solution in Polar Coordinates:$$S(A)=\int_{-\pi/2}^{\pi/2}\int_0^{a\cos(\theta)}\sqrt{x^2(a^2-x^2-y^2)+y^2(a^2-x^2-y^2)+1}\,r\mathrm{d}r\mathrm{d}\theta$$
I converted $x^2+y^2=ax$ into polar co-ordinates and I solved for $r$ to get $r=acos(\theta)$ but for some reason this is not the proper limit of integration, I'm stumped about what the proper limit of integration for $r$ should be.


text:
Q: Manipulation of Word Document using OOXML? We have a requirement to read Word document and make changes to it with dynamic data from Application & some sections that will be updated by the user directly into the word.
Every time the user wants to fetch data from Application, he will upload the document and merge it.
To be more specific, I looked into option of manipulating the word document by adding meta tags as markers in the ooxml for each section. But i am not able to find any.Is there an option to add meta tags for content, which can act like template markers?
Note: We want to implement this in a Java application.

A: You can use special Java Library: http://poi.apache.org/ Apache POI to manipulate DOC files, but for template you need different system like velocity or freemarker. Or you can just use String replace.


text:
Q: Run bash script from another script without waiting for script to finish executing? Is there any way to execute two bash scripts without the first one blocking? The following does not work:
exec ./script1.sh #this blocks!
exec ./script2.sh

A: Put & at the end of the line.
./script1.sh & #this doesn't blocks!
./script2.sh

A: Run the first one in background using & and you should be good.


text:
Q: How can I make a 3D plot of a piecewise function of two variables? I am trying to plot the following function in MATLAB:

The goal is to stitch all of the different conditions into one graph to make an overall CDF graph. What I have tried so far is the following:
x=linspace(0,1,20);
y=linspace(0,1,20);
Z=x.^y;
plot3(x,y,Z)
hold on
plot3(x,0,0);
plot3(0,y,0);

I am unsure of how to graph 1 for x>1, y>1 and also if there is a way to make the plot a solid surface for this set of conditions. I have tried using the rand() generator to produce 20+ numbers between 0 and 1, which shows the area that the variables could be located. However, it looks messy when it's a scatter of lines in a given area. I would rather it be a solid surface.
Is there a specific command I can use for this? I have seen in some examples using Mesh() to make the graph solid but am not sure if this would work for the set of data.

A: You can accomplish this by generating a regular grid of x and y values with meshgrid, modifying values in Z with logical indexing, and displaying the result with surf:
% Grid points spanning from -1 to 2 for x and y:
[x, y] = meshgrid(linspace(-1, 2, 91));

% Fill Z with zeroes to start (satisfies condition 1 by default):
Z = zeros(size(x));

% Condition 2:
index = (x >= 0) & (x <= 1) & (y >= 0) & (y <= 1);
Z(index) = x(index).*y(index);

% Condition 3:
index = (x >= 0) & (x <= 1) & (y > 1);
Z(index) = x(index);

% Condition 4:
index = (y >= 0) & (y <= 1) & (x > 1);
Z(index) = y(index);

% Condition 5:
Z((x > 1) & (y > 1)) = 1;

% Plot surface:
surf(x, y, Z, 'EdgeColor', 'none');

Note: This assumes that unspecified conditions, like (x < 0 and y > 1) and (y < 0 and x > 1), should be zero as well.


text:
Q: How can I bypass the Complete Action Using menu when using an implicit intent filter? I'm attempting to launch my app automatically when visiting a URL (test.com) in this example
however every time I do so I am asked which application I should use to do so. I'd like a way to launch my app every time without prompting for user interaction.
I've done research into how this can be done and have found the following:
Android Eliminate Complete Action Using dialog
But if I implement an explicit intent instead of an implicit intent - how do I specify to launch my activity when visiting test.com since I wont be using
<data android:scheme="http" android:host="test.com" android:pathPrefix="/" />

IMPLICIT INTENT (works successfully - launches app when visiting test.com but prompts user to select app - which is undesired - need to launch my app without the complete action using prompt)
<activity android:name="com.nfc.linked.Warning">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"></action>
        <category android:name="android.intent.category.LAUNCHER"></category>
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.VIEW"></action>
        <category android:name="android.intent.category.DEFAULT"></category>
        <category android:name="android.intent.category.BROWSABLE"></category>
        <data android:scheme="http" android:host="test.com" android:pathPrefix="/" />
    </intent-filter>
</activity>

EXPLICIT INTENT (ATTEMPT):
public class Warning extends Activity {

    Intent intent = new Intent(this, Warning.class);
    startActivity(intent);

}

A: You can't.
What you call an Explicit Intent targets exactly one class.
What you've done earlier is to create an intent-filter in your manifest, which listens for Intents related to a URL along the lines of http://*.test.com/*. However, since HTTP is a very common protocol, and your URI is simply a website, other apps like browsers which listen for URLs like http://* will also offer to show the content. Due to this, Android creates a chooser, from which the user must select your app.
The only way around this is to have a button which opens the chooser for http://test.com in your app, ask the user to press it and choose your app as the default handler for such URLs. It cannot be done programmatically for security reasons, as then malicious apps can set themselves as the default for various actions.
Another option would be to come up with your own URI scheme, like Google Play's market://. As your app will be the only one using this, it will be the only one available to handle the link. However, you will need to make sure all third parties trying to open your app through another place (like a link on a webpage or from another app) follow your URL scheme. Additionally, if a user presses one of the third party links and your app is not installed, it will likely result in an ActivityNotFoundException on the user's device.


text:
Q: Mock alert with fn() from another function I have a file1.js with a function that fires up alert():
file1.js
export function test(value){
  alert(value); //string
}

file1.test.js:
import { test } from "./test";
...
it("returns value", () => {

  window.alert = jest.fn();
  test(10);
  expect(window.alert).toHaveBeenCalledWith("10");
});

Could someone point me out how to get the alert called?

A: What you're doing is mocking a function, which you can view how to do in this link here.
When you mock a function, you're essentially obtaining the instance(s) of the said functions. You may also find that using the jest.spyOn() function will also help too and more or less does the same thing.
Another thing to note is that you're testing what the function does, which is how I undergo writing my unit tests. This pattern is known as AAA (Arrange, Act, Assert) which you should read up on in this link.
-Ehsan

A: In Codesandbox instead of alert() it should be window.alert()


text:
Q: Amarok in kubuntu 19.04 I just have upgraded from kubuntu 18.10 to 19.04 and I found Amarok player has disappeared!
How could I install it again?
Thanks!

A: I tried to create an AppImage from deb files with pkg2appimage.
amarok.yml
app: Amarok
ingredients:
  dist: disco
  packages:
    - amarok
  sources:
    - deb http://archive.ubuntu.com/ubuntu/ disco main universe
    - deb http://archive.ubuntu.com/ubuntu/ bionic main universe

Then run bash -ex ./pkg2appimage amarok.yml (with https://github.com/AppImage/pkg2appimage/blob/master/pkg2appimage)
The result is an AppImage that runs on a system with Amarok installed but not if not installed (native).
My solution for now is to add the bionic tls sources again and install amarok from there. This is not a very clean solution but the simplest for now.
Add to /etc/apt/sources.list:
deb http://archive.ubuntu.com/ubuntu/ bionic main universe
deb-src http://archive.ubuntu.com/ubuntu/ bionic main universe

Then run apt-get update and apt-get install amarok.


text:
Q: Add map as drilldown for pie chart I have a pie chart and I want to add map drilldown series. How?
http://jsfiddle.net/u03oddrg/1/
$('#things-in-brazil').highcharts({
    chart: { type: 'pie'},
    series: [{
        name: 'Things in Brazil',
        data: [
            { name: 'Thing 1', y: 1500 },
            { name: 'Thing 2', y: 2600 }
        ]
    }]
});

var data_for_thing1 = [
    { "hc-key": "br-pa", value: 110 },
    { "hc-key": "br-sc", value: 210 },
    { "hc-key": "br-ap", value: 340 },
    { "hc-key": "br-ba", value: 480 },
    { "hc-key": "br-mt", value: 90 }
];
$('#thing1-by-state').highcharts('Map', {
    mapNavigation: { enabled: false },
    series : [{
        data : data_for_thing1,
        mapData: Highcharts.maps['countries/br/br-all'],
        joinBy: 'hc-key',
        name: 'Thing 1',
        states: { hover: { color: '#BADA55' } },
        dataLabels: { enabled: true, format: '{point.name}' }
    }]
});


text:
Q: find a curve through a point cloud (gps-tracks) i have some gps-tracks (list of lat/lon, no altitude required) in python on the same route (3km). When plotting all tracks with scatter, you can see the deviation of the tracks.
I want to get the "middle" of the tracks to have a basic route from all tracks. Therefore i did some research about possible methods, but could not find a proper way. Or it is way to difficult for my programming skills.
Is there a way with python to mix all points together and get a b-spline or so, that gives me a way?
Thanks


text:
Q: How to persist state between tabs (TabBar) in Flutter? I have a TabBarView with 3 TabBar. When I'm in tab 1 I do something, then I navigate to tab 2 when I come back to tab 1 I want to the previous state of tab 1 will not change.
How can I achieve this in Flutter?
Below is my code screenshot
class _LandingPageState extends State<LandingPage> with SingleTickerProviderStateMixin {
  int _selectedIndex = 0;
  PageController pageController;
  TabController tabController;

  @override
  void initState() {
    tabController = TabController(length: 3, vsync: this, initialIndex: 0);
    pageController = PageController(initialPage: 0)
      ..addListener(() {
        setState(() {
          _selectedIndex = pageController.page.floor();
        });
      });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
              bottomNavigationBar: BottomNavigationBar(
              currentIndex: _selectedIndex,
              onTap: (index) {
                setState(() {
                  _selectedIndex = index;
                  tabController.animateTo(index,
                      duration: Duration(microseconds: 300),
                      curve: Curves.bounceIn);
                });
              },
              items: [
                BottomNavigationBarItem(
                    icon: Icon(Icons.assignment), title: Text("Các yêu cầu")),
                BottomNavigationBarItem(
                    icon: Icon(Icons.history), title: Text("Lịch sử")),
                BottomNavigationBarItem(
                    icon: Icon(Icons.person), title: Text("Hồ sơ")),
              ]),
          body: TabBarView(
              controller: tabController,
              children: [
                RequestPage(key: PageStorageKey<String>("request_page"),),
                HistoryPage(key: PageStorageKey<String>("history_page")),
                ProfilePage(key: PageStorageKey<String>("profile_page"))])
          ),
    );
  }

A: Make sure that all of your TabBarView children are StatefulWidgets and then add a AutomaticKeepAliveClientMixin like so in all of them, for example, for your RequestPage, it should look like this:
class RequestPage extends StatefulWidget {
  RequestPage({Key key}) : super(key: key);

  @override
  _RequestPageState createState() => _RequestPageState();
}

class _RequestPageState extends State<RequestPage> with AutomaticKeepAliveClientMixin{
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return // Your widget tree
  }

  @override
  bool get wantKeepAlive => true;
}

A: Try AutomaticKeepAliveClientMixin and override wantKeepAlive to always return true

A: As the body of Scaffold Use IndexedStack to preserve state. Example :
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          bottomNavigationBar: BottomNavigationBar(
            onTap: (index) {
              setState(() {
                _selectedIndex = index;
              });
            },
            currentIndex: _selectedIndex,
            items: [
              BottomNavigationBarItem(
                ...
              ),
              BottomNavigationBarItem(
                ...
              ),
            ],
          ),
          body: IndexedStack(
            children: <Widget>[
              PageOne(),
              PageTwo(),
            ],
            index: _selectedIndex,
          ),
        );
      }


text:
Q: What does 'Nice' mean on the processes tab What does the 'Nice' column represent on the processes tab of the system monitor?

A: Nice is not simply priority multiplied by minus one.
You will find that on unix/linux systems that if a task is hogging the processor, then the system does not grind to a halt. This is because the system will dynamically lower this tasks priority.
The niceness influences the base priority.
So while niceness can be thought of as negative priority, it will have less effect than priority would have on a Microsoft NT system, as the Linux scheduler is already doing a good job at keeping things nice.

A: 'nice' refers to the priority the process gets on your CPU. This is a number in the range of -20 (highest priority) to 19 (lowest). You'll probably find that most applications you're running are at nice '0', which means that they are running with normal priority and none will get preferential treatment by the scheduler over another.
If you're running an intensive program, you may wish to launch it from a terminal with nice -n 10 /path/to/program. That way it will impact less on the performance of your system.
Note that you need root (sudo) privileges to schedule a process with priority greater than normal (<0). This is to prevent users from being able to bog down the entire system easily, and so that critical tasks can always receive the CPU time they require.
There's a good explanation on Wikipedia too.


text:
Q: Finding the values of k for an equation which is a tangent to a curve I have been faced with the following question:

Find the values of $k$ for which $y = kx - 2$ is a tangent to the curve
  $y = x^2 - 8x + 7$

I managed to figure this out by treating them as simultaneous equations and then calculating the discriminant so that k either has the value $-14$ or $-2$ however I was wondering if there was another possible method to answer this perhaps by way of differentiation.
EDIT
And using differentiation how is it possible to get the answer that k is either $-14$ or $-2$?

A:
Find the values of $k$ for which $y = kx - 2$ is a tangent to the curve
  $y = x^2 - 8x + 7$

*

*Where do the equations intersect? Solve for $kx - 2 = x^2 - 8x + 7$.

*Where is the slope of the line $y = kx - 2$ $\Big($ Slope = $ \frac{d}{dx}(kx - 2) = k\Big)\;$ equal to $\;\frac{d}{dx}(x^2 - 8x + 7) = 2x - 8\;$?

A: HINT
For the graphs $y=f(x)$ and $y=g(x)$ to be tangent at $x=a$ you need
$$f(a)=g(a)\text{ and }g'(a)=f'(a).$$

A: Hint: The tangent at $(a,b)$ is $y=(2a-8)(x-a)+b$.

 Since $(a,b)$ is a point on the parabola, we have $b=a^2-8a+7$. Hence the tangent equation is $y=(2a-8)x-a^2+7$, i.e. $k=2a-8$ and $a^2-7=2$.


text:
Q: HAProxy health check not working but CURL returns 200 OK I have a HAProxy health check configured with the following backend:
backend php_servers
   http-request set-header X-Forwarded-Port %[dst_port]
   option httpchk get /health
   http-check expect status 200
   server php1 internal_ip:80 check

HAProxy doesn't enable the server but when using CURL I receive a 200 OK response.
Command: curl -I internal_ip/health
Response:
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 01 Dec 2016 20:53:48 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Access-Control-Allow-Origin: api.flex-appeal.nl
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-transform

Why doesn't HAProxy recognize the servers as "UP"? Seems I can connect just fine.

A: The correct HTTP verb is GET, not get:
option httpchk GET /health

You can also check/enable the stats page: on the LastChk column you will see why the check fails. In my case, I get a 501 Not Implemented response.
I can reproduce it by doing the same request as HAProxy:
$ telnet localhost 80
Trying ::1...
Connected to localhost.
Escape character is '^]'.
get /health HTTP/1.0

HTTP/1.1 501 Not Implemented
Date: Thu, 01 Dec 2016 21:53:09 GMT
Server: Apache/2.4.23 (Unix) PHP/7.0.13
[...]


text:
Q: Vue.js componente con inputs Estoy creando un componente con vue.js que contiene varios inputs. Quiero crear un botón que al ser presionado me agregue un nuevo componente (sin refrescar los anteriores componentes que tengo creados en el DOM). Cómo podría hacerlo, tengo el siguiente código del componente

  <button @click="addComponent">
    add component
  </button>
  <todo-item v-for="(component, index) in components" :key="index"/>


text:
Q: How to query by multiple conditions in faunadb? I try to improve my understanding of FaunaDB.
I have a collection that contains records like:
{
  "ref": Ref(Collection("regions"), "261442015390073344"),
  "ts": 1587576285055000,
  "data": {
    "name": "italy",
    "attributes": {
      "amenities": {
        "camping": 1,
        "swimming": 7,
        "hiking": 3,
        "culture": 7,
        "nightlife": 10,
        "budget": 6
      }
    }
  }
}

I would like to query in a flexible way by different attributes like:

*

*data.attributes.amenities.camping > 5

*data.attributes.amenities.camping > 5 AND data.attributes.amenities.hiking > 6

*data.attributes.amenities.camping < 6 AND data.attributes.amenities.culture > 6 AND hiking > 5 AND ...

I created an index containing all attributes, but I don't know how to do greater equals filtering in an index that contains multiple terms.
My fallback would be to create an index for each attribute and use Intersection to get the records that are in all subqueries that I want to check, but this feels somehow wrong:
The query: budget >= 6 AND camping >=8 would be:
Index:
{
  name: "all_regions_by_all_attributes",
  unique: false,
  serialized: true,
  source: "regions",
  terms: [],
  values: [
    {
      field: ["data", "attributes", "amenities", "culture"]
    },
    {
      field: ["data", "attributes", "amenities", "hiking"]
    },
    {
      field: ["data", "attributes", "amenities", "swimming"]
    },
    {
      field: ["data", "attributes", "amenities", "budget"]
    },
    {
      field: ["data", "attributes", "amenities", "nightlife"]
    },
    {
      field: ["data", "attributes", "amenities", "camping"]
    },
    {
      field: ["ref"]
    }
  ]
}

Query:
Map(
  Paginate(
    Intersection(
      Range(Match(Index("all_regions_by_all_attributes")), [0, 0, 0, 6, 0, 8], [10, 10, 10, 10, 10, 10]),
    )

  ),
  Lambda(
    ["culture", "hiking", "swimming", "budget", "nightlife", "camping", "ref"],
    Get(Var("ref"))
  )
)

This approach has the following disadvantages:

*

*It does not work like expected, if for example the first (culture) attribute is in this range, but the second (hiking) not, then I would still get a return values

*It causes a lot of reads due to the reference that I need to follow for each result.

Is it possible to store all values in this kind of index that would contain all the data? I know I can just add more values to the index and access them. But this would mean I have to create a new index as soon as we add more fields to the entity. But maybe this is a common thing.
thanks in advance

A: There are a couple of misconceptions that I think are leading you astray. The most important one: Match(Index($x)) generates a set reference, which is an ordered set of tuples. The tuples correspond to the array of fields that are present in the values section of an index. By default this will just be a one-tuple containing a reference to a document in the collection selected by the index. Range operates on a set reference and knows nothing about the terms used to the select the returned set ref. So how do we compose the query?
Starting from first principles. Lets imagine we just had this stuff in memory. If we had a set of (attribute, scores) ordered by attribute, score then taking only those where attribute == $attribute would get us close, and then filtering by score > $score would get us what we wanted. This corresponds exactly to a range query over scores with attributes as terms, assuming we modeled the attribute value pairs as documents. We can also embed pointers back to the location so we can retrieve that as well in the same query. Enough chatter, lets do it:
First stop: our collections.
jnr> CreateCollection({name: "place_attribute"})
{
  ref: Collection("place_attribute"),
  ts: 1588528443250000,
  history_days: 30,
  name: 'place_attribute'
}
jnr> CreateCollection({name: "place"})
{
  ref: Collection("place"),
  ts: 1588528453350000,
  history_days: 30,
  name: 'place'
}

Next up some data. We'll chose a couple of places and give them some attributes.
jnr> Create(Collection("place"), {data: {"name": "mullion"}})
jnr> Create(Collection("place"), {data: {"name": "church cove"}})
jnr> Create(Collection("place_attribute"), {data: {"attribute": "swimming", "score": 3, "place": Ref(Collection("place"), 264525084639625739)}})
jnr> Create(Collection("place_attribute"), {data: {"attribute": "hiking", "score": 1, "place": Ref(Collection("place"), 264525084639625739)}})
jnr> Create(Collection("place_attribute"), {data: {"attribute": "hiking", "score": 7, "place": Ref(Collection("place"), 264525091487875586)}})

Now for the more interesting part. The index.
jnr> CreateIndex({name: "attr_score", source: Collection("place_attribute"), terms:[{"field":["data", "attribute"]}], values:[{"field": ["data", "score"]}, {"field": ["data", "place"]}]})
{
  ref: Index("attr_score"),
  ts: 1588529816460000,
  active: true,
  serialized: true,
  name: 'attr_score',
  source: Collection("place_attribute"),
  terms: [ { field: [ 'data', 'attribute' ] } ],
  values: [ { field: [ 'data', 'score' ] }, { field: [ 'data', 'place' ] } ],
  partitions: 1
}

Ok. A simple query. Who has Hiking?
jnr> Paginate(Match(Index("attr_score"), "hiking"))
{
  data: [
    [ 1, Ref(Collection("place"), "264525084639625730") ],
    [ 7, Ref(Collection("place"), "264525091487875600") ]
  ]
}

Without too much imagination one could sneak a Get call into that to pull the place out.
What about only hiking with a score over 5? We have an ordered set of tuples, so just supplying the first component (the score) is enough to get us what we want.
jnr> Paginate(Range(Match(Index("attr_score"), "hiking"), [5], null))
{ data: [ [ 7, Ref(Collection("place"), "264525091487875600") ] ] }

What about a compound condition? Hiking under 5 and swimming (any score). This is where things take a bit of a turn. We want to model conjunction, which in fauna means intersecting sets. The problem we have is that up until now we have been using an index that returns the score as well as the place ref. For intersection to work we need just the refs. Time for a sleight of hand:
jnr> Get(Index("doc_by_doc"))
{
  ref: Index("doc_by_doc"),
  ts: 1588530936380000,
  active: true,
  serialized: true,
  name: 'doc_by_doc',
  source: Collection("place"),
  terms: [ { field: [ 'ref' ] } ],
  partitions: 1
}

What's the point of such an index you ask? Well we can use it to drop any data we like from any index and be left with just the refs via join. This gives us the place refs with a hiking score less than 5 (the empty array sorts before anything, so works as a placeholder for a lower bound).
jnr> Paginate(Join(Range(Match(Index("attr_score"), "hiking"), [], [5]), Lambda(["s", "p"], Match(Index("doc_by_doc"), Var("p")))))
{ data: [ Ref(Collection("place"), "264525084639625739") ] }

So finally the piece de resistance: all places with swimming and (hiking < 5):
jnr> Let({
...   hiking: Join(Range(Match(Index("attr_score"), "hiking"), [], [5]), Lambda(["s", "p"], Match(Index("doc_by_doc"), Var("p")))),
...   swimming: Join(Match(Index("attr_score"), "swimming"), Lambda(["s", "p"], Match(Index("doc_by_doc"), Var("p"))))
... },
... Map(Paginate(Intersection(Var("hiking"), Var("swimming"))), Lambda("ref", Get(Var("ref"))))
... )
{
  data: [
    {
      ref: Ref(Collection("place"), "264525084639625739"),
      ts: 1588529629270000,
      data: { name: 'mullion' }
    }
  ]
}

Tada. This could be neatened up a lot with a couple of udfs, exercise left to the reader. Conditions involving or can be managed with union in much the same way.

A: Thanks for your question. Ben already wrote out a complete example that shows what you can do and I'll base myself on his recommendations and try to clarify further.
FaunaDB's FQL is quite powerful which means there are multiple ways to do that, yet with such power comes a small learning curve so I'm happy to help :). The reason it took a while to answer this question is that such an elaborate answer actually deserves a complete blog post. Well, I've never written a blog post in Stack Overflow, there is a first for everything!
There are three ways to do 'compound range-like queries' but there is one way that will be most performant for your use-case and we'll see that the first approach is actually not entirely what you need. Spoiler, the third option we describe here is what you need.
Preparation - Let's throw in some data just like Ben did
I'll keep it in one collection to keep it simpler and am using the JavaScript flavour of the Fauna Query Language here. There is a good reason to separate data in a second collection though which is related to your second map/get question (see the end of this answer)
Create the collection
 CreateCollection({ name: 'place' })

Throw in some data
    Do(
      Select(
        ['ref'],
        Create(Collection('place'), {
          data: {
            name: 'mullion',
            focus: 'team-building',
            camping: 1,
            swimming: 7,
            hiking: 3,
            culture: 7,
            nightlife: 10,
            budget: 6
          }
        })
      ),
      Select(
        ['ref'],
        Create(Collection('place'), {
          data: {
            name: 'church covet',
            focus: 'private',
            camping: 1,
            swimming: 7,
            hiking: 9,
            culture: 7,
            nightlife: 10,
            budget: 6
          }
        })
      ),
      Select(
        ['ref'],
        Create(Collection('place'), {
          data: {
            name: 'the great outdoors',
            focus: 'private',
            camping: 5,
            swimming: 3,
            hiking: 2,
            culture: 1,
            nightlife: 9,
            budget: 3
          }
        })
      )
    )

OPTION 1: Composite indexes with multiple values
We can put as many terms as values in an index and use Match and Range to query those. However! Range probably gives you something different than you would expect if you use multiple values. Range gives you exactly what the index does and the index sorts values lexically. If we look at the example of Range in the docs we see an example there which we can extend upon for multiple values.
Imagine we would have an index with two values and we write:
    Range(Match(Index('people_by_age_first')), [80, 'Leslie'], [92, 'Marvin'])

Then the result will be what you see on the left and not what you see on the right. This is a very scalable behaviour and exposes the raw-power without overhead of the underlying index but is not exactly what you are looking for!

So let's move on to another solution!
OPTION 2: First Range, then Filter
Another quite flexible solution is to use Range and then Filter. This however is a less good idea in case you are filtering out a lot with filter since your pages will become more empty. Imagine that you have 10 items in a page after the 'Range' and use filter, then you will end up with pages of 2, 5, 4 elements depending on what is filtered out. This is a great idea however if one of these properties has such a high cardinality that it will filter out most of entities. E.g. imagine everything is timestamped, you want to first get a date range and then continue filtering something that will only eliminate a small percentage of the resultset.  I believe that in your case all of these values are quite equal so this the third solution (see lower) will be the best for you.
We could in this case just throw all values in so that they all get returned which avoids a Get. For example, let's say that 'camping' is our most important filter.
    CreateIndex({
      name: 'all_camping_first',
      source: Collection('place'),
      values: [
        { field: ['data', 'camping'] },
        // and the rest will not be used for filter
        // but we want to return them to avoid Map/Get
        { field: ['data', 'swimming'] },
        { field: ['data', 'hiking'] },
        { field: ['data', 'culture'] },
        { field: ['data', 'nightlife'] },
        { field: ['data', 'budget'] },
        { field: ['data', 'name'] },
        { field: ['data', 'focus'] },
      ]
    })

You can now write a query that just gets a range based on the camping value:
    Paginate(Range(Match('all_camping_first'), [1], [3]))

Which should return two elements (the third has camping === 5)
Now imagine that we want to filter over these and we set our pages small to avoid unnecessary work
    Filter(
      Paginate(Range(Match('all_camping_first'), [1], [3]), { size: 2 }),
      Lambda(
        ['camping', 'swimming', 'hiking', 'culture', 'nightlife', 'budget', 'name', 'focus'],
        And(GTE(Var('hiking'), 0), GTE(7, Var('hiking')))
      )
    )

Since I want to be clear on both the advantages as disadvantages of each approach, let's show exactly how filter works by adding another one that has attributes that match our query.
    Create(Collection('place'), {
      data: {
        name: 'the safari',
        focus: 'team-building',
        camping: 1,
        swimming: 9,
        hiking: 2,
        culture: 4,
        nightlife: 3,
        budget: 10
      }
    })

Running the same query:
    Filter(
      Paginate(Range(Match('all_camping_first'), [1], [3]), { size: 2 }),
      Lambda(
        ['camping', 'swimming', 'hiking', 'culture', 'nightlife', 'budget', 'name', 'focus'],
        And(GTE(Var('hiking'), 0), GTE(7, Var('hiking')))
      )
    )

Now still returns only one value but provides you with an 'after' cursor that points to the next page. You might think: "huh? My page size was 2?". Well that's because Filter works after Pagination and your page originally had two entities from which one got filtered out. So you are left with a page of 1 value and a pointer to the next page.

{
  "after": [
    ...
  ],
  "data": [
    [
      1,
      7,
      3,
      7,
      10,
      6,
      "mullion",
      "team-building"
    ]
  ]

You could also opt to Filter directly on the SetRef as well and only paginate afterwards. In that case, the size of your pages will contain the required size. However, keep in mind that this is an O(n) operation on the amount of elements that comes back from Range. Range uses an index but from the moment you use Filter, it will loop over each of the elements.
OPTION 3:  Indexes on one value + Intersections!
This is the best solution for your use-case but it requires a bit more understanding and an intermediate index.
When we look at the doc examples for intersection we see this example:
    Paginate(
       Intersection(
          Match(q.Index('spells_by_element'), 'fire'),
          Match(q.Index('spells_by_element'), 'water'),
       )
    )

This works because it's two times the same index and that means that **the results are similar values ** (references in this case).
Let's say we add a few indexes.
    CreateIndex({
      name: 'by_camping',
      source: Collection('place'),
      values: [
        { field: ['data', 'camping']}, {field:  ['ref']}
      ]
    })

    CreateIndex({
      name: 'by_swimming',
      source: Collection('place'),
      values: [
        { field: ['data', 'swimming']}, {field:  ['ref']}
      ]
    })

    CreateIndex({
      name: 'by_hiking',
      source: Collection('place'),
      values: [
        { field: ['data', 'hiking']}, {field:  ['ref']}
      ]
    })

We can intersect on them now but it will not give us the right result. For example... let's call this:
    Paginate(
      Intersection(
        Range(Match(Index("by_camping")), [3], []),
        Range(Match(Index("by_swimming")), [3], [])
      )
    )

The result is empty. Although we had one with swimming 3 and camping 5.
That is exactly the problem. If swimming and camping were both the same value we would get a result. So it's important to notice that Intersection intersects the values, so that includes both the camping/swimming value as well as the reference. That means that we have to drop the value since we only need the reference. The way to do that before pagination is with a join, Essentially we are going to join with another index that is going to just.. return the ref (not specifying values defaults to only the ref)
CreateIndex({
  name: 'ref_by_ref',
  source: Collection('place'),
  terms: [{field:  ['ref']}]
})

This join looks as follows
    Paginate(Join(
      Range(Match(Index('by_camping')), [4], [9]),
      Lambda(['value', 'ref'], Match(Index('ref_by_ref'), Var('ref'))
    )))

Here we just took the result of Match(Index('by_camping')) and just dropped the value by joining with an index that only returns the ref. Now let's combine this and just do an AND kind of range query ;)
    Paginate(Intersection(
      Join(
        Range(Match(Index('by_camping')), [1], [3]),
        Lambda(['value', 'ref'], Match(Index('ref_by_ref'), Var('ref'))
      )),
      Join(
        Range(Match(Index('by_hiking')), [0], [7]),
        Lambda(['value', 'ref'], Match(Index('ref_by_ref'), Var('ref'))
      ))
    ))

The result is two values, and both in the same page!
Note that you can easily extend or compose FQL by just using the native language (in this case JS) to make this look much nicer (note I didn't test this piece of code)
    const DropAllButRef = function(RangeMatch) {
      return Join(
        RangeMatch,
        Lambda(['value', 'ref'], Match(Index('ref_by_ref'), Var('ref'))
      ))
    }

    Paginate(Intersection(
      DropAllButRef (Range(Match(Index('by_camping')), [1], [3])),
      DropAllButRef (Range(Match(Index('by_hiking')), [0], [7]))
    ))

And a final extension, this only returns indexes so you'll need to map get. There is of course a way around this if you really want to by.. just using another index :)
    const index = CreateIndex({
      name: 'all_values_by_ref',
      source: Collection('place'),
      values: [
        { field: ['data', 'camping'] },
        { field: ['data', 'swimming'] },
        { field: ['data', 'hiking'] },
        { field: ['data', 'culture'] },
        { field: ['data', 'nightlife'] },
        { field: ['data', 'budget'] },
        { field: ['data', 'name'] },
        { field: ['data', 'focus'] }
      ],
      terms: [
        { field: ['ref'] }
      ]
    })

Now you have the range query, will get everything without a map/get:
  Paginate(
    Intersection(
      Join(
        Range(Match(Index('by_camping')), [1], [3]),
        Lambda(['value', 'ref'], Match(Index('all_values_by_ref'), Var('ref'))
      )),
      Join(
        Range(Match(Index('by_hiking')), [0], [7]),
        Lambda(['value', 'ref'], Match(Index('all_values_by_ref'), Var('ref'))
      ))
    )
  )

With this join approach you could even do range indexes on different collections as long as you join them to the same reference before intersecting! Pretty cool huh?
Can I store more values in the index?
Yes you can, indexes in FaunaDB are views, so let's call them indiviews. It's a tradeoff, essentially you are exchanging compute for storage. By making a view with many values you get very fast access to a certain subset of your data. But there is another tradeoff and that is flexibility. You can not just go adding elements since that would require you to rewrite your whole index. In that case you will have to make a new index and wait for it to build if you have much data (and yes, that is quite common) and make sure that the queries you do (look at the lambda parameters in map filter) match your new index. You can always delete the other index afterwards. Just using Map/Get will be more flexible, everything in databases is a tradeoff and FaunaDB gives you both options :). I would suggest to use such an approach from the moment your datamodel is fixed and you see a specific part in your app that you want to optimise.
Avoiding MapGet
The second question on Map/Get requires some explanation. Separating out the values that you will search on from the places (as Ben did) is a great idea if you want to use Join to get the actual places more efficiently. This will not require a Map Get and therefore cost you far less reads but do notice that Join is rather a traverse (it'll replace the current references with the target references it joins to) so if you need both the values and the actual place data in one object at the end of your query than you will require Map/Get. Look at it from this perspective, indexes are ridiculously cheap in terms of reads and you can go quite far with those but for some operations there is just no way around Map/Get, Get is still only 1 read. Given that you get 100 000 for free per day that is still not expensive :). You could keep your pages also relatively small (size parameter in paginate) to make sure you don't do unnecessary gets unless your users or app requires more pages.
For people reading this that do not know this yet:

*

*1 index page === 1 read

*1 get === 1 read

Final notes
We can and will make this easier in the future. However, note that you are working with a scalable distributed database and often these things are just not even possible in other solutions or very inefficient. FaunaDB provides you with very powerful structures and raw access to how indexes work and gives you many options. It does not try to be clever for you behind the scenes as this might result in very inefficient queries in case we get it wrong (that would be a bummer in a scalable pay-as-you-go system).

A: Easy way to query with the multiple conditions I think with the query it with documents differences, In my solutions it is like:

    const response = await client.query(
      q.Let(
        {
          activeUsers: q.Difference(
            q.Match(q.Index("allUsers")),
            q.Match(q.Index("usersByStatus"), "ARCHIVE")
          ),
          paginatedDocuments: q.Map(
            q.Paginate(q.Var("activeUsers"), {
              size,
              before: reqBefore,
              after: reqAfter
            }),
            q.Lambda("x", q.Get(q.Var("x")))
          ),
          total: q.Count(q.Var("activeUsers"))
        },
        {
          documents: q.Var("paginatedDocuments"),
          total: q.Var("total")
        }
      )
    );

    const {
      documents: {
        data: dbData = [],
        before: dbBefore = [],
        after: dbAfter = []
      } = {},
      total = 0
    } = response || {};

    const respBefore = dbBefore[0]?.value?.id || null;
    const respAfter = dbAfter[0]?.value?.id || null;

    const data = await dbData.map((userData) => {
      const {
        ref: { id = null } = {},
        data: { firstName = "", lastName = "" }
      } = userData;

      return {
        id,
        firstName,
        lastName
      };
    });

So in the query builder you can filter each nested document in variable in Let section by the index that you want.

A: Here is the another variant of filtering, in SQL looks like:

SELECT * FROM clients WHERE salary > 2000 AND age > 30;

For fauna query:

const response = await client.query(
  q.Let(
    {
      allClients: q.Match(q.Index("allClients")),

      filteredClients: q.Filter(
        q.Var("allClients"),
        q.Lambda(
          "client",
          q.And(
            q.GT(q.Select(["data", "salary"], q.Get(q.Var("client"))), 2000),
            q.GT(q.Select(["data", "age"], q.Get(q.Var("client"))), 30)
          )
        )
      ),

      paginatedDocuments: q.Map(
        q.Paginate(q.Var("filteredClients")),
        q.Lambda("x", q.Get(q.Var("x")))
      ),
      total: q.Count(q.Var("filteredClients"))
    },

    {
      documents: q.Var("paginatedDocuments"),
      total: q.Var("total")
    }
  )
);

This is some kind of filtering in javascript where the condition if returns true so it will be in the result of the response. Example:

const filteredClients = allClients.filter((client) => {
  const { salary, age } = client;

  return ( salary > 2000 ) && (age > 30)
})


text:
Q: .gitignore files in parent folder I have a folder structure like this:
folder 1
- folder 2
- - file.css
- - file.css
- folder 3
- - file.css
- folder 4
- - file.css

Is there a way to make git ignore all the .css files in folder 1? Without having to mention the children folders?

A: $ cat .gitignore
/folder 1/*.css

The / at the beginning anchors the file names to the root of the repository. A simple * matches only file names, not the / for sub-directories.
If folder 1 is your git root folder, use
/*.css

For a folder named .css in your git root folder use
/.css

A: css in folder1
/*.css

all css
*.css


text:
Q: Unity's NavMesh Agent glitches on navmesh edges I've recently started playing around with AI and Unity's built in pathfinding. So far I haven't had any bigger troubles with it but yesterday I imported a mountain model with a path going from it's base to the very top.
My AI game object consists of Rigidbody (set to kinematic), Capsule Collider and a NavMesh Agent.
I generated the NavMesh and set max slope to 40 degrees and the AI navigates just fine when it follows my player or walks along designated paths (waypoints) but when I try to pick a random position on the NavMesh in AI's radius it glitches out  and starts shaking after few seconds, usually when the destination is close to NavMesh's edge.
I've captured two videos of it and I'm struggling to fix this since yesterday.
I've tried removing the Rigidbody completely, changing obstacle avoidance settings, lowering the maximum slope but nothing worked so far.
This is how it looks like:
Video 1
Video 2
The code I use to get random position:
Pastebin
        void ControlRandomWander()
        {
            float pointDist = Vector3.Distance(currentWanderPos, transform.position);

            if(pointDist < 2f || currentWanderPos == Vector3.zero)
            {
                wanderWaitTimer += Time.deltaTime * 15;

                anims.LookAround(true);

                if (wanderWaitTimer >= wanderWaitTime)
                {
                    Vector3 randPos = GetRandomPositionAroundTarget(transform.position, -wanderRadius, wanderRadius);

                    NavMeshPath pth = new NavMeshPath();
                    NavMesh.CalculatePath(transform.position, randPos, agent.areaMask, pth);
                    float pathDist = 0f;

                    if (pth.status == NavMeshPathStatus.PathComplete)
                    {
                        for (int i = 0; i < pth.corners.Length - 1; i++)
                        {
                            pathDist += Vector3.Distance(pth.corners[i], pth.corners[i + 1]);
                        }

                        Debug.Log(pathDist);

                        if (pathDist <= wanderRadius)
                        {
                            currentWanderPos = randPos;

                            wanderWaitTime = Random.Range(wanderWaitMin, wanderWaitMax);

                            anims.LookAround(false);
                            wanderWaitTimer = 0;

                            MoveToPosition(randPos, true);
                        }
                    }
                }
            }
            else
            {
                if (agent.destination != currentWanderPos)
                {
                    MoveToPosition(currentWanderPos, true);
                }
            }
        }

        Vector3 GetRandomPositionAroundTarget(Vector3 pos, float minRange, float maxRange)
        {
            float offsetX = Random.Range(minRange, maxRange);
            float offsetZ = Random.Range(minRange, maxRange);

            Vector3 orgPos = pos;

            orgPos.x += offsetX;
            orgPos.z += offsetZ;

            NavMeshHit hit;
            if(NavMesh.SamplePosition(orgPos, out hit, 5f, agent.areaMask))
            {
                Debug.Log(hit.position);
                return hit.position;
            }

            Debug.Log(hit.position);

            return pos;
        }

I would really appreciate any help sorting out this issue.

A: Turns out NavMesh.SamplePosition doesn't take NavMesh Agent radius into account so the agent can't ever reach it.
I managed to fix it by moving the hit.position by half of agent's radius away from the edge.
if(NavMesh.SamplePosition(orgPos, out hit, 5f, agent.areaMask))
{
     Vector3 ret = hit.position;
     Vector3 pathDir = pos - ret;
     ret += pathDir.normalized * (agent.radius / 2);

     return ret;
}


text:
Q: What is 2SLS estimator with three instruments? Given the following model,
$$y_i = a + bx_i +e_i$$
It's known that $Cov(e, x ) \neq 0$, so we are going to use 2SLS method. We have three variables $v_1, v_2, v_3$.
What is the formula for the slope $\hat b$?


text:
Q: Comparing 2 datasets I'm been looking for the best way to create a look up table which holds every record ID for database 1 alongside every record ID from data base. So if one database had 10 records no the second had 5 the look up table would have 50 row, 10x5 and my look up table looks like this
1 1
1 2
1 3
1 4
1 5
2 1
2 2
2 3
2 4
2 6
3 1

A: If you are using a relational database, like SQL, you can reference a primary key from another table. This would be called a foreign key.
If you have a one to many relationship, meaning a record from table A could be assigned to multiple records in table B, but table B can only relate to one record in table A; then you can add table A's primary key as a foreign key in table B. In this scenario you do not have to create a separate table that maintains the relationships.
If you have a many to many between the two tables, meaning that records from table A can relate to multiple records in table B and vice versa, then you do require a third table with two columns containing the primary keys of each table.
Let the database engine do the work for you. You can then write a basic join query to lookup the related records.


text:
Q: java.awt.Graphics change color after drawing I have asked a similar question a while ago here, but didn't get an answer. The original question was about changing the color of a shape after clicking on it. But I am puzzled on how to access the shape at all after it is drawn.
This is my paintComponent method
    @Override
protected void paintComponent(Graphics graph) {
    super.paintComponent(graph);
    Graphics2D g = (Graphics2D) graph;
    // smooth graphics
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // moving to the middle of the panel
    g.translate(this.getWidth()/2, this.getHeight()/2);

    // painting colored arcs
    for(int i = 0; i < 4; i++) {
        g.setColor(dimColors[i]);
        g.fill(arcs[i]);
    }

    // painting borders
    g.setColor(Color.BLACK);
    g.setStroke(new BasicStroke(5F));
    g.drawLine(-98, 0, 98, 0);
    g.drawLine(0, -98, 0, 98);
    g.draw(circle);

    // painting central white circle
    g.setColor(Color.WHITE);
    g.fill(smallCircle);
    g.setColor(Color.BLACK);
    g.draw(smallCircle);

}

the arcs[] array contains a bunch of Arc2D's that are drawn on the panel. My question is now, if I want to change the color of, for example arcs[0], how do I do that?
Thanks!
EDIT: I now have this MouseAdapter event
     private class MyMouseAdapter extends MouseAdapter {
     public void mousePressed(MouseEvent e) {

         Point p = e.getPoint();
         Component c = getComponentAt(p);

         Graphics g = c.getGraphics();

         dimColors[1] = Color.RED;

         paintComponent(g);

     }
 }

And it works, it changes the color of arc[1] because arcs[1] has dimColors[1] set as color when drawing it.
However, I still can't figure out how to check wether the right arc was clicked. Right now you just click anywhere on the graphics panel and it changes the color of that specific arc

A: This doesn't answer your earlier question, however it does answer your question of click detection. To do this it is best to use Graphics2D because it is a lot easier to write than most other options. Here is an example:
     public class GraphicsPanel extends JPanel implements MouseListener
    {
            private Rectangle2D rect;

First we create our Graphics2D rectangle rect.
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)(g);
            g2d.setColor(Color.GREEN);
            rect = new Rectangle2D.Double(70, 70, 100, 100);
            g2d.fill(rect);
            this.addMouseListener(this);
        }

And then we override the paintComponent method and create our new Rectangle2D.Double object.
We then fill the rectangle with g2d.fill() and then add a mouse listener to the JPanel.
        public void mousePressed(MouseEvent e)
            {

               if(rect.contains(e.getX(), e.getY()))
                    System.out.println("Rectangle clicked");
            }
    }

Finally, we need to see if that rectangle contains the point where the user clicked. To do this, simply see if the rectangle we created contains the user's click location by using the Rectangle2D.double's contains(int x, int y) method. That's it!

A:
if I want to change the color of, for example arcs[0], how do I do that?

A line (or whatever) only exists as a bunch of pixels that were painted in the original color.  To change its color you must change the current color and draw it again.


text:
Q: cannot be able to use "as" key word in DynamicTableEntity (Azure Table) I have an Azure table where I have inserted heterogeneous entities. After the retrieval, I want to convert them to some specific type using "as". I tried to do this, but it threw the following error:

Cannot be able to convert DynamicTableEntity to TestingEntity Via reference conversion, boxing conversion, unboxing conversion,  wrapping conversion or null type conversion.

Is there any way I can convert my entities to a particular type?
My code is as follows:
 CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                // Create the table client.
                CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

                CloudTable table = tableClient.GetTableReference("TestingWithTableDatetime");
                // Create the table if it doesn't exist.
                table.CreateIfNotExists();
     TableQuery<DynamicTableEntity> entityQuery =
                    new TableQuery<DynamicTableEntity>();
                var employees = table.ExecuteQuery(entityQuery);

                IEnumerable<DynamicTableEntity> entities = table.ExecuteQuery(entityQuery);
                foreach (var e in entities)
                {
                    EntityProperty entityTypeProperty;
                    if (e.Properties.TryGetValue("EntityType", out entityTypeProperty))
                    {
                        if (entityTypeProperty.StringValue == "SampleEntity1")
                        {
//Cannot be able to Use as
                            var TestingWithTableDatetime = e as SampleEntity1;
                        }
                        if (entityTypeProperty.StringValue == "SampleEntity2")
                        {
                            // Use entityTypeProperty, RowKey, PartitionKey, Etag, and Timestamp
                        }
                        if (entityTypeProperty.StringValue == "SampleEntity3")
                        {
                            // Use entityTypeProperty, RowKey, PartitionKey, Etag, and Timestamp
                        }
                    }
                }

Class definition for Sample1
 public class Sample1 : TableEntity
    {
        public Sample1(string pk, string rk)
        {
            this.PartitionKey = pk;
            this.RowKey = rk;
            EntityType = "MonitoringResources";
        }

        public string EntityType { get; set; }

        public Sample1()
        {
        }

    }

Things I have tried.I have created a class as Testing and in that I inherited Table entity.Then Testing is inherited by sample1 as follow
Testing Class definition
public class testing : TableEntity
    {
        public testing(string pk, string rk)
        {
            this.PartitionKey = pk;
            this.RowKey = rk; //MetricKey
        }

        public string EntityType { get; set; }

        public testing()
        {
        }
    }

modified Class sample1:
public class sample1 : testing
    {
        public sample1(string pk, string rk) : base(pk, rk)
        {
            EntityType = "sample1";
        }

        public sample1()
        {
        }
    }

In this i didnt get any error but
when I am converting it to sample1 by using "as" it returns as null.
Finally I ended with creating some helper.
 public static class AzureManager
    {
        /// <summary>
        ///  Converts a dynamic table entity to .NET Object
        /// </summary>
        /// <typeparam name="TOutput">Desired Object Type</typeparam>
        /// <param name="entity">Dynamic table Entity</param>
        /// <returns>Output Object</returns>
        public static TOutput ConvertTo<TOutput>(DynamicTableEntity entity)
        {
            return ConvertTo<TOutput>(entity.Properties, entity.PartitionKey, entity.RowKey);
        }

        /// <summary>
        ///  Convert a Dynamic Table Entity to A POCO .NET Object.
        /// </summary>
        /// <typeparam name="TOutput">Desired Object Types</typeparam>
        /// <param name="properties">Dictionary of Table Entity</param>
        /// <returns>.NET object</returns>
        public static TOutput ConvertTo<TOutput>(IDictionary<string, EntityProperty> properties, string partitionKey, string rowKey)
        {
            var jobject = new JObject();
            properties.Add("PartitionKey", new EntityProperty(partitionKey));
            properties.Add("RowKey", new EntityProperty(rowKey));
            foreach (var property in properties)
            {
                WriteToJObject(jobject, property);
            }
            return jobject.ToObject<TOutput>();
        }

        public static void WriteToJObject(JObject jObject, KeyValuePair<string, EntityProperty> property)
        {
            switch (property.Value.PropertyType)
            {
                case EdmType.Binary:
                    jObject.Add(property.Key, new JValue(property.Value.BinaryValue));
                    return;

                case EdmType.Boolean:
                    jObject.Add(property.Key, new JValue(property.Value.BooleanValue));
                    return;

                case EdmType.DateTime:
                    jObject.Add(property.Key, new JValue(property.Value.DateTime));
                    return;

                case EdmType.Double:
                    jObject.Add(property.Key, new JValue(property.Value.DoubleValue));
                    return;

                case EdmType.Guid:
                    jObject.Add(property.Key, new JValue(property.Value.GuidValue));
                    return;

                case EdmType.Int32:
                    jObject.Add(property.Key, new JValue(property.Value.Int32Value));
                    return;

                case EdmType.Int64:
                    jObject.Add(property.Key, new JValue(property.Value.Int64Value));
                    return;

                case EdmType.String:
                    jObject.Add(property.Key, new JValue(property.Value.StringValue));
                    return;

                default:
                    return;
            }
        }
    }

the above one works for me.
var obj= AzureManager.ConvertTo<Sample1>(e);

If you find any other way.Please suggest.

A: Here is an alternative and much simpler solution for you that is natively supported by Azure Storage SDK version > 8.0.0. You do not even need to write any transformation / conversion code :)
Have a look at:
TableEntity.Flatten method: https://msdn.microsoft.com/en-us/library/azure/mt775434.aspx
TableEntity.ConvertBack method: https://msdn.microsoft.com/en-us/library/azure/mt775432.aspx
These methods are provided by the SDK as static, standalone helper methods. Flatten method will convert your entities to a flat dictionary of entity properties where you can simply assign a partition key and row key, create a dynamictableentity from the flat dictionary and write to azure table storage.
When you want to read the entity back, read it as dynamic table entity and pass the property dictionary of the returned dynamic table entity to TableEntity.ConvertBack method. Just tell it which type of object you want the method to convert the property dictionary into, via its generic type parameter and it will do the conversion for you.
I originally implemented these api s as nuget packages and now they are integrated into azure storage sdk. If you want to read a bit more about how they work you can see the article I wrote originally about the nuget packages here:
https://doguarslan.wordpress.com/2016/02/03/writing-complex-objects-to-azure-table-storage/

A:
Is there any way I can convert my entities to a particular type?

We could use DynamicTableEntityConverter to do that.
According to your code, we could use the following code to  covert DynamicTableEntity  to Sample1
var TestingWithTableDatetime = DynamicTableEntityConverter.ConvertToPOCO<Sample1>(e);


text:
Q: Get end of week based on date column in the dataframe below, the 'end_of_week' column does not yet exist. I'm trying to make so that if 'date' is lesser or equal to Thursday of that week, 'end_of_week' is Thursday. How do I do this?
What I'm trying to do:
df['end_of_week'] = Thursday of same week if df['date'] <= Thursday

Example:
0   date    end_of_week
1   2015-08-31  2015-09-03 #if <= Thursday of that week
2   2015-09-01  2015-09-03
3   2015-09-07  2015-09-10
4   2015-09-09  2015-09-10
5   2015-09-16  2015-09-17
6   2015-09-17  2015-09-17

Thanks.

A: How about:
df['end_of_week'] = df['date'].map(lambda x: next_weekday(x, 3) if  x.weekday() < 3 else x)

where, from @phihag's answer at Find the date for the first Monday after a given a date:
def next_weekday(d, weekday):
    days_ahead = weekday - d.weekday()
    if days_ahead <= 0:
        days_ahead += 7
    return d + datetime.timedelta(days_ahead)

Doing a test:
import pandas as pd
import datetime
xl3 = pd.ExcelFile('test2.xlsx')
df3 = xl3.parse("Sheet1")
df3
Out[71]:
   x          y       date
0  1        fum 2015-06-01
1  2         fo 2015-06-02
2  3         fi 2015-06-03
3  4        fee 2015-06-04
4  5  dumbledum 2015-06-05
5  6  dumbledee 2015-06-06

df3['end_of_week'] = df3['date'].map(lambda x: next_weekday(x, 3) if x.weekday() < 3 else x)

df3
   x          y       date end_of_week
0  1        fum 2015-06-01  2015-06-04
1  2         fo 2015-06-02  2015-06-04
2  3         fi 2015-06-03  2015-06-04
3  4        fee 2015-06-04  2015-06-04
4  5  dumbledum 2015-06-05  2015-06-05
5  6  dumbledee 2015-06-06  2015-06-06

A: You can use arrow to find the nearest Thursday. Arrow considers Monday the zeroth day of the week.
import arrow

THURSDAY = 3
arw = arrow.get("2015-08-31")
arw = arw.replace(days= +(THURSDAY - arw.weekday())).format('YYYY-MM-DD')

#=> arw = '2015-09-03'

To address your issue directly:
import arrow

THURSDAY = 3
dates = [
    "2015-08-31",
    "2015-09-01",
    "2015-09-07",
    "2015-09-09",
    "2015-09-16",
    "2015-09-17",
]

end_of_week_dates = []

for date in dates:
    arw = arrow.get(date)
    if arw.weekday() <= THURSDAY:
        end_of_week = arw.replace(days= +(THURSDAY - arw.weekday())).format('YYYY-MM-DD')
        end_of_week_dates.append(end_of_week)
    else:
        # handle the case where the date is after the Thursday of that week

# end_of_week_dates = [
#   '2015-09-03',
#   '2015-09-03',
#   '2015-09-10',
#   '2015-09-10',
#   '2015-09-17',
#   '2015-09-17'
# ]


text:
Q: Manipulating Date in Excel code A column in an excel worksheet holds the month in this format:
Oct_2010

What I want to do is, get the last date of that month. What I figured I would do is, read the month in the cell, get the first day of the next month and then subtract one day, so I get the last date of the previous month.
But, how can I get Excel (VBA code) to read Oct_2010 as Oct 2010?

A: How about:
 =DATE(YEAR(REPLACE(A1,4,1,"/")),MONTH(REPLACE(A1,4,1,"/")),0)

Where A1=Oct_2010

A: In VBA
Function LastDayFromString(sDate As String) As Date

    Dim dtTemp As Date

    If Not sDate Like "???[_]####" Then Err.Raise 9999, , "Invalid date string format"

    dtTemp = DateValue(Replace(sDate, "_", "/"))

    LastDayFromString = DateSerial(Year(dtTemp), Month(dtTemp) + 1, 0)

End Function

Used like
?lastdayfromstring("Oct_2010")
10/31/2010


text:
Q: jquery switch statement and scope issue I have this working script (i know its incomplete):
function rsvpNew(selector,function_url) {
 $(selector).livequery('click',function(){
   var select = $(selector).attr('rel');
   var event_id = $(this).parents('ul.event-options').attr('rel');
   element = this;

   switch(select) {
        case "attending":
        $.ajax({
        type: "POST",
        url: "/events/set_member/"+function_url,
        data: "event_id="+event_id,
        beforeSend:  function() {
        $("Saving...").prependTo('body');
                        },
        complete: function() {

                $('span.notice').fadeOut(500);
                $(element).closest('span.rsvp-status').html("I'm Attending – Remove");
                }

        });

             break;

Now the line
$(element).closest('span.rsvp-status').html("I'm Attending – Remove");

Is working, but when I do something similar to get the parent ul of this li, it doesn't work.
Any ideas?

A:
but when I do something similar to get
  the parent ul of this li, it doesn't
  work. Any ideas?

To get the parent of something you can use a few options:
$('li').parent('ul'); //will return your ul

Gets the direct parent of an element.

Another way is to use closest:
$('li').closest('ul'); //should also return your ul

Gets a set of elements containing the
  closest parent element that matches
  the specified selector. Especially
  useful for event delegation.


text:
Q: In Three.js, while using WebVR, how do I move the camera position? I'm trying to adapt my existing three.js project to work with WebVR.  I've made decent progress -- I can look around the scene in VR, but I'm unable to move the camera position away from the initial place it gets spawned (which appears to be close to 0,0,0, it seems like there is a predefined userHeight that gets factored in)
Once I call renderer.vr.setDevice( vrDisplay ) it seems like a new camera is created and the existing camera that my scene was using is no longer used.  I'd like to keep using that camera, or at least inherit most of its properties.
I've noticed that there is a renderer.vr.getCamera() method (link to source) but I haven't found any examples or documentation of how to use it (or if I should use it).  Curiously, this method accepts a camera as an argument, which is a bit unintuitive for a getter.  Looking at the code, it seems like the function should be called setCamera and left me a bit confused.  I tried calling the function and passing in my existing camera but it had no effect.
Any help is appreciated.  I am using a Google Daydream View on the latest version of Android/Chrome using Three.js R91

A: swirlybuns, Mugen87 solution works as long as you add user to the scene
var user = new THREE.Group();
user.position.set(0,0,0);
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.1, 1000 );
camera.position.y = 1.6;
user.add( camera );
scene.add(user);

and on render loop
user.position.setZ(camera_z_pos);
camera_z_pos -= current_velocity;

Tested on
Three.js v102
chrome mobile v75


text:
Q: axiomatic Euclidean geometry and its relation to the geometry of special relativity It has been shown that the Euclidean plane defined by Hilbert's axioms is isomorphic to the 2D Euclidean vector space. Spacetime in special relativity can't be modeled by an Euclidean vector space, so not all of Hilbert's axioms can hold in the geometry of special relativity.
My question is: which of them are violated and which of them still hold?
And going one-step further: can the axioms which are violated be replaced by others so that we get a synthetic version of the geometry of special relativity analogous to axiomatic Euclidean geometry?
Any thoughts and references are appreciated. I didn't post this question under physics because I don't think that many physicists are familiar with axiomatic geometry.


text:
Q: How do I map an OData nested filter query against a DTO to another entity? I am trying to test the ASP.NET Web API OData V4 $filter functionality.
I could map a non- nested filter query against a DTO to another entity easily following the answer here without using AutoMapper.
But I want to map a nested filter query to a non-complex DTO.
eg. mapping ?$filter= SubProperties/Amount eq 100 against a DTO which has Amount field under SubProperties class and then further map it to a target DTO which has Amount property not nested.
GET products?$filter=SubProperties/Amount eq 100`
The Product class:
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Level { get; set; }
    public Properties SubProperties {get;set;}
}

public class Properties
{
    public double Amount{ get; set; }
}

The ProductDTO class:
public class ProductDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Level { get; set; }
    public double Amount { get; set; }
}

The ProductsController:
public class ProductsController : ApiController
{
    public IEnumerable<ProductDTO> Get(ODataQueryOptions<Product> options)
    {
       IQueryable<Product> products = this._products.AsQueryable();

        IEdmModel model = GetProductDTOModel();
        IEdmType type = model.FindDeclaredType(typeof(ProductDTO).ToString());
        ODataQueryOptionParser parser = new ODataQueryOptionParser(model, type, null, new Dictionary<string, string> { { "$filter", options.Filter.RawValue } });
        ODataQueryContext context = new ODataQueryContext(model, typeof(Product), options.Context.Path);
        FilterQueryOption filterMapper = new FilterQueryOption(options.Filter.RawValue, context, parser);

    }
}

When I expand on options -> Filter it has mapped correctly to the filter query string and FilterClause loads correctly. But after mapping it to ProductsDTO and expanding on filterMapper , FilterClause throws an exception, since it doesn't have a property SubProperties.


text:
Q: How to force `ip route get` to ignore a specific device? How can I do ip route get, but force it to ignore a specific device?
When I start my VPN, I run ip route get <vpn_server_ip> to determine what interface to use to connect to the VPN. Then I add a default route with highest priority that sends all traffic to my VPN tun device. The VPN traffic is not captured by the default route because its sockets bind to the interface obtained from the ip route get.
That's all fine, but if there are network changes and the outgoing interface goes down, I need to start using the next interface. But because the VPN is running I can't call ip route get <vpn_server_ip> because that will return the tun device. I don't want to temporarily remove the VPN route because that will leak traffic.

A: The ip route get command uses the actual routing information and uses the longest prefix match algo. There isn't a way to ignore specific interfaces. But if you have the several suitable routes with various metrics, you can use the other command - ip route list match <ip>. It will return all suitable routes for the particular ip address, not only the best route.


text:
Q: type of html content http get returned in flutter I am not frontend web developer, and
I am using google map inside web view in flutter application.
import 'package:http/http.dart' as http;
uri = Uri.parse("[some google map url][1]");
var response = await http.get(uri);
debugPrint(response.body);

it prints something like this :
 <!DOCTYPE html><html itemscope="" itemtype="http://schema.org/Place" lang="en"> <head> <link href="/maps/preview/opensearch.xml?hl=en" title="Google Maps" rel="search" type="application/opensearchdescription+xml"> <title>  Google Maps  </title> <meta content=" Find local businesses, view maps and get driving directions in Google Maps. " name="Description">  <meta content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" name="viewport"> <meta content="chrome=1" http-equiv="X-UA-Compatible">
<meta content="notranslate" name="google"> <meta content="origin" name="referrer"> <meta content="ByHT0GXztW_RcGxS0o86DBf1WtNu02FfqlcT8njnSqU" name="google-site-verification"> <meta content="Diln__r3p9-tt39P2Cl2Amvx6oFB4PATnxuFBaw6ej8" name="google-site-verification">   <meta content="ثانوية زكي الأرسوزي to Faculty of Architecture" itemprop="name"> <meta content="ثانوية زكي الأرسوزي to Faculty of Architecture" property="og:title">  <meta content="https://maps.goo.......

the body of the response is not similar to the body shown in the same url in the browser inspector, can someone explain to me what is the difference between them please.
(I want to get the same html code in the browser in dart).


text:
Q: How to redirect / route VPN traffic to back standing local network? There are two computers one "HOME" with Ubuntu 10.10 installed, and another "WORK" with WinXP installed. WORK PC is behind draconian firewall. However, let's imagine, that there is VPN connection installed between this 2 work stations, for example, with teamviewer, hamachi, openvpn, or by some other mean (by the way, what is the best mean for such purposes?).
One is interested in working with WORK's LAN resources from his HOME computer via VPN. So my question is about configuration required to be done on WinXP machine (or, maybe on both machines), to make such interaction possible?
I'm guessing that some routing stuff should be performed somewhere. But I don't know what exactly and how to do?

A: I believe Hamachi supports this out of the box.  You'll want to setup a Gateway Network:

Provide secure access to your private
  network/LAN, including the resources
  on it, from a centralized LogMeIn
  Hamachi² gateway, without modifying
  firewalls or network routers.

You can configure the type of network you want from their control panel when you sign up.  Your work computer would be the Gateway.
This may violate your workplace computer use policies so just be aware of that.


text:
Q: How to create check box in django I am developing a site in django.I have to display a check box in templates.
I am using model form,
class ReportPersonForm(forms.ModelForm):
    class Meta:
        model = ReportPerson
        fields = ['name','first_aid','sick_bay','ambulance']

I have to create check box for the following fields   respectively,first_aid,sick_bay,ambulance and render in template.
Can anyone help me to create a check in django and how to design template to display the check box.
Thanks

A: If you define you field in model as BooleanFileld - you can use
{{ form.first_aid }}

in you template

A: In your forms file
class ReportPersonForm(forms.ModelForm):
    first_aid = models.BooleanField()
    sick_bay = models.BooleanField()
    ambulance = models.BooleanField()
    class Meta:
        model = ReportPerson
        fields = ['name','first_aid','sick_bay','ambulance']

Then for your template you have multiple options, read on in the docs what suits your needs:
Working with forms


text:
Q: Preference setIcon to ColorDrawable does not work on Android 5.0 Lollipop In my app I use the following line to distinguish some preferences:
preference.setIcon(new ColorDrawable(color));

In Android versions prior to Lollipop it works fine and the preference shows a square icon of the selected color, but in Lollipop none is shown.
Any idea for how to solve it?
Thanks
Here is a solution that is working for me:
preference.setIcon(getPreferenceIcon(color));

function Drawable getPreferenceIcon(int color)
{
  if (Build.VERSION.SDK_INT < 21) return new ColorDrawable(color);
  int bitmap_size = 64;
  Bitmap bitmap = Bitmap.createBitmap(bitmap_size, bitmap_size, Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(bitmap);
  Paint paint = new Paint();
  paint.setColor(color);
  canvas.drawRect(new Rect(0, 0, bitmap_size, bitmap_size), paint);
  return new BitmapDrawable(getResources(), bitmap);
}

A: Here is a simplified version of The Matrix's answer, I removed the check on the version since it was also not working properly on Ice Cream Sandwich (a thin line was displayed, not a square):
private Drawable getPreferenceIcon(int color) {
    int size = 200;// Set to a big size to fit all screens, will be contained anyway in the preference row
    Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    bitmap.eraseColor(color);

    return new BitmapDrawable(getResources(), bitmap);
}

A: If you're willing to do it in the XML file, here's an easy solution:
<Preference
    ...
    android:icon="@color/colorSome"/>

It's a simple solution if you don't want to change the icon in-code.


text:
Q: PL/SQL dbms_output adding extra Carriage Return in CLOB When using dbms_output to put a clob with a carriage return it is inserting an additional one, which creates additional line breaks that can be seen when running it in SQL*Plus and using spool to capture it. The database being used is Oracle 11g. For example, running this:
SET HEADING OFF
SET FEEDBACK OFF
SET ECHO OFF SET
VERIFY OFF SET
TRIMOUT ON SET
TRIMSPOOL ON
SET SERVEROUTPUT ON

SPOOL ./TestResult.txt

-- Spooling direct select for comparing results
SELECT 'line 1'||CHR(13)||CHR(10)||'line 2' FROM DUAL;

declare
  l_clob clob;
begin
  l_clob := 'line 1'||chr(13)||chr(10)||'line 2';
  dbms_output.put_line(l_clob);
end;
/

SPOOL OFF

Produces:
line 1
line 2

line 1

line 2

With the underlying line breaks going like:
[CR][LF]
line 1[CR][LF]
line 2[CR][LF]
[CR][LF]
line 1[CR]
[CR][LF]
line 2[CR][LF]
[CR][LF]

As additional note, the code above is a simplified example to illustrate my issue. In reality, the CRLF line jumps came from a clob column that I cannot modify, but I need to process before creating some client side log files with spool, as I cannot use utl_file or similar functions for creating them. Also this should be handled inside PL/SQL or SQL*Plus if possible, so I am not looking for solutions in the line of eliminating the extra CRs externally with a text editor, sh/bat scripts or similar methods.
I have tried to find why it is inserted or how to get rid of it to no avail, so any help will be greatly appreciated.

A: Include SET LINESIZE into your set of SET commands, e.g.
set serveroutput on
set linesize 2000        --> this
spool ..

A: Use DBMS_OUTPUT.PUT.
This procedure places a partial line in the buffer.
On "Database PL/SQL Packages and Types Reference", chapter 100 DBMS_OUTPUT
PUT Procedure


text:
Q: Find large strings allocation during java debug session After analyzing a heap dump I found that there were some 30MB strings allocated (single string of 30 MB).
Is there a way to set a break point while debugging the application so I can find the code which allocates these huge strings?
Since thousands of strings are allocated during application run it isn't possible just putting a break point on each string allocation.
I believe conditional break point will be too slow as well.
If possible I would want to exam those strings content to understand the origin of these allocation.
For example they may be a result of a web service call which usually is called with small amount of data but in rare cases with huge input (which are the cases I want to find).

A: Although you explicitly asked for a debug session, I assume that this was mainly an attempt to solve the actual problem: Large strings are allocated, and you don't know where this happens.
The allocations can be traced with jVisualVM. You can start jVisualVM and your program, and connect the jVisualVM to your program.
If this does not suit your needs, I can delete this answer. Otherwise, here's how you can do it:
In the "Profiler" tab you can check the "Settings" checkbox in the upper right, and select the "Memory Settings" tab. There you can set the "Record allocation stack traces" checkbox:

Then, after pressing the "Memory" button at the top, the profiler will collect the information about the string allocations. After the application has exited (or after a snapshot has been taken), you can examine the recorded stack traces to find the method that allocates the large string - in this example, method4:

A: *

*Copy the source code of java.lang.String from JDK sources to your
project

*Create a method in your String.java like below (count is an existing instance variable of java.lang.String)
private void checkSize(){
    if(count>1000000) //1MB
      System.out.println(count);
 }

*Edit java.lang.String to call this method checkSize() at the end of every constructor

*Add breakpoint at the line System.out.println(count);

*Add the new java.lang.String to bootstrap classpath

*This breakpoint will break only when a String of size > 1MB  gets created

A: I'd try the conditional breakpoint, even if it meant leaving the app running for a day or two. At least then you can get on with something else while it is running. And any other solution is likely to take a day or two to implement anyway.
Failing that, you could using AspectJ to add pointcut into the String constructors and use that to log a message, throw an exception etc. This is basically the same as a conditional breakpoint but should run more quickly.


text:
Q: Python loop over files in directory then list I am trying to loop over files in a directory and list the path of each one.
My code iterates over each file but lists the wrong directory. What am I missing to return the full directory?
Here's my code so far:
import os

directory = "posts/"

for file in os.listdir(directory):
    if file.endswith(".md"):
        dir = os.path.abspath(file)
        print "The Path is: " + str(dir)

The structure is like this:
.
├── app.py
└── posts
    ├── first.md
    └── second.md

Output from the terminal (missing the /posts/ part of the directory):
The Path is: /home/tc/user/python-md-reader/second.md
The Path is: /home/tc/user/python-md-reader/first.md

A: If you take a look at the source code:
def abspath(path):
    """Return the absolute version of a path."""
    if not isabs(path):
        if isinstance(path, unicode):
            cwd = os.getcwdu()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)         # normpath according to the comment
                                  # """Normalize path, eliminating double slashes, etc."""

What abspath does is simply join the current working directory with the path you provided, since you only provide the file as a path, and you are one level up of the posts directory it will get ignored.

A: You can just put the directory back into the path:
dir = os.path.abspath(os.path.join(directory, file))


text:
Q: Dynamic link to other workbook in Excel In cell A1 I have a path to an external Excel-file:
C:\Users\John\Stuff\MySourceFile.xlsm

In cell A2 I have a hardcoded link pointing to a specific cell in that external file to show the value.
='C:\Users\John\Stuff\[MySourceFile.xlsm]Sheet1'!A1

Question: How can I edit the cell A2 to make the link dynamic so that if I change the A1 value, the A2 would automatically relink to the new file? (Note: Looking for a no-VBA solution)


text:
Q: Can't create object from VB6 COM DLL using VB6 program I have a VB6 COM DLL that was developed on a WinXP 32bit system. It works fine on that PC from C#, VB6, and Python applications. I am testing the DLL on another WinXP 32bit system and on Win7 32bit and 64bit. The Python program runs fine on any system. The VB6 program gives 'error 429: ActiveX component can't create object'.
Dim foo As testdll.Class1
MsgBox (1)
Set foo = New testdll.Class1
MsgBox (2)

The program sees the dll, since the first MsgBox displays fine, but the second one doesn't after trying to create an object. Any ideas?

A: The Python script is probably creating late bound instances via ProgId.  My guess is you haven't maintained binary compatibility on this DLL so ClassId values have changed, causing problems for early bound client code such as your VB6 client.

A: Most probably the .dll has a dependency on some other dll, which is absent on the non-development machines. You can check this using dependency walker.
It is no very strange that the first line of code does not raise an error: in this line the Class1 is not initialized, in the second it is. So check the Class_Initialise method for calls to other dll's.


text: Q: track all users access to database" vulnerability in azure sql database giving no result I am getting "track all users access to database" vulnerability in azure sql database but after clicking on it the result page shows message that "query yield no result" and both approve result as baseline and remove from baseline options are disabled.


text:
Q: Dropping XML message More than a week I'm trying to create communication between javascript(running on node.js) clientside script and WCF(SOAP) service.
Communication is throught: XML, POST method
xmlhttp.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');

URL and XML which I'm sending to service is defined as:
soapRequest('http://winserver:8735/ReportsListsService',
    `<?xml version="1.0" encoding="UTF-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
      <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IReportsListsService/GetClients</Action>
    </s:Header>
    <s:Body>
      <GetClients xmlns="http://tempuri.org/" />
    </s:Body>
  </s:Envelope>`);

This is my service, currently trying call simplest method GetClients
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;
using tt4t.Dispatching.ApplicationServer.Data.CommonData;

namespace tt4t.Dispatching.ApplicationServer.Data.Reports.Lists
{
    [ServiceContract]
    public interface IReportsListsService : IMicroservice
    {
  [OperationContract]
        IEnumerable<Client> GetClients();
    }
}

But getting this error in chrome debug console
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><s:Fault><faultcode>s:Client</faultcode><faultstring xml:lang="en-US">The incoming message contains a SOAP header representing the WS-Addressing 'Action', yet the HTTP transport is configured with AddressingVersion.None.  As a result, the message is being dropped.  If this is not desired, then update your HTTP binding to support a different AddressingVersion.</faultstring></s:Fault></s:Body></s:Envelope>

This error responds to this line of my xml request
   <s:Header>
              <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IReportsListsService/GetClients</Action>
   </s:Header>

Full code: here

A: The problem was missing
xmlhttp.setRequestHeader('SOAPAction', "http://tempuri.org/IReportsListsService/GetClients");