text:
Q: How to anchor sprites of different heights to the same Y position I have multiple sprites of different heights but I want them to all look like they're standing on the same floor (y position). For example to make my first sprite look like he's standing on the floor I have to position him at
CGPoint(x: self.frame.midX, y: 200)

But my other sprite who is slightly different size, to make him look like he's standing on the same floor I have to position him at
CGPoint(x: self.frame.midX, y: 150)

Is it possible to anchor different sized sprites to the same y position? Like anchor the bottom of the sprite to the floor so no matter how big or small the sprite, the bottom will always be at the same y value?
So for example no matter the height of the sprite, if I set a Y of 200 for example, their feet will always be at Y of 200 and their body will grow upwards from there

A: If you're using SKSpriteNodes, yes, there is an easy way to do this.
Each SKSpriteNode has a property called "anchor point". In design terms, this is the origin, the point from which the object is rotated.
It's also the point in the parent (the scene, presumably) a sprite uses to determine where it's positioned when you're setting its position values.
This anchor point is expressed in terms of 0's and 1's, in a bottom left to top right coordinate system.
ie an anchor point of (0, 0) is the bottom left of any SKSpriteNode, whilst (1, 1) is the top right.
Most sprites default to an anchor point of (0.5, 0.5), which is the middle.
Your positioning is compensating for this middle anchor point by the amount of height in your objects, and that's how you're getting them to the same y position (at their base) in your scene.
You can either compensate for the height of the object when placing it mathematically (or manually, as you are), or set the anchor point to the bottom of your sprites. Both will achieve the same effect.
eg. Set an anchor point of (0.5, 0) and your sprite is anchored at the bottom middle. Do this to all your sprites, and you can give them the same y position value, and they'll all be resting on that "floor", regardless of their height.
Here's a thorough breakdown of this, and its implications and possibilities:
http://www.garethelms.org/2014/06/help-with-spritekit-position-and-anchorpoint/


text:
Q: receive another android phones gps location through SMS i am trying to create an app that in theory will track an animal who has a gps chipped collar and display it on a map.
i currently have the map running showing the users current position however need to also display the "animal"(test phone).
i plan on using another phone as an example for the report however am unsure how to receive the other phones gps coordinates.
i was advised to uses sms messages instead of the internet servers as this may be too complicated for my timescale.
what i want to know, is if it is possible to get my app to send a SMS to another phone and request its GPS location and receive it via a SMS and display on a Google map?
if it is do you know of a tutorial to do so.
Any information would be greatly appreciated.
Thank You in advance.

A: It's not very simple and fast to implement it. First you need a component(Could be a broadcastReceiver) on the test phone "waiting" for the sms. You could register your receiver in order to trigger the sms event and check for the sender for example, or the text itself to see if it's a "request-gps" sms. When you receive the sms you could start a Service to track your gps location, and when you get it, you could reply to this number with the location. In your application (which send firstly the sms) you receive the sms with the gps location and you could display the position in a map.
So the user send the sms:
smsManager.sendTextMessage(smsNumber, null, requestGps, null, null);

On the "animal side" there is the receiver:
   @Override
      public void onReceive(Context context, Intent intent) {

        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String sender = "";
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                sender += msgs[i].getOriginatingAddress();
            }
        }
  }

On the service (Always "animal" side) you register for GPS location and then you reply to the SMS
smsManager.sendTextMessage(smsNumber, null, gpsLocation, null, null);

And in user side you receive the sms exactly as the "animal" does, and then you display the gps coordinates on your map

A: This is quite possible. What you need is receiver with RECEIVE_SMS filter on both phones. The first app can send SMS with some specific code to the phone on tracking side. In the onReceive method, you can check if the SMS contains your code and if it matches, you can start tracking location by creating a LocationManager object and registering a listener using requestLocationUpdates method. In the onLocationChanged method, you can send an SMS back to the first mobile the latitude and longitude details.
The receiver in the first mobile can parse this latitude and longitude values and show it in your application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve COM ProgID from exe without registering it Background:
I would like to extract the COM data from a VB6 application so I can register it correctly (according to Microsoft best practice) the application.  I am using WiX 3.0 and heat.exe will not extract the data (known issue with heat)  and I do not have ready access to the associated TLB file.  The VB6 application does not have compatibility turned on so it regenerates the COM GUIDs every build (They want to have the application be able to run side by side with an older version.)
I created a C# application that will collect the TypeLib, interface and CoClass information from the VB6 application without registering it and create a wxs file for candle to use.  My company has several other older applications like this and I would like to make it a more generic solution.
The Issues:
1.Is there a way to collect the 'true' ProgID (programmer intended one) from the application with out the project or TLB file and without registering it?
2.Is there a way to find out the intended Threading Model from a DLL without registering it? (I intend that it can handle all COM active items, might as well be complete)
Thank you.

A: Yes and no.
As far as I know, there's no generic way to get ProgIDs out of a typelib or COM server.
The entry point for DLLs is DllRegisterServer which is supposed to write registration information to the registry, and for EXE servers they usually have a command-line argument that has the same implication.
Type libraries happen to contain a description of all interfaces and coclasses in the component, but they rarely contain the human-readable ProgID.
The only clear way I can see and recommend is to override HKCR\CLSID key to point to somewhere temporarily, and then call DllRegisterServer. As registry key overrides are process-local this will only work for in-process (DLL) servers.
See http://msdn.microsoft.com/en-us/library/ms724901(v=VS.85).aspx for info on overriding registry keys.
Then inspect the scratch registry and see what changes were made, e.g. CLSID<->ProgID mappings, threading model, etc.


text:
Q: Does a free group $F$ of finite rank $n$ have finitely many retracts (as a subgroup)? A subgroup $H$ of a group $G$ is called a retract of $G$ if there exists an epimorphism $r:G\to H$ such that $r(h)=h$ for all $h\in H$.
Does a free group $F$ of finite rank $n$ have finitely many retracts (as a subgroup)? Does a retract of a free group $F$ of finite rank have a specific form?
What I've tried: Let $G=\mathbb{Z}$. Let $H\neq 1$ be a retract of $G$. Then there is an epimorphism $r:G\to H$ such that $r(h)=h$ for all $h\in H$. So $G=H\ltimes \mathrm{ker}(r)$. Since $\mathrm{ker}(r)\lhd G$, if $\mathrm{ker}(r)\neq 1$, then we have $\mathrm{ker}(r)=n\mathbb{Z}$, hence $H\cong \mathbb{Z}_n$ which is a contradiction to the fact that $H$ is a subgroup of free group $\mathbb{Z}$. Thus $\mathrm{ker}(r)=1$, and then $H=\mathbb{Z}$. We conclude that either $H=1$ or $H=G$.

A: I close this question by giving the answer of @MoisheKohan in the comments: For $n\geq 2$, the statement is false because each free factor of $F_n$ is a retract and there are infinitely many free factors. Thanks to @MoisheKohan for pointing this out.


text:
Q: Publish web app without webjobs In visual studio 2015, I am deploying a site with three webjobs by right-clicking the web app and publishing (stop judging me! I know you do terrible things too!). I have multiple publish profiles (.pubxml) set up; Is there a way in one of the profiles to publish only the website/app and skip the webjobs?

A: Of course you can, find <ExcludeApp_Data>False</ExcludeApp_Data> and change value to True.
Note that if you have already published webjobs to website, this settings won't remove them.


text:
Q: Validate user input against ArrayList I am having issues with the following part of my code.
when "nn" is entered  i get invalid code.
when valid code is entered i get invalid code however this only happens once.
program doesn't seem to work as intended. Please assist.
    System.out.println("ENTER CODE (nn to Stop) : ");
    ArrayList<Product> list = new ArrayList<Product>();
    .
    .
    .
    .

    ArrayList<Code> codeList = new ArrayList<Code>();

    for (Product product : list) {
        System.out.print("CODE : ");
        String pcode = scan.next();
        if (pcode.equalsIgnoreCase("nn")) {
            break;
        }

        if (!(code.equalsIgnoreCase(product.getCode()))) {
            System.out.println("Invalid code, please enter valid code.");
            System.out.print("CODE : ");
            pcode = scan.next();

        }

        System.out.print("QUANTITY : ");
        int quan = scan.nextInt();
        while (quan > 20) {
            System.out.println("Purchase of more than 20 items are not allowed, please enter lower amount.");
            System.out.print("QUANTITY : ");
            quan = scan.nextInt();
        }
        codeList.add(new Code(pcode, quan));
    }

A: You want continue instead of break.
Also, you should only call code = scan.next() once inside the loop; otherwise you'll skip over some items.
String code = scan.next();
boolean match = false;
for (Product product : list) {
    if (code.equalsIgnoreCase(product.getCode())) {
        match = true;
        break;
    }
}
// now only if match is false do you have an invalid product code.

Update:

I still can't get this to work. What I am trying to do is test user
  input to make sure that product code exists, if not prompt that the
  product code entered is invalid and asks for correct code. I also need
  to have the condition to stop order when "nn" is entered. I have tried
  while loops, do-while loops etc. i can't seem to get it right. Please
  assist. My problem is with writing code for multiple conditions. When
  one is working correctly the other isn't.

while (true) {
    final String code = scan.next();
    if (isExitCode(code)) {
        break;
    }
    if (!isValidCode(code)) {
        System.out.println("Invalid code, please enter valid code.");
        continue;
    }
    int quantity = -1;
    while (true) {
        quantity = scan.nextInt();
        if (!isValidQuantity(quantity)) {
            System.out.println("bad quantity");
            continue;
        }
        break;
    }
    // if you've got here, you have a valid code and a valid
    // quantity; deal with it as you see fit.
}

Now you just need to write the methods isExitCode(), isValidCode(), and isValidQuantity().


text:
Q: Woocommerc rename field name in admin Order details How to rename of label "Phone" in admin order details and in quick view without plugin?
1) In Admin order:

2) Quick view order:

A: There are 2 solutions that i can thinkof.
First solution is to generate your own po/mo files and set phone to be w/e you want. This solution will require almost 0 maintance.
Second solution would be with coding. This also is almost 0 maintance since we will only copy/past if there are any changes. For the overwriting part if someone else have better solution lets share.
//With following filter we can override billing phone label
add_filter( 'woocommerce_admin_billing_fields' , 'order_admin_custom_fields',99,1 );
function order_admin_custom_fields( $fields ) {
    $fields['phone'] = array(
        'label'=> __('Mobile phone','text-domain')
    );
    return $fields;
}
// For quick view order is a bit more complicated since we dont have filter to use.
//So we are removing the entire template and load a new one which is copy/paste from the original.
//Location of the file is woocommerce/includes/admin/list-tables/class-wc-admin-list-table-orders.php
//The only difference is changing the phone text to whatever we want.
remove_action('admin_footer','order_preview_template');
add_action('admin_footer','order_preview_template_new');

function order_preview_template_new() {
?>

<?php
}


text:
Q: SQL INSERT INTO statement not inserting data into database I could not figure out the wrong in this code. Yet, this insert into query does not feed data to my SQL Server database.
Try
    Dim connetionString As String
    Dim cnn As SqlConnection
    connetionString = "Data Source=LAPTOP-7I5LAV8T; Initial Catalog=dbTailorMadePeople; User ID=sa; Password=sa1111"
    cnn = New SqlConnection(connetionString)
    cnn.Open()
    Dim cmd As New SqlCommand With {.CommandText = "INSERT INTO rsMember(firstName, middleName, lastName, memberID) VALUES ('" & txtFirstName.Text & "', '" & txtMiddleName.Text & "', '" & txtLastName.Text & "', '" & txtID.Text & "')", .Connection = cnn}

    cmd.ExecuteNonQuery()

    MsgBox("Success")

Catch ex As Exception

End Try

A: Since you are using ADO.Net , always parameterized your query to avoid SQL Injection.
ex

Dim query as String = String.Empty
query &= "INSERT INTO rsMember(firstName, middleName, lastName, memberID)  "
query &= "VALUES (@firstName,@middleName, @lastName, @memberID)"

Using conn as New SqlConnection("yourConnectionStringHere")
    Using comm As New SqlCommand()
        With comm
            .Connection = conn
            .CommandType = CommandType.Text
            .CommandText = query
            .Parameters.AddWithValue("@firstName", strFName)
            .Parameters.AddWithValue("@middleName", strMName)
            .Parameters.AddWithValue("@lastName", strLName)
            .Parameters.AddWithValue("@memberID", strMemberID)
        End With
        Try
            conn.open()
            comm.ExecuteNonQuery()
        Catch(ex as SqlException)
            MessageBox.Show(ex.Message.ToString(), "Error Message")
        End Try
    End Using
End USing

A: There is an error in this line:
Dim cmd As New SqlCommand With {.CommandText = "INSERT INTO rsMember values (firstName, middleName, lastName, memberID) VALUES ('" & txtFirstName.Text & "', '" & txtMiddleName.Text & "', '" & txtLastName.Text & "', '" & txtID.Text & "')", .Connection = cnn}

Note: Missed Values in sql query
Tip: 1) Before executing the Sql query, temporarily save your sql query in a string.
Dim SqlQuery as string ="Your insert query"
Dim cmd As New SqlCommand With {.CommandText = SqlQuery  , .Connection = cnn}

2) use breakpoint at this line
Dim SqlQuery as string ="Your insert query"
Break while running, get the value from SqlQuery variable and check whether the query is working.


text:
Q: Jquery settimeout not waiting to redirect Well, I am currently trying to set a timer on a redirect to another webpage, however when I use settimeout it does not work.
    setTimeout(function() {
        window.location.replace("https://github.com/Riggster"");
    }, 2000);

It redirects me, however it does not wait two seconds. And I am not sure why.
$(document).ready(function () {
    var gsb = $('.github-side-bar');
    var rd = $('.redirectnotice');
    gsb.on('click' , function() {
        $('html, body').animate({
            scrollTop: 0
        }, 500);
        rd.show('slow');
        setTimeout(function() {
            window.location.replace("https://github.com/Riggster"");
        }, 2000);
    });

Associated HTML:

Redirecting you

A: You need to prevent the default action of the anchor
gsb.on('click' , function(e) {

    e.preventDefault();

    $('html, body').animate({
        scrollTop: 0
    }, 500);
    rd.show('slow');
    setTimeout(function() {
        window.location.replace("https://www.google.com");
    }, 2000);
});

A: You may need to show us more of your code to track down the issue.  What you have there looks fine.  I tested it here and it works perfectly in Chrome, FF, and IE.
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Test</title>

wait, then redirect...


text:
Q: PIP --upgrade not working Python3.4.4 I've looked at a number of posts on this and nothing seems to fix it. I initally started out on Python 3.5, heard that there were several unresolved issues with pip and so I uninstalled and reinstalled Python 3.4.4 -
I want to use pyautogui for a work task, but when I try to install pyautogui directly after Python3.4.4 installation it tells me the PIL Module can't be found. I read in another article to install 3.4.4 and update pip, then install pyautogui. Cool, so I installed 3.4.4, I needed to upgrade pip. So I entered in
Scripts\pip.exe install --upgrade pip

from the command line in the root folder. Every time I get this
 Exception:
Traceback (most recent call last):
  File "h:\python34\lib\shutil.py", line 527, in move
    os.rename(src, real_dst)
PermissionError: [WinError 32] The process cannot access the file because it is
being used by another process: 'h:\\python34\\scripts\\pip.exe' -> 'C:\\Users\\z
jf\\AppData\\Local\\Temp\\pip-qo75adq9-uninstall\\python34\\scripts\\pip.exe'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "h:\python34\lib\site-packages\pip\basecommand.py", line 211, in main
  File "h:\python34\lib\site-packages\pip\commands\install.py", line 311, in run

  File "h:\python34\lib\site-packages\pip\req\req_set.py", line 640, in install
  File "h:\python34\lib\site-packages\pip\req\req_install.py", line 716, in unin
stall
  File "h:\python34\lib\site-packages\pip\req\req_uninstall.py", line 125, in re
move
  File "h:\python34\lib\site-packages\pip\utils\__init__.py", line 315, in renam
es
  File "h:\python34\lib\shutil.py", line 540, in move
    os.unlink(src)
PermissionError: [WinError 32] The process cannot access the file because it is
being used by another process: 'h:\\python34\\scripts\\pip.exe'

Thing is, nothing is running in that folder. I don't have windows explorer open to it, I don't have anything accessing any files in there, and I'm obviously running it from an upper level directory using the command line. So I have no idea why it's saying that pip.exe is being used by another process. The only process it's being run by is itself and if that's the issue, then how in the world are you supposed to upgrade it?
**EDIT: ** Per the accepted answer, in order to get PIP to update I used the command
python -m pip install -U pip
Once that worked I tried to install pyautogui yet again. It still said that PIL module could not be found. PIL is the Python Image Library. I installed it using
python -m pip install image
And once that worked I then installed pyautogui like so
python -m pip install pyautogui

A: To upgrade pip on windows google "upgrade pip on windows" or alternately run this in a command prompt:
python -m pip install -U pip

This is a known issue on windows where an executable can't be overwritten while it's running. Sorry no links handy but it should be easy to find more details.

A: Problem: You are using pip version 18.1, however version 19.0.1 is available. You should consider upgrading via the 'python -m pip install –upgrade pip' command.
Solution: In order to upgrade PIP in Windows, you'll need to open the Windows Command Prompt, and then type/copy the command below. Note that the following method would only work if you already added Python to Windows path. Don't worry if you don't know what it means, as I'll show the full steps to upgrade pip in windows in the next section.
python -m pip install --upgrade pip


text:
Q: How can I allow an output event from one Angular element to update the value of another Angular element? Please note that this question has to do with Angular Elements, which is detailed here. This functionality allows for the creation of HTML elements from compiled Angular components.
I am working on modernizing an old web application piece-by-piece. The target framework is Angular, and so to ease the transition we are creating Angular elements to replace difference pieces of our old code.
The basic structure is as follows: I have a menu-bar component whose output I want to use to update a content component.
menu-bar.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  templateUrl: './menu-bar.component.html',
  styleUrls: ['./menu-bar.component.css']
})
export class MenuBarComponent implements OnInit {
  @Output() menuItemId = new EventEmitter()

  constructor() { }

  ngOnInit() {
  }

  sendId(id: number) {
    console.log(id)
    this.menuItemId.emit(id)
  }
}

content.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { HttpService } from '../../services/http.service';
import { Data } from '../../classes/data.model';
import * as chemReact from '../../classes/reactionResult.model';

@Component({
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {
  @Input() initialContentId: number;

  initialContent: Data;

  constructor(
    private httpService: HttpService) { }

  ngOnInit() { }

  ngOnChanges() {
    console.log("Content ID was changed to " + this.initialContentId)

    this.httpService.getData(this.initialContentId)
      .subscribe(c => {
        console.log("Returned from subscription")
        this.initialContent = Object.assign(new Data(), c);
        console.log("Initial content is " + this.initialContent.name);
        this.initialContent.createdData.subscribe(data =>
            console.log("Created Data is " + data))
        this.substances.push(this.initialContent);
      });
  }
}

When running the Angular project as a standalone app, this works properly. However, after I've exported the components as elements and included them in my legacy project:

    <menu-bar></menu-bar>

    <content
        initialContentId="menuItemId"></content>

the content control does not update when the input is changed.
Possibly Helpful Information

*

*When I click on an item in the menu component, all of my console logging statements get called, so I know I'm properly receiving and then sending the event.

*Say I click "Menu Item 1". When I click "Menu Item 2", the results I expect for "Menu Item 1" will show up in the control. So I know that the content component is getting the data set, it's just not updating when I expect it to.


text:
Q: Laravel 5 Form Request manually specify field name to be displayed In Laravel's form request, how can I manually assign the field name to be displayed on error?
This is my blade.php file
<input type="text" name="txtConfigKey" id="txtConfigKey" class="form-control" placeholder="Config Key" />

Then on my request file:
    public function rules()
    {
        return [
            'txtConfigKey' => 'required'
        ];
    }

Then the output is: "The txt config key field is required."
Notice that it converted the "txtConfigKey" with spaces. Is there a way for me to manually specify what would the field be?
In CodeIgniter, I can do something like this:
$this->form_validation->set_rules('txtConfigKey', 'Config Key', 'required');

Wherein the first parameter is the name of the field and the second parameter is the name of the field that I want to be displayed on the error message.

A: If you are using form request then there is a method called messages().
You have to override it with your custom error messages like:
public function messages()
{
    return [
    'txtConfigKey.required'=>'The Config Key is required'
    ];
}


text:
Q: Find indices of unique array in a non-unique array with non-numeric items I have the following array:
import numpy as np
a = np.array(['a', 'b', 'c','a','a','d','e'])
b = np.array(['a','b'])

actual data stored  in the arrays are uuids, example:
123e4567-e89b-12d3-a456-426614174000

I would like to search b in a and get the indices:
array([0, 3, 4, 1])

this solution can work for me:
np.nonzero(b[:, None] == a)[1]

but the problem is I'm dealing with huge arrays (15M in the non-unique and 150k in the unique sub-array with str_ type), so for the given operation I would need 1.8TB of memory which I don't have.
any idea how can I solve this issue or workaround the memory restrictions with my own solution?
thanks.

A: Since the order of the indices isn't really relevant, you can use np.isin, and then np.flatnonzero on the results to retrieve the indices where the returned array is True:
a = np.array(['a', 'b', 'c','a','a','d','e'])
b = np.array(['a','b'])

np.flatnonzero(np.isin(a,b))
# array([0, 1, 3, 4], dtype=int64)

This should be reasonably fast and memory efficient (O(len(a))) unlike the broadcasting approach (O(len(a)*len(b))), even with the array sizes mentioned in the question:
a = np.random.randint(0,15e2,int(15e6))
b = np.random.randint(0,150e3,int(150e3))

%timeit np.flatnonzero(np.isin(a,b))
# 2.58 s ± 28.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

A: Here's one based on view+lookup -
def map_indices_conststring(a, b):
    a2D = a.view(np.uint8)[::4].reshape(len(a),-1)
    b2D = b.view(np.uint8)[::4].reshape(len(b),-1)

    n = b2D.shape[1]
    lookup = np.zeros(256, dtype=bool)
    mask = np.ones(len(a), dtype=bool)
    for i in range(n):
        lookup[b2D[:,i]] = 1
        mask &= lookup[a2D[:,i]]
    out = np.flatnonzero(mask)
    return out

Sample run -
In [46]: a
Out[46]:
array(['a123', 'b232', 'c434', 'b235', 'a123', 'd223', 'b232'],
      dtype='<U4')

In [47]: b
Out[47]: array(['a123', 'b232'], dtype='<U4')

In [48]: map_indices_conststring(a, b)
Out[48]: array([0, 1, 4, 6])

Timings on string data with 1.5M non-unique and 15K unique sized string arrays -
In [2]: a = np.random.randint(10000000000,99999999999,(1500000)).astype(str)

In [3]: b = np.unique(np.random.randint(10000000000,99999999999,(15000)).astype(str))

In [4]: %timeit map_indices_conststring(a, b)
266 ms ± 2.63 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# @yatu's soln
In [5]: %timeit np.flatnonzero(np.isin(a,b))
1.03 s ± 3.75 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


text:
Q: Get count of selected items from asp listbox using jquery I am trying to get the count of selected items from an asp listbox using jquery but can't figure out how to do it. this is how I have it as of now, but I get "Cannot get property length of undefined or null reference" on selectedOptions property. var lb fills with
objectHtmlSelectElement, so that seems right.
function CheckSelectionCount(sender, args) {
            var lb = document.getElementById(sender.controltovalidate);
            var count = lb.selectedOptions.length;
            args.IsValid = count >= 1 && count <= 5;
}

Many similar questions
 remedy this using a selector combined with the :selected attribute, but I think I need to leverage the sender argument and store it in a variable.
I'm sure this will be easy for the experts on here! Thanks in advance

A: jQuery to get the count
function CheckSelectionCount(sender, args) {
    var count = $("#" + sender.controltovalidate + " option:selected").length;
    args.IsValid = count >= 1 && count <= 5;
}

Without jQuery
function CheckSelectionCount(sender, args) {
    var lb = document.getElementById(sender.controltovalidate);
    var opts = lb.options;
    var count = 0;
    for(var i=0; i<opts.length; i++) {
        if(opts[i].selected) count++;
    }
    args.IsValid = count >= 1 && count <= 5;
}


text:
Q: reorder database when reorder UitableView cell i am using reordering in UITableView in iOS. i want that my database should also reorder when i reorder in UITableView cell. I am not able to find anything helpful tutorials till now. How can i make changes in database with change in order in UITableview. please help.

A: I dont think there is any in built way to do this.
You can do something like this.
1.Add new column and name it some thing like 'order' or 'sort'
2.insert sequence number in this 1,2 ,3 ....
3.when u change order in UITableView update this column.
4.now when u select data sort it by this column


text:
Q: strtotime() for MySQL date comparison with Joomla Development Working on a syntax issue, I'm trying to compare today's date to the event_start_date field in the database.  Here is my Joomla query:
public static function getEventsList() {

    $db = JFactory::getDbo();
    $query = $db->getQuery(true);

    $today = date("Y-m-d");

    $query
            ->select('*')
            ->from($db->quoteName('#__my_table'))
            ->where('event_start_date' . ' >= ' . $today);

    $db->setQuery($query);
    $results = $db->loadObjectList();

    return $results;
}

event_start_date table in the database is a Date column, and formatted like this:  2015-10-10
I think I need to convert $today to strtotime or DateTime so that I can properly compare today's date variable against the MySQL field.
There are a million posts about strtotime, but I can't get the right syntax.  Any advice?


text:
Q: (ASP.NET )Store currently selected Asp:Listbox item as string I am trying to store the text of the currently selected item of an Asp:Listbox in a variable. The value is always stored a null, or I receive the error
"System.NullReferenceException: 'Object reference not set to an instance of an object.'"
Listbox declaration below
<asp:ListBox ID="lbModules" runat="server" AutoPostBack="true" OnSelectedIndexChanged="lbModules_SelectedIndexChanged" ></asp:ListBox>

Code for SelectedIndexChanged below
`
protected void lbModules_SelectedIndexChanged(object sender, EventArgs e)
        {
            string code = lbModules.SelectedItem.Text;
            int week = 1;
            UpdateTextBox(week, code);
        }

`
The listbox is being populated elsewhere with a method looping and adding values with listbox.items.add
I have tried
listbox.SelectedItem.Text, listbox.SelectedValue.Text, listbox.SelectedItem.Value, listbox.SelectedValue.Value,
Nothing I try returns the text of the selected value, always throws an exception or returns null.

A: Ok, first up, it does not make much sense to use the selected index change event UNLESS you have a autopostback=true.
So, if the user is to enter some info into text box etc., then the user say hits your submit button, then I not really sure of any value of using the selected index change event. But, with autopost-back it does.
hence, this markup:

Select Hotels

        <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="true"
            DataValueField="ID"
            DataTextField="HotelName"
            OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
            Width="190px" Height="160px" >
        </asp:ListBox>

Selected value

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

And code behind:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadData();
    }

    void LoadData()
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            string strSQL =
                "SELECT ID,HotelName FROM tblHotelsA ORDER BY HotelName";
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                conn.Open();
                DataTable rstData = new DataTable();
                rstData.Load(cmdSQL.ExecuteReader());
                ListBox1.DataSource = rstData;
                ListBox1.DataBind();
            }
        }
    }

    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ListBox1.SelectedIndex >= 0)
        {
            TextBox1.Text = ListBox1.SelectedItem.Value;
            TextBox2.Text = ListBox1.SelectedItem.Text;
        }
    }

Note VERY but BEYOND careful that we ONLY load the listbox ONE time. Since for any event trigger on a page, the on-load event fires first, and THEN you code stub for the given button or event. Thus, if you load up the lb, or grid or in fact "any" data, but fail to include the all important if !IsPostBack code stub?
Then you cannot actually build a working web page!!! (so, my last 200+ web pages I have built ALL have and ALWAYS have that real first page load, since as noted, the on-load event triggers always on post-backs. So, if you load up the lb or anything again, it will blow out and overwrite your selections you have made).
So, above results in this:

However, if user is to enter data, select things, and THEN hit a submit button, then of course you probably would remove the autopostback = true. And place the above code behind the button click, and NOT use the selected index change event.
Even if you add items to the lb with code, the above rules still apply.
So, say this listbox:

Select Hotels

        <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="true"
            OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
            Width="190px" Height="160px" >
        </asp:ListBox>

Selected value

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

We still need the autopostback, and thus this code:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadData();
    }

    void LoadData()
    {

        for (int i = 1; i <= 6; i++)
        {
            string MyText = "Item # " + i;
            ListBox1.Items.Add(new ListItem(MyText, i.ToString()));
        }
    }

    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ListBox1.SelectedIndex >= 0)
        {
            TextBox1.Text = ListBox1.SelectedItem.Value;
            TextBox2.Text = ListBox1.SelectedItem.Text;
        }
    }

And now we get/see this:

So, either you are missing autopostback, or you are re-running your code to fill the lb each time on post-back, and that will as noted blow out any selecting the user makes.


text:
Q: Custom content type I have a custom content type create in visual studio 2010:
custom http://img204.imageshack.us/img204/439/customf.jpg
Here you have my custom content type....
I would like to use this content type in a sub-site in the same site.
Now I have this:
http // XXXXX/........../Forms/AllItems.aspx
I would like to use this content type in
http //XXXXX/SUBSITE...../Forms/AllItems.aspx...
In the code I associated my custom content type to the first document library like this:
 <CustomAction
Id="SPTest.CustomMenuItem.ButtonClicked"
Location="CommandUI.Ribbon.ListView"
RegistrationId="{F9658A9F-3F04-48BD-A14A-9EBAF5DE9EE8}"
RegistrationType="List"
>

Where RegistrationId is the Id of document's library site, but when I put in this RegistrationId the Id of the subsite document library... nothing happens...
Another Question: When I selected an item in this document library, Documents tab will be show.... IS there some way to display PATOne Rule Engine instead of documents tab???

A: That is a "Custom Action", not a "Custom Content Type". Hint: the Content Type will contain a 'ContentType' element. It will look something like:
<ContentType ID="0x01AB"
     Name="MyCustomContentType"
     Group="MyCustomContentTypeGroup"
     Description="Customized Content Type"
     Version="0">
   <FieldRefs>
    <FieldRef ID="{8c06beca-0777-48f7-91c7-6da68bc07b69}"
     Name="Created"
     DisplayName="Field1" />
    <FieldRef ID="{1df5e554-ec7e-46a6-901d-d85a3881cb18}"
     Name="Author"
     DisplayName="Field2" />
   </FieldRefs>
</ContentType>

Further, the RegistrationId should not be a guid if it is to be registered against a content type. If Registered against a list, the RegistrationId should either be the list's type ID e.g. (101 for document libraries in the site), or possibly the GUID of a specific list (in which case the action will only work for that list). I've not tried this last one, but suspect it'd work. (Edit: It is described as working this way at the bottom of this discussion)
Depending on what the guid is, you may have registered the custom action for a specific list, but the list in your subsite will have a different ID, so that custom action registration will not apply to it.
In short, you can add custom actions to:

*

*A specific List, which is what I think you've done.

*All lists of a given type within a site/subsite

*A content type that you then use on those lists. (I've not tried)

To register against a content type, I would expect the registration to look like:
<CustomAction
    Id="SPTest.CustomMenuItem.ButtonClicked"
    Location="CommandUI.Ribbon.ListView"
    RegistrationType="ContentType"
    RegistrationId="0x01AB"

Note the RegistrationType and RegistrationId

A: This is my content type
<?xml version="1.0" encoding="utf-8"?>
 <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction
Id="SPTest.CustomMenuItem.ButtonClicked"
Location="CommandUI.Ribbon.ListView"
RegistrationId="{F9658A9F-3F04-48BD-A14A-9EBAF5DE9EE8}"
RegistrationType="List"
>
<CommandUIExtension>
  <CommandUIDefinitions>
    <CommandUIDefinition
      Location="Ribbon.Tabs._children">
      <Tab
        Id="Ribbon.PATOneRule"
        Title="PATOne Rule Engine"
        Sequence="501">
        <Scaling
          Id="Ribbon.PATOneRule.Scaling">
          <MaxSize
            Id="Ribbon.PATOneRule.MaxSize"
            GroupId="Ribbon.PATOneRule.PATOneRuleGroup"
            Size="OneLargeTwoMedium"/>
          <Scale
            Id="Ribbon.PATOneRule.Scaling.PATOneRuleScaling"
            GroupId="Ribbon.PATOneRule.PATOneRuleGroup"
            Size="OneLargeTwoMedium" />
        </Scaling>
        <Groups Id="Ribbon.PATOneRule.Groups">
          <Group
            Id="Ribbon.PATOneRule.PATOneRuleGroup"
            Description="Workflow Rules"
            Title="Workflow Group"
            Sequence="52"
            Template="Ribbon.Templates.CustomTemplateExample">
            <Controls Id="Ribbon.PATOneRule.PATOneRuleGroup.Controls">
              <Button
                Id="Ribbon.PATOneRule.PATOneRuleGroup.NewWorkflow"
                Image32by32="/PublishingImages/_t/new_jpg.jpg"
                Command="PATOneRule.NewWorkflow"
                Sequence="15"
                Description="Create New Workflow"
                LabelText="New Workflow"
                TemplateAlias="cust1"/>
              <Button
                Id="Ribbon.PATOneRule.PATOneRuleGroup.RunWorkflow"
                Image32by32="/PublishingImages/_t/play_jpg.jpg"
                Command="PATOneRule.RunWorkflow"
                Sequence="15"
                Description="Run Selected Workflow"
                LabelText="Run Workflow"
                TemplateAlias="cust2"/>
              <Button
               Id="Ribbon.PATOneRule.PATOneRuleGroup.EditWorkflow"
               Image32by32="/PublishingImages/_t/edit_jpg.jpg"
               Command="PATOneRule.EditWorkflow"
               Sequence="15"
               Description="Edit Selected Workflow"
               LabelText="Edit Workflow"
               TemplateAlias="cust3"/>
            </Controls>
          </Group>
        </Groups>
      </Tab>
    </CommandUIDefinition>
    <CommandUIDefinition Location="Ribbon.Templates._children">
      <GroupTemplate Id="Ribbon.Templates.CustomTemplateExample">
        <Layout
          Title="OneLargeTwoMedium"
          LayoutTitle="OneLargeTwoMedium">
          <Section Alignment="Top" Type="OneRow">
            <Row>
              <ControlRef DisplayMode="Large" TemplateAlias="cust1" />
              <ControlRef DisplayMode="Large" TemplateAlias="cust3" />
              <ControlRef DisplayMode="Large" TemplateAlias="cust2" />
            </Row>
          </Section>
        </Layout>
      </GroupTemplate>
    </CommandUIDefinition>
  </CommandUIDefinitions>
  <CommandUIHandlers>
    <CommandUIHandler
      Command="PATOneRule.NewWorkflow"
      CommandAction="javascript:__doPostBack('NewWorkflow', '')" />
    <CommandUIHandler
     Command="PATOneRule.EditWorkflow"
     CommandAction="javascript:
     function getId() {
       var ctx = SP.ClientContext.get_current();
       var selectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
       var key;
       var itemsSelected;
       for (key in selectedItems) {
       itemsSelected = itemsSelected + ', ' + selectedItems[key].id;
      }
      __doPostBack('EditWorkflow',itemsSelected);
     }
     getId();"
     EnabledScript="javascript:
     function singleEnable() {
       var items =
       SP.ListOperation.Selection.getSelectedItems();
       var ci = CountDictionary(items);
       return (ci == 1);
     }
     singleEnable();"
     />
    <CommandUIHandler
    Command="PATOneRule.RunWorkflow"
    CommandAction="javascript:
     function getId() {
       var ctx = SP.ClientContext.get_current();
       var selectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
       var key;
       var itemsSelected;
       for (key in selectedItems) {
       itemsSelected = itemsSelected + ', ' + selectedItems[key].id;
      }
      __doPostBack('RunWorkflow',itemsSelected);
     }
     getId();"
    EnabledScript="javascript:
     function singleEnable() {
       var items =
       SP.ListOperation.Selection.getSelectedItems();
       var ci = CountDictionary(items);
       return (ci>0);
     }
     singleEnable();"
     />
  </CommandUIHandlers>
</CommandUIExtension>


text:
Q: How to enable the link based on the fetched id in codeigniter I have two details page, each has a link "back to the listing page". There are two listing pages. Now I want when the user clicks on the link, it will take him out and will put him on previous page from where he came.
I've Interior page and Architect page, each of the page contains lots of profile and a link "view more" to end of each profile. Problem is when click on view more it redirecting to the ful details page but there is a link "back to the listing page" when click on that link i want to redirect the page to the previous page ( example: Came from interior page so click on back link option should take me to interior page )
I've done almost but need little help

      <?php
      $category = $article->category_id; // assuming this returns 1 or 0
       if($category == 1) {
         echo "( Back To List Page  )";
       } if($category == 3) {
       echo "( Back To List Page  )";
       } else {
       echo "( Back To List Page  )";
          }
           ?>

A: Window.history will be the answer for this in my option
Go back


text:
Q: Как скрыть то, что exe файл является sfx архивом Моя скомпилированная пайтон программа имеет много файлов помимо exe(компиляция в один файл делает программу нерабочей). Нужно чтобы при открытии свойств exe файла не было никаких вкладок связанных с архивом вкладок, а также права не принадлежали 7z/WinRar

A: Этого сделать нельзя без потери работоспособности.


text:
Q: Get neighbouring vertices only using depth first search How to get neighbouring vertices only using depth first search?
I am using depth first search algorithm to search a Directed Graph, my problem is that I want to make it only return the neighbors of my start vertex, instead it keeps carrying on until it reaches a dead end.
So lets say I have vertices (A, B, C, D)
And edges ((A -> B), (A -> C), (C -> D))
And I want all neighbors of Vertex A, instead of getting B and C it is also including D even though D is not Adjacent to A?
  public void dfs(int x)  // depth-first search
  {                                 // begin at vertex 0
  vertexList[x].wasVisited = true;  // mark it
  displayVertex(x);                 // display it
  theStack.push(x);                 // push it

  while( !theStack.isEmpty() )      // until stack empty,
     {
     // get an unvisited vertex adjacent to stack top
     int v = getAdjUnvisitedVertex( theStack.peek() );
     if(v == -1)                    // if no such vertex,
        theStack.pop();
     else                           // if it exists,
        {
        vertexList[v].wasVisited = true;  // mark it
        displayVertex(v);                 // display it
        theStack.push(v);                 // push it
        }
     }  // end while

  // stack is empty, so we're done
  for(int j=0; j<nVerts; j++)          // reset flags
     vertexList[j].wasVisited = false;
  }  // end dfs
  // ------------------------------------------------------------
  // returns an unvisited vertex adj to v
public int getAdjUnvisitedVertex(int v)
  {
  for(int j=0; j<nVerts; j++)
     if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
        return j;
        System.out.println("Found unvisited vertex");
  return -1;
  }  // end getAdjUnvisitedVertex()

I understand I could just store the neighbors of a Vertex when creating it but then that means I will have to make a lot of changes if I had to make changes in the future, if anyone has any ideas on how to guide me in the right direction I would be very grateful!!

A: If you represent your graph as the adjecency matrix then you should just can just take all entries that are non zero from the row corresponding to vertex A.
for(int j=0; j<nVerts; j++)
 if(adjMat[v][j]==1) System.out.println("vertex " + j);

so you do not need dfs for that.


text:
Q: Is it possible to pipe PowerShell output to a URL? Anyone know if it's possible to pipe the output of a PowerShell command into a URL request?
I would like to be able to pipe the output to a web server where I can parse out any meaningful data and store it or email it on.
The output is small, so I'm not worried about the finer details like POST limitations and character escaping, etc.

A: It depends on what you want to pipe and what type of HTTP request you want to do.
Invoke-WebRequest supports the following HTTP requests : Delete, Get, Head, Merge, Options, Patch, Post, Put, and Trace.
One caveat is that the only parameter of Invoke-WebRequest which support pipeline input is -Body .
You can check the online help of Invoke-WebRequest for more details :
http://technet.microsoft.com/library/hh849901.aspx


text:
Q: Filter results of array of objects in React, using Filter and state I am trying to filter through an array based on checkboxes. When these are ticked, it would show the elements with those attributes (viewable, reported etc). I am having issues with the filter function.
I tried using the forEach method, but that becomes messy with trying to keep the last checkboxes results the same. So I've decided to keep those values the same using state, then to filter the results based on the state. However I am being told 'Cannot read property 'state' of undefined' even though my console log shows the viewable and reported values as 1s or 0s. Not sure what's going wrong but would appreciate a solution to the problem, especially if I'm on the wrong track!
handleCheck = (e) => {
        if (e.target.checked) {
            this.setState ({
                [e.target.name]: '1'
            })
        } else {
            this.setState ({
                [e.target.name]: '0'
            })
        }
        console.log(this.state);
        this.filterPosts();

    }

    filterPosts = () => {
        this.setState ({
            parentArray: this.props.parentResults
        })

        var filterArray = this.state.parentArray.filter(function(element) {
            if (this.state.viewable===1 && this.state.reported===1) {
                return element.viewable===1 && element.reportCount>0
            } else if (this.state.viewable===1 && this.state.reported===0) {
                return element.viewable===1 && element.reportCount===0
            } else if (this.state.viewable===0 && this.state.reported===1) {
                return element.viewable===0 && element.reportCount>0
            } else if (this.state.viewable===0 && this.state.reported===0) {
                return element.viewable===0 && element.reportCount===0
            }
        });

        console.log(filterArray);
    }

The parentArray comes from the props, and definitely works as I've been able to use forEach methods. I then alter state using checkboxes, and am trying to use this to modify the filter function.
Just want the posts that are viewable or reported to appear and disappear as you check the boxes. Cheers!

A: The reason you are getting the error is that setState works asynchronously. So when you try to filter your array it is still not initialized.
You should either initialize your parentArray in constructor as
    constructor(props){
      super(props);
      this.state = {
          parentArray: this.props.parentResults,}

    }

or either just filter your this.props.parentResults in your filter posts function like
filterPosts = () => {
    var filterArray = this.props.parentResults.filter(function(element) {
        if (this.state.viewable===1 && this.state.reported===1) {
            return element.viewable===1 && element.reportCount>0
        } else if (this.state.viewable===1 && this.state.reported===0) {
            return element.viewable===1 && element.reportCount===0
        } else if (this.state.viewable===0 && this.state.reported===1) {
            return element.viewable===0 && element.reportCount>0
        } else if (this.state.viewable===0 && this.state.reported===0) {
            return element.viewable===0 && element.reportCount===0
        }
    });

    console.log(filterArray);
}


text:
Q: How to create and push values into an 3 dimensional array I need help with making a 3-dimensional array, my objective is e.g:
Just for graphic illustration :-), see row below
[category: 1[subcategories: 1[subsubcategories: 1,2],2[subsubcategories: 3,4]]
In scenario above the user has selected:
category 1
subcategories: 1
subsubcategories: 1,2
subcategories: 2
subsubcategories: 3,4

I can then with these values create a string like: 1^1:1,2^2:3,4
Hope anyone understands :)

A: Use objects instead of arrays. When you use string indexes on array elements the array gets turned into an object and some of the array methods might not work properly afterwards. Why not just use an object from the beginning then.

WARNING !!
  If you use named indexes, JavaScript will redefine the array to a standard object.
  After that, some array methods and properties will produce incorrect results.

this is taken from https://www.w3schools.com.
Here is an example of how to use it:

// Object = {} instead of array = []
var myObject = {};
myObject['category'] = {1: {subcategories: {1:[1,2], 2: [3,4] }} };

// For example
var anotherObject = {};
anotherObject['category'] = {1: {}, 2: {}};
anotherObject['category'][1] = [1,2];
anotherObject['category'][2] = [3,4];

// Edit: example 3
// ---------------
// result from database JSON format
var resultFromDB = {"category": {"1": {"subcategories": {"1": {"subsubcategories": [1,2]}, "2": {"subsubcategories": [3,4] }}}} };

// example of building new object from input
var myNewObject = {};
var type;

// go through the first level
for(var index in resultFromDB)
{
  // in case you needed this is how you would check type of input
  type = typeof resultFromDB[index];
  if((type === "object") && (type !== null)) // check if its an object
  {
    // set myNewObject[index] to new object
    myNewObject[index] = {};
    // go through second level
    for(var subIndex in resultFromDB[index])
    {
        // set myNewObject[index][subIndex] as new object
        myNewObject[index][subIndex] = {};
        // go through third level
        for(var subSubIndex in resultFromDB[index][subIndex])
        {
           // simply use an '=' to get all from that level
           myNewObject[index][subIndex][subSubIndex] = resultFromDB[index][subIndex][subSubIndex];

        }
    }
  }
}

console.log("This is the new object");
console.log(myNewObject);
console.log("\n");
console.log("This is the original object");
console.log(myNewObject);

// If you need to extract in multiple places you could make a function for quick access
function returnObject(incomingObject)
{
    var myNewObject = {};
    var type;

    // ... copy paste here all the above code from example 3 except resultFromDB

    return myNewObject;
}

// then just call it from anywhere
var theNewestObject = returnObject(resultFromDB);


text:
Q: Why do calculus textbooks gloss over absolute values? The archetypal example of this is in the equation $\frac{dy}{dx}=y.$ When solving by separation, you end up reaching the result
\begin{align*}
|y|&=C_1 e^x \\
\Rightarrow y&=C_2 e^x. \\
\end{align*}
The justification for this step, according to a lot of sources, is the fact that the + or - from the absolute value can be combined with the constant to yield a new constant. However, this falls into the pointwise trap: what prevents the function from taking the positive branch at some points and the negative branch at others? In this case, making the function piecewise destroys continuity, violating the initial differential equation, but an extra step would be needed to rigorously confirm this result.
A bigger problem arises in the case of differential equations such as $\frac{dy}{dx}\cdot \frac{1}{2}x=y,$ let's say with initial condition $(1,1).$ Again, this equation is quite easy to solve by separation of variables to yield the result $y=x^2$ as your solution - or is it? As it turns out, $y=\textbf{sgn}(x)\cdot x^2$ also satisfies the differential equation everywhere as well as the initial condition. This, to me at least, is alarming, since I've never seen these kinds of "pathological" solutions addressed in the solving of differential equations, and I can't find anything on the internet about this either, despite this being an extremely simple differential equation which has definitely appeared in textbooks or tests before. Even WolframAlpha ignores this solution and gives only $y=x^2.$ Is this something that is just commonly overlooked, or did teachers/authors think it wasn't important, or... what? I have yet to find a satisfying explanation. I have also asked my teacher, again with no satisfying answer.

A: Since your question asks specifically about absolute values, I would like to interrogate slightly a statement from it:

When solving by separation, you end up reaching the result
$|y| =C_1 e^x$

Presumably this statement is based on something you learned in single-variable calculus, viz., that $\int \frac{1}{x} \, dx = \ln |x|$.  One thing that's being glossed over here is the meaning of this latter equation.  The expression $\frac{1}{x}$ does not define a function on $\mathbb{R}$, and so it doesn't morally have a single antiderivative on $\mathbb{R}$, as the formula suggests.  Rather, it has two antiderivatives, $\ln(x)$ on $(0, \infty)$ and $\ln(-x)$ on $(-\infty, 0)$.  And sure, one can summarize this by a single formula, but it's somewhat misleading to do so.  (In my experience calculus textbooks handle this point fine, but it's sufficiently sophisticated that it washes over most single-variable calculus students, and it would be an eccentric instructor who focused on drilling the point.)
Given the issue above, one way to view what's going on is that by the time you have reached the statement $|y| = C e^x$ you have already passed through the dodgy part of the argument, which is about what happens in separation of variables at the points where one side or the other has division by zero.  The same thing happens in the second example, where division by zero happens on both sides of the separated equation.

A: There's two possible answers to your question (at least in my mind), neither of which are particularly satisfying.
$1)$ The reason calculus textbooks gloss over the things you mentioned in your question is that they are providing a relatively simple description of the math. That is, they are teaching the math and adding that level of rigor and detail wouldn't provide a better/more useful understanding of differential equations.
$2)$ The study of differential equations can trace its roots back to solving real world physics and engineering problems. The reason the finer details might be ignored is that they simply don't matter for the vast majority of differential equations encountered in real world applications. You ask "what prevents the function from taking the positive branch at some points and the negative branch at others?" Well, reality mainly. There are not any physical processes (at least none that I can think of) that such a function would describe and so we can safely ignore such a solution.
I make no judgements on the mathematical appropriateness of either of these reasonings, just that I believe them to be the most likely answers.

A: As Angelica points out in her comment, this isn't really an answer, but it's too long for a comment.  I agree with QC_CQAOA  that the most likely explanations are those given in his or her answer.
If you only require $\ y\ $ to be at least once differentiable at $\ x=0\ $, then the general solution of your second example over the whole real line is $$\ y=\big(C_1H(x)+C_2H(-x)\big)x^2\ ,$$ where $ H\ $ is the Heaviside step function. To specify both $\ C_1\ $ and $\ C_2\ $ uniquely, you need one initial condition for some $\ x_1>0\ $ (to determine $\ C_1\ $) and another for some $\ x_2<0\ $ (to determine $\ C_2\ $).  If you require $\ y\ $ to be at least twice differentiable at $\ x=0\ $, however, then you must have $\ C_1=C_2\ $ and there is a unique solution for a single initial condition given at any $\ x_3\ne0\ $.


text:
Q: Find string in file, replace everything after "="? I would like to read a file, find some strings and replace everything that is after the symbol "=" in this line.
Lets say I have a textfile like this:
name=whatever
age=150
id.from.system=10298092_42_42

path=D:\name\somewhere
whatever_A= WHATEVER

Lets say I want to change path. At first I have to find the string "path" and then replace everything after "=" somehow. Any ideas? I know I could easily read the file line by line something like this:
val source = io.Source.fromFile("C:/myfile.txt)
val lines = source.mkString
source.close()

But this is maybe not the best idea, because its not that performant to read the whole file (maybe the file got 10000000 lines, and the string is already at line 2, but my program would read the whole file. That would be unnecessary).
And there is maybe another problem: if Im searching for specific strings, like here for "name" but these strings are there several times. I want to make sure that its only valid is after the string there is an "=". Maybe I could search always for something with an "=" at the end, that could solve the problem. But I have no idea how to write this in a nice scala code.

A: You can use an iterator to only iterate until you find the line you're looking for.
val source = io.Source.fromFile("somePath").getLines
val line = source.find(_.startsWith("path="))

line will contain the first line that starts with "path=".

A: If your C:/myfile.txt contains the line path=D:\name\somewhere, you can replace D:\name\somewhere with the following code:
val lines = fromString("path=D:\\name\\somewhere").getLines // use fromFile here
for { in <- lines
      out <- if (in startsWith("path=")) "path=D:\\my\\path" else in
} yield out

This example will return the string
path=D:\my\path

You would need to use fromFile to get the lines and write the lines out to a new file.
Here's another approach that accomplishes the same thing:
val lines = fromString("path=D:\\name\\somewhere").getLines
lines.map(in => if (in startsWith("path=")) "path=D:\\my\\path" else in)


text:
Q: AoT Compiler for Python I want to get my Python script working on a bare metal device like microcontroller WITHOUT the need for an interpreter. I know there are already JIT compilers for Python like PyPy, and interpreters like CPython.
However, existing interpreters I've seen (such as CPython) take up large memory (in MB range).
Is there an AOT compiler for Python (i.e. compiling directly to native hardware through intermediary like LLVM)?
I assume such a compiler would enable Python to run much faster compared to existing implementations AND with lower memory footprint. If there is, I wonder why that solution hasn't been popularized.

A: As you already mentioned Cython is an option (However, it is true that the result is big due since the C runtime need to implement the Python functionality together with your program).
With regards to LLVM there was a project by Google named unladen swallow. However, that project is mostly abandoned. You can find some information about it here
Basically it was an attempt to bring LLVM optimizations into the runtime of Cython. E.g JITTING Python code.
Another old alternative was shed skin which compiles Python to C++. Some information about it can be found here.
Yet another option similar to shed skin is to restrict yourself to a subset of the Python language and use micropython.

A: An alternative would be to use GraalVM with Truffle AOT with Python.
It's basically  Python running on an optimized AOT for jvm.
The project looks promising. You can chek this link here:
https://www.graalvm.org/22.2/graalvm-as-a-platform/language-implementation-framework/AOT/

A: Recently came across codon,

Codon is a high-performance Python compiler that compiles Python code to native machine code without any runtime overhead. Typical speedups over Python are on the order of 10-100x or more, on a single thread. Codon's performance is typically on par with (and sometimes better than) that of C/C++.


text:
Q: Using two variables from PHP on the same WHERE in MySQL I'm trying to extract data from a MySQL server with PHP. The information has a date field like this YYYYMM (fx. 201108). My question is how would an SQL query look if I wanted to return the first or last half of a specific year? I have tired something like this, however the lessthan seems to be ignored:
SELECT * FROM `poster` WHERE mdr LIKE '2011%' AND mdr < '%06'

I'm afraid google havnt been much help for me.

A: Try th folowing:
SELECT * FROM `poster` WHERE mdr LIKE '2011%' AND MONTH(STR_TO_DATE(mdr, '%Y%m')) < 06

A: you can do this, but not with VARCHAR or TEXT:
SELECT * FROM `poster` WHERE mdr < '201106' AND mdr > '201100'

A: You can only use the % and _ wildcards with the LIKE statement.
This will work, but using any function on a field will kill any opportunity to use indexes, slowing things down.
SELECT * FROM poster WHERE mdr LIKE '2011%' AND right(mdr,2) > '06'

See:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

A: TRY ( assuming that datatype is varchar)
SELECT SUBSTRING('YYYYDDMM',FROM 0 FOR 2) AS firstHalf,
       SUBSTRING('YYYYDDMM',FROM 2 FOR 2) AS SecondHalf
FROM yourTable

References

*

*string functions

*datetime functions


text:
Q: Run Android app on PC but outside of Emulator screen I know we can Android apps on PC using emulator like Andy or Bluestack.
What I really want to know if there's a way to run the app using the emulator but outside of Emulator screen.
For example - I use fooview app which floats on screen and I want to run that on PC. Using the emulators, I'm able to run it but only inside the emulator's screen not PC GUI.

A: No, this cannot be done.
Aside from the fact that I don't know an emulator that would expose its host to android in such manner, it would be nearly impossible to make it possible for an emulator that emulates a completely different OS to do that.
That said, most apps available for Android do have either a version for PC, or the PC has a program that works similar to that app on Android.
I looked at fooView, and I'm very sure there is a program out there that allows you to count your mouse clicks and keyboard presses, and even track how far your cursor traveled.


text:
Q: Bootstrap column messed up I am using Bootstrap's grid system to make a responsive banner. The banner is split into 3 sections, banner-left, banner-right-top and banner-right-bottom. This is what it should look like:

But I seem to be getting this:

The white spaces on the col-sm-4 grid. Can anyone help??
Also, here's my code for the banner.

banner {
  margin: 0 !important;
  padding: 0 !important;
}
.col-sm-8,
.col-sm-4 {
  padding: 0px !important;
  margin: 0px !important;
}
.banner,
.row {
  width: 100% !important;
  margin: 0 auto !important;
}
.btn-banner {
  color: #fff;
  background: transparent;
  border: 1px solid #fff;
  padding: 20px 10px !important;
  transition: .5s ease-out;
  -moz-transition: .5s ease-out;
  -webkit-transition: .5s ease-out;
}
.btn-banner:hover {
  color: #fff;
  background: #2c3e50;
  border: 1px solid #fff;
  text-decoration: none;
  transition: .5s ease-in;
  -moz-transition: .5s ease-in;
  -webkit-transition: .5s ease-in;
}
.banner .row .banner-left,
.col-sm-8 {
  background: url(http://www.wgcafe.nl/wp-content/uploads/2015/04/a-vintage-red-background-with-a-crisscross-mesh-pattern-and-grunge-stains-wanlop-sonngam.jpg) no-repeat;
  background-size: cover;
  max-height: 800px;
}
.banner .row .banner-left,
.col-sm-8 .text {
  padding: 127px 5% 127px 10% !important;
}
.banner .row .col-sm-8 .text h2 {
  font-size: 30px;
  color: #fff;
}
.banner .row .col-sm-8 .text p {
  color: #fafbfb;
}
.banner>.banner-right,
.col-sm-4>.banner-right-top {
  background: url(http://xyer.co/wallpaper/19/1/red-blue-free.jpg) no-repeat;
  background-size: cover;
  max-height: 400px !important;
  margin: 0px !important;
  padding: 0px !important
}
.banner>.banner-right,
.col-sm-4>.banner-right-top .text {
  padding: 162px 10% 160px 20% !important;
}
.banner>.banner-right,
.col-sm-4>.banner-right-top .text h3 {
  color: #fff;
}
.banner>.banner-right,
.col-sm-4>.banner-right-bottom {
  background: url(http://art.ngfiles.com/images/189000/189626_nondual_red-and-blue-emissions.jpg) no-repeat;
  background-size: cover;
  max-height: 400px !important;
}
.banner>.banner-right,
.col-sm-4>.banner-right-bottom .text {
  padding: 89px 10% 89px 20% !important;
  color: #fff;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

WE ARE AN ELECTRICAL &amp MAINTENANCE COMPANY

Based in London and Kent regions.

        FIND OUT MORE

WE ARE A PROFESSIONAL TEAM

          GET IN TOUCH TODAY

WE PROVIDE MANY TYPES OF ELECTRICAL INSTALLATION, INCLUDING COMMERCIAL, INDUSTRIAL AND DOMESTIC.

The one thing that allowed this to work was CSS.. *{margin:0; padding:0;}, but that ruined everything else on the page apart from the banner. Any other alternatives to fix this??

A: I fixed it up for you:
http://codepen.io/staypuftman/pen/yeyMjo
You used containers and content elements but were trying to absolutely position content with pixel padding. That will break on different size screens. Use percentages like this:
// This is your content, pad element relative to the container
// I used percentages so, again, this would be relative to the viewport and potentially reusable
.banner .row .banner-left,.col-sm-8 .text{
  padding: 25% 20%;
}

I used vh (viewport height) units to size your boxes appropriately to the viewport. This is a more efficient way of doing what you were trying to do.
// This is your left-hand column container
// Note how I see 100vh, that just makes it as tall as your viewport
.banner .row .banner-left,.col-sm-8{
    background:url(http://www.wgcafe.nl/wp-content/uploads/2015/04/a-vintage-red-background-with-a-crisscross-mesh-pattern-and-grunge-stains-wanlop-sonngam.jpg) no-repeat;
    background-size:cover;
    max-height: 800px;
  height: 100vh;
}

A: Set the margin on the "banner-right-top" and "banner-right-bottom" to 0 !important;


text:
Q: Ninject: Intercept by attribute without deriving from InterceptAttribute I'm looking for a way to hook up an interceptor to a method call based on a certain attribute using Ninject. Ninject offers the InterceptAttribute base class to do so which is neat, however I would like to achieve this with a custom attribute. The reason is that I want to decorate certain domain service interfaces with business related attributes, so I can't have any stuff tightly coupled to a framework in it.
Is this possible?

A: You could derive from InterceptorRegistrationStrategy and override the Execute(IPlan plan) method (plus probably also RegisterClassInterceptors) to use your own attribute types instead of ninject's InterceptAttribute.
You would then need to register the implementation as a kernel component:
this.Kernel.Components.Add<IPlanningStrategy, MyInterceptorRegistrationStrategy>();

You'll probably also have to understand how InterceptorRegistrationStrategy, AutoNotifyInterceptorRegistrationStrategy and MethodInterceptorRegistrationStrategy work so you can create an implementation which works and is side-effect free.
(this does not replace the interception extensions but rather just extends it).
There is also stackoverflow answer covering a custom strategy which might be useful: Ninject Intercept any method with certain attribute?
Or of course you could could use one of the other approaches to do interception:

*

*with a binding, define interception for the whole type like Bind<IFoo>().To<Foo>().Intercept().With<MyInterceptor>() and have the MyInterceptor check whether it should intercept a given method or not.

*use conventions API or write something like that yourself, search for all of your custom interception attributes and then use this syntax:

Kernel.InterceptAround<CustomerService>(
    s=>s.GetAllCustomers(),
    invocation =>logger.Info("Retrieving all customers..."),
    invocation =>logger.Debug("Customers retrieved"));

(also see Interception with ninject)


text:
Q: FleetDB and Playbook modules are not loading due to a mysql issue? I have recently started working with Security Onion as a home project and I have been having a consistent issue with MySQL server and Security Onion not wanting to work. I can't seem to find much about this issue on the internet as I have searched on it for about two weeks. I was attempting to remedy the situation through different means, like uninstalling security onion, docker, MySQL, and all other dependencies and starting the installation process over again and I keep running into the same issue.
What I am seeing from sudo cat /root/sosetup.log is an issue between FleetDB and Playbook. Mostly all modules are being successfully installed/loading into Docker, but here is a snippet from the SO setup log where the issue lies.
I am using Ubuntu 18.04
I have a static IP setup for the server I'm working on
      ID: fleetdb
Function: mysql_database.present
    Name: fleet
  Result: False
 Comment: One or more requisite failed: mysql.so-mysql
 Started: 21:07:54.333399
Duration: 0.011 ms
 Changes:

      ID: fleetdbuser
Function: mysql_user.present
  Result: False
 Comment: One or more requisite failed: fleet.fleetdb
 Started: 21:07:54.337203
Duration: 0.006 ms
 Changes:

      ID: fleetdbpriv
Function: mysql_grants.present
  Result: False
 Comment: One or more requisite failed: fleet.fleetdb
 Started: 21:07:54.340117
Duration: 0.006 ms
 Changes:

and
      ID: create_playbookdbuser
Function: mysql_user.present
    Name: playbookdbuser
  Result: False
 Comment: MySQL Error 2003: Can't connect to MySQL server on '192.168.0.19' (110)
 Started: 21:08:07.936111
Duration: 261912.003 ms
 Changes:

      ID: query_playbookdbuser_grants
Function: mysql_query.run
  Result: False
 Comment: MySQL Error 2003: Can't connect to MySQL server on '192.168.0.19' (110)
 Started: 21:12:29.849936
Duration: 131064.848 ms
 Changes:

      ID: query_updatwebhooks
Function: mysql_query.run
  Result: False
 Comment: MySQL Error 2003: Can't connect to MySQL server on '192.168.0.19' (110)
 Started: 21:14:40.915454
Duration: 131071.339 ms
 Changes:

      ID: query_updatepluginurls
Function: mysql_query.run
  Result: False
 Comment: MySQL Error 2003: Can't connect to MySQL server on '192.168.0.19' (110)
 Started: 21:16:51.987499
Duration: 131070.6 ms
 Changes:

So, this mostly looks like a MySQL server issue that I am having and I am not sure how to go about this. I have MySQL Server installed, through sudo apt-get install mysql-server and I am able to access it, this is what it brings back when I look for Users and Databases.
+------------------+-----------+
| User             | Host      |
+------------------+-----------+
| debian-sys-maint | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

Because of these modules failing, the Security Onion setup failed and came back with Install had a problem. Please see /root/sosetup.log for details. A summary of errors can be found in /root/errors.log. Press OK to exit.
Any and all help would be very appreciated, and if you have any questions about anything regarding hardware, software, etc, feel free to ask.
Thank you

Update: This is where I am at now with this issue
I commented out the loopback address under my.cnf in /etc/mysql and that may have fixed most of the underlying issue, but I am now left with 3 playbook modules that were left 'unchanged' (broken, as I would put it). Here is the output from running so-playbook-restart:
    Function: mysql_query.run
      Result: None
     Comment: Database query_playbookdbuser_grants is not present
     Started: 16:25:17.691762
    Duration: 31.445 ms
     Changes:

          ID: query_updatwebhooks
    Function: mysql_query.run
      Result: None
     Comment: Database query_updatwebhooks is not present
     Started: 16:25:17.723549
    Duration: 30.857 ms
     Changes:

          ID: query_updatepluginurls
    Function: mysql_query.run
      Result: None
     Comment: Database query_updatepluginurls is not present
     Started: 16:25:17.754968
    Duration: 34.591 ms
     Changes:


text:
Q: How to pass implicit reference from constructor I have the following code:
class myClass(someObject:Option[SomeThing]){

  def doSomeThing(a:Int,b:Int)(implicit someOtherOption:Option[SomeThing]) = ???
}

I would like to pass someObject from constructor to doSomething method.
I can do it by making implicit reference inside a class
implicit val someImplictObject = someObject

but this way looks ugly. I guess, I can use implicitly method but I can't find correct syntax.

A: You can set default value for someOtherOption this way:
def doSomeThing(a:Int, b:Int)
   (implicit someOtherOption:Option[SomeThing] = someObject) = ???

A: Do you want to pass it when calling the method or when defining it? In the first case you just need doSomething(a, b)(someObject). In the second, you can write
def doSomeThing(a:Int,b:Int) = { // no someOtherOption parameter
  implicit val someImplictObject = someObject
  ...
}

without making someObject avaialable implicitly to the entire class.


text:
Q: appolo useMutation array of object I try to make mutation with appolo, but I don't know what's the problem.
Everything work in the playground.
const ADD_PURCHASE = gql`
  mutation addPurchaseById($data: {uniqueId: String, items: [{price: Int, name: String, description: String, image: String}]}) {
    addPurchaseById(data: $data) {
      price
      name
      image
      description
    }
  }
`;

const [addPurchaseById, {data, loading}] = useMutation(ADD_PURCHASE);

here, my cart is an array of object: name, price, description, image.
This is how I try to make the request:
const uniqueId = getUniqueId();
await addPurchaseById({
   variables: {data: {uniqueId: uniqueId, items: cart}},
});

On my server part, I have this in my typeDefs :
input ItemMutation {
        price: Float!
        name: String!
        image: String!
        description: String!
    }

    input Purchase {
        uniqueId: String!
        items: [ItemMutation]!
    }

    type Mutation {
        addPurchaseById(data: Purchase!): [Item]!
    }


text:
Q: Manupulate inline defined color with CSS or SASS Is there a way to detect a color what was defined in html and then manipulate it? (ex saturate?)
I tried using inherit, but it doesn't seem to work

.child {
background-color: saturate(inherit, 50%)
}


text:
Q: citrix keeps breaking after every OS update anybody understands why is my Citrix client always broken after seemingly every Windows update I install?

I tried downloading citrix client from www.citrix.com but when I tried to install it failed with error, that this is not the latest version. But I just downloaded it! Next time I tried to get this ICAWebWrapper.msi and store it to use it next time this happens, but it does not take it and says it's not valid installation file.
Seems like the only solution to this is to completely uninstall citrix client, download and install again! Jeez...
I have currently Citrix Workspace 1810 (18.10.0.20023). I need some solution so this stops happening. Any ideas?


text:
Q: AWS account root user not able to query Athena tables I have logged into AWS as the root account and still unable to query a Athena table that was created by another IAM User having Administrator Role. When I log off and login in as the IAM User which created the Tables, I am able to query.
Any inputs how can I grant permission to the AWS Root Account to the Athena Table (also available in the Glue Catalog) ?

A: This was because, the Admin role had not been granted access in Lakeformation to the given database which was being queried. Once, Admin role was assigned, the Account Owner was able to query the tables in the given database from Athena.


text:
Q: Why do I need to start a web server to use d3? I read various d3js tutorials and nobody is explained why to use d3 you need to start a web server (whether in Python or Node, ...).
So, why is it necessary?

A: Sometimes it's not necessary. But in general, it's a good idea to replicate the environment that your code will be viewed in so you don't run into unforeseen issues when you publish or unnecessary frustrations due to using an environment not intended for your technology.
d3 is intended to run in the browser, with some parts of it requiring to be run on a web page for certain browsers. In my experience, the issues that arise from opening a d3 page directly in browser using the file URI, i.e. file://, are split into two categories: security and schemeless urls.
Security Limitations
The file:// protocol often has additional limitations. Particularly relevant to d3 is the restrictions of using XMLHttpRequest (used in d3v4 and below) and fetch (used in d3v5), which form the basis for loading data files (e.g. using d3.csv).
Chrome, and other browsers, does not normally allow XMLHttpRequest or fetch requests to local files. You may get an error that says something like:

Cross origin requests are only supported for protocol schemes: http,
  data, chrome, chrome-extension, https

You can read more about how to enable asynchronous reading from local files and the reasoning behind disabling it by default from this answer: https://stackoverflow.com/a/18137280/6184972
Firefox, however, does not seem to have this restriction.
Schemeless Urls
Some d3 examples, particularly older ones, include d3 using this convention:
<script src="//d3js.org/d3.v3.min.js"></script>

The //d3js.org is a Schemeless Url (also known as Protocol-Relative Urls) which means that the browser can decide what protocol to use. That means it will use https://d3js.org if the loading page uses https, and (maybe) http://d3js.org if the loading page uses http.
Unfortunately when loading a file through the file:// protocol, this means that the aforementioned URL will refer to file://d3js.org/d3.v3.min.js, which usually isn't what is intended. In this case you may get an error like:

GET file://d3js.org/d3.v3.min.js net::ERR_FILE_NOT_FOUND
Uncaught ReferenceError: d3 is not defined

Using Schemeless Urls has fallen out of favor, in lieu of always using https:// instead. See: https://stackoverflow.com/a/31100809/6184972
If this is the only issue that you're running into, it may be solvable by including the protocol (i.e. changing src="//d3js.org/d3.v3.min.js" to src="https://d3js.org/d3.v3.min.js"
Additional references:
https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server#The_problem_with_testing_local_files


text:
Q: Download file and populate Grid in ASP.NET at the same time I try to use a ASP.NET button event to do two things are

*

*Populate a Grid

*Download/Export a file
The code I have got sends the file with correct data but
A. Grid is not populated
B. There is an exception Response.End();
Any clue how to fix it?
protected void ButtonExportCSV_Click(object sender, EventArgs e)
{
   try
   {
       ... Getting startDate, endDate
       List<WorkOrder> result = GetWorkOders(startDate, endDate); // It populates Grid  using  GridViewWorkOrders.DataSource = result;             GridViewWorkOrders.DataBind();

       string csv = DataHelper.ToCsv(";", result);

       var filename = "WorkOrders-ingresados-" + DateTime.Now.ToString("ddMMyyyy-HHmmsss");

       Response.Clear();

       Response.ContentType = "text/csv";
       Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".csv");
       Response.Write(csv);
       Response.End(); // The exception occurs here
    }
    catch (Exception ex)
    {

    }
}

UPDATE #1
I could get rid of the exception replacing Response.End() with
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.

but anyway grid is not populated.
ANy clue if it is possible at all?

A: ok. i think the the issue is
you are trying to send multiple Content-Type in single response which is not possible

*

*to populate Grid, server need to send html so the Content-Type: text/html

*to download a file Content-Type: text/csv
in your code you are overriding the text/html (which is default when GridView.DataBind() called) with text/csv
so the grid view html will be erased and csv content will be attached to response
alternate
first send GridView Bind response without the csv file
then once page loaded with new Grid, call a script function which calls a method in server to download csv file


text:
Q: Geocode area/neigborhood into polygon vertices I have been successfully using the Google Maps API using the R package ggmap to find location coordinates for e.g. addresses or city names.
However, Google Maps now shows areas as well, indicating their extent with a transparent red polygon, e.g. when searching for "South Extension I, New Delhi", it shows the extent of this area/neigborhood (figure below).

The Google Maps API only seems to return the coordinates of the geometric center, and the viewport (rectangular) boundary coordinates (after zooming to the area extent): https://developers.google.com/maps/documentation/geocoding/intro
How can I obtain the coordinates of the vertices of the polygon which indicates the area/neighborhood?


text:
Q: javascript - if var exist in string/array return error i have something like this
<input name="ip" id="ip">

this ip needs to be added to a list of ips that contains multiple ips in this format
<select id="iplist" name="iplist">
<option value="192.168.1.2">192.168.1.2</option>
<option value="192.168.1.10 - admin">192.168.1.10 - admin</option>
<option value="192.168.2.2 - test">192.168.2.2 - test</option>
<option value="192.168.2.9 - test1">192.168.2.9 - test1</option>
</select>

and many other values in the select list (not only the ones listed), when the button is executed and the ip needs to be added to the select option I need to check if the ip is already in the list or not, if is not to return error,
so i have something like this to get the values
var iplist = $.map($('#iplist option'), function(e) { return e.value; });

and console.log is showing all the values in array
console.log(iplist);

To get the values as string i can use
var str = iplist.join(',');

However I have a very hard time to verify if the ip is already in the select list.
Any help is really appreciated, thank you in advance for your time taken to look into this.
I'm thinking of regex to verify if the ip exist in array, but I have problems with that because there are multiple values types, delimited by comma also with space, and also without space

A: With the assumption that there is a button, which is not in the html you showed, you can use the code below. The regular expression used is from another Stackoverflow post (see Extract ip address from a string using regex
)
   var r = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/;
var inputvalue = document.getElementById("ip").value;
inputvalue  = inputvalue.match(r);
if(!inputvalue){
    return console.log("bad input");
}

inputvalue = inputvalue[0];

if($("select#iplist option").filter(function(){return $(this).val().match(r)[0] === inputvalue}).length){
    console.log("exists");
}else{
    $('select#iplist').append($('<option>', {value: inputvalue, text: inputvalue}));
}

function myFunction(){

var r = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/;
var inputvalue = document.getElementById("ip").value;
inputvalue  = inputvalue.match(r);
if(!inputvalue){
 return console.log("bad input");
}

inputvalue = inputvalue[0];

if($("select#iplist option").filter(function(){return $(this).val().match(r)[0] === inputvalue}).length){
 console.log("exists");
}else{
 $('select#iplist').append($('<option>', {value: inputvalue, text: inputvalue}));
}

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>

    <select id="iplist" name="iplist">
<option value="192.168.1.2">192.168.1.2</option>
<option value="192.168.1.10 - admin">192.168.1.10 - admin</option>
<option value="192.168.2.2 - test">192.168.2.2 - test</option>
<option value="192.168.2.9 - test1">192.168.2.9 - test1</option>
</select>

<input name="ip" id="ip"/>
<button onclick="myFunction()">add</button>
</body>


text:
Q: C++ - Unable to convert from std::basic string to bool I am trying to build a simple authentication mechanism whereby the user inputs his login credentials and his input is then compared to content in a file 'UserDB.txt'. However, when i try to iterate through the file and compare his credentials with all the lines in the file, the following error occurs :
main.cpp:86:38: error: could not convert 'credential.std::basic_string<_CharT, _Traits, _Alloc>::operator=<char, std::char_traits<char>, std::allocator<char> >((*(const std::basic_string<char>*)str.std::vector<_Tp, _Alloc>::operator[]<std::basic_string<char>, std::allocator<std::basic_string<char> > >(((std::vector<std::basic_string<char> >::size_type)i))))' from 'std::basic_string<char>' to 'bool'

Here is my code :
std::cout << "\nEnter Username: " << endl;
std::getline(std::cin,username);
std::cout << "\nEnter password: " << endl;
std::getline(std::cin,password);

credential=username + ":" + password; //Concatenates the credentials into one variable

std::fstream myFile("UserDB.txt");
if (myFile.is_open())
{
    std::istream_iterator<std::string> iter(myFile), end;
    std::vector<std::string> str(iter, end);

    // print contents
    for (int i = 0; i < str.size(); i++)
    {
        std::cout << i << ": " << str[i] << std::endl;
        if (credential=str[i]) //Error occurs here
        {
            cout << "Credentials accepted!" << endl;
        }
        else
        {
            cout << "Login fail! Wrong credentials..." << endl;
            exit(0);
        }
    }
}

I know I probably shouldn't be using the -fpermissive flag in g++ as it would probably come back and bite me in the ass later on. So how do I avoid this problem in the first place?

A: You should change credential=str[i] to credential==str[i].  You need the double = or its going to try to set credentials equal to str[i]

A: Its ok I found a work around...
std::cout << "\nEnter Username: " << endl;
            std::getline(std::cin,username);
            std::cout << "\nEnter password: " << endl;
            std::getline(std::cin,password);
            credential=username + ":" + password; //Concatenates the credentials into one variable
            std::cout << "Variable credential is :" + credential;

string array[50]; // creates array to hold names
            short loop=0; //short for loop for input
            string line; //this will contain the data read from the file
            ifstream myfile ("UserDB.txt"); //opening the file.
            if (myfile.is_open()) //if the file is open
            {
                while (! myfile.eof() ) //while the end of file is NOT reached
                {
                    getline (myfile,line); //get one line from the file
                    array[loop] = line;
                    //cout << "\n";
                    //cout << loop << ":" << array[loop] << endl; //and output it

                    if (credential==array[loop])
                    {
                        cout << "Login successful!";

                        displayMenu();
                    }
                    else
                    {
                        //Login failed...
                        loop++;
                    }

                }

                myfile.close(); //closing the file
            }
    else cout << "Unable to open file"; //if the file is not open output


text:
Q: Как передать массив в следующий promise js Хотелось бы передать в промис (тот что после комментария в коде) айди пользователя, помимо переменной lenta, сейчас передается только lenta:
'use strict';
var InstagramPrivateAPI = {};

InstagramPrivateAPI = {};
InstagramPrivateAPI.V1 = require(__dirname + '/client/v1');
InstagramPrivateAPI.Helpers = require(__dirname + '/helpers');
var acc = require(__dirname + "/client/v1/account");
var med = require(__dirname + "/client/v1/media")

var Promise = require('../bluebird');
var _ = require('../lodash/');

module.exports = InstagramPrivateAPI;

var Client = require('instagram-private-api').V1;
var device = new Client.Device('maksgmn');
var storage = new Client.CookieFileStorage(__dirname + '/cookies/maksgmn.json');

acc.searchForUser(session, 'kaigreene')
    .then(function(profile) {
        return profile.id
    })
    .then(function(someId) {
        var feed = new Client.Feed.UserMedia(session, someId);
        var lenta = Promise.mapSeries(_.range(0, 1), function() {
            return feed.get();
        })
        return lenta
    })
    //вот промис в который нужно передать lenta и айди пользователя
    .then(function(results) {
        // result should be Media[][]
        var media = _.flatten(results);
        var urls = _.map(media, function(medium) {
            return medium.params.imageVersions2.candidates[0].url
        });
        console.log(urls)
    })

Кстати вот содержимое urls (массив ссылок на изображения, после обработки
lenta):
[ 'https://scontent-arn2-1.cdninstagram.com/vp/6af16d285248021beb138878d39300f5/5C7ABDF2/t51.2885-15/e35/44564146_322592125137172_4748922672367052265_n.jpg?ig_cache_key=MTkxNTA2MzY3NjkyMDg3NzI4NQ%3D%3D.2',
  'https://scontent-arn2-1.cdninstagram.com/vp/fafb1cbedf2f2ee526b53bbbe19242e0/5BF37B8A/t51.2885-15/e15/p640x640/43536314_2236965789913961_7161939884150660296_n.jpg',
  'https://scontent-arn2-1.cdninstagram.com/vp/40aa382750e5e94a6e66d57c61381280/5C7E3B85/t51.2885-15/e35/44183920_263573101019253_2196926879861470922_n.jpg?ig_cache_key=MTkxNDI0NTA3MjY5NjQ0Mzg2MQ%3D%3D.2',
  'https://scontent-arn2-1.cdninstagram.com/vp/0f494a3130df8f5e9020adba2aaeaaa1/5C8D533C/t51.2885-15/e35/44453843_206191696937914_2654101859534502211_n.jpg?ig_cache_key=MTkxNDA4NDAwNzQ1NTExMjY3Mw%3D%3D.2',
  'https://scontent-arn2-1.cdninstagram.com/vp/891e76d89e68cef102ca82891bd79500/5C7D169D/t51.2885-15/e35/45513332_314414985821365_5157081956783129672_n.jpg?ig_cache_key=MTkxNDAxOTA3MjAzNzQ2OTc0OA%3D%3D.2',
  'https://scontent-arn2-1.cdninstagram.com/vp/8630ce604e8fc13c4b0f8dea529066c3/5BF360C2/t51.2885-15/e15/44277878_2176945342563453_2262613550408503718_n.jpg',
  'https://scontent-arn2-1.cdninstagram.com/vp/10c7c4f145e8c749d9865b9042b594ba/5C6D275A/t51.2885-15/e35/44589483_282353665729077_4185404619021489633_n.jpg?ig_cache_key=MTkxMzQ2NTEyMjA3MDQ3Mjk2NA%3D%3D.2',
  'https://scontent-arn2-1.cdninstagram.com/vp/c99a00b3d36a5013736920475b98cadb/5C8D2738/t51.2885-15/e35/44850363_1912754462367214_2546260771931931006_n.jpg?ig_cache_key=MTkxMzMwMzc3ODc4ODY5NDI0Mg%3D%3D.2',
  'https://scontent-arn2-1.cdninstagram.com/vp/b850a45fe4cc20a93da64857aee9575c/5C8D1984/t51.2885-15/e35/44634212_1869528946493492_7969207514966425740_n.jpg?ig_cache_key=MTkxMjc0MTYxMDc4NzgwOTAzNQ%3D%3D.2',
  'https://scontent-arn2-1.cdninstagram.com/vp/28e6be91c8fc996dfc47b8ea3e9781d6/5BF3CAE9/t51.2885-15/e15/43398735_115170416088701_3256913169852741968_n.jpg',
  'https://scontent-arn2-1.cdninstagram.com/vp/60e627e88aeef3ded3466d1e8a80f6fd/5BF3E157/t51.2885-15/e15/43258810_358264328256668_5269209695486174863_n.jpg',
  'https://scontent-arn2-1.cdninstagram.com/vp/85487f3fb5b805ce3fc63b40a9d5e121/5BF35B86/t51.2885-15/e15/s640x640/43504006_685794225133434_1066643086450380052_n.jpg' ]

Пробовал сделать следующим образом:
'use strict';
    var InstagramPrivateAPI = {};

    InstagramPrivateAPI = {};
    InstagramPrivateAPI.V1 = require(__dirname + '/client/v1');
    InstagramPrivateAPI.Helpers = require(__dirname + '/helpers');
    var acc = require(__dirname + "/client/v1/account");
    var med = require(__dirname + "/client/v1/media")

    var Promise = require('../bluebird');
    var _ = require('../lodash/');

    module.exports = InstagramPrivateAPI;

    var Client = require('instagram-private-api').V1;
    var device = new Client.Device('maksgmn');
    var storage = new Client.CookieFileStorage(__dirname + '/cookies/maksgmn.json');

    acc.searchForUser(session, 'kaigreene')
        .then(function(profile) {
            return profile.id
        })
        .then(function(someId) {
            var feed = new Client.Feed.UserMedia(session, someId);
            var lenta = Promise.mapSeries(_.range(0, 1), function() {
                return feed.get();
            })
            return {id : someId, fd : lenta}
        })
        //затем тут уже передаем results.fd
        .then(function(results) {
            // result should be Media[][]
            var media = _.flatten(results.fd);
            var urls = _.map(media, function(medium) {
                return medium.params.imageVersions2.candidates[0].url
            });
            console.log(urls)
        })

Но в итоге получаю пустой массив при выводе console.log(urls)
Подскажите, как можно сделать, чтобы нормально передевалось в следующий промис айди пользователя и вот эта переменная lenta

A: lenta в данном случае - тоже Promise, и чтобы передать его значение, нужно дождаться его окончания.
Например можно использовать Promise.all
return Promise.all([someId,lenta])

Тогда в следующем then, параметром будет массив с двумя элементами: 0 элемент - someId, 1 элемент - значение lenta
Получить их можно с помощью деструктуризации:
.then(function([someId, lenta]){
    var media = _.flatten(lenta);
    ...
})


text:
Q: how to find logged-in users using sorcery? Is there any way to find the currently logged-in users and delete the sessions of particular users using sorcery?
Thanks in advance.

A: From the documentation:
Below is a summary of the library methods. Most method names are self explaining and the rest are commented:

# activity logging
current_users

You can use current_users to iterate through all your users. To log them out have a look at reset_session.