text:
Q: How to remove features from geojson by mouse selection? There are these unnecessary lines in my geojson:

You see, not all the borderline was deleted when I merged two countries.
Is there any way to quickly select and remove the features in a practical manner, because there's more than one case like this I'm dealing with.
Thanks in advance.
EDIT: Deleted some of them by using Edit>"Remove Ring".
But there are still some which cannot be removed by this tool.
Is there such plugin available, that will remove lines that are irrelevant with the polygon?

A: The problem of GeoJSON and shapefiles is that they have no topology (the limit between 2 polygons is duplicate, digitized two times, see Understanding Topology and Shapefiles)
But there are other solutions than removing features by mouse:
1) you can use a GeoJSON format that encodes topology
see TopoJSON
2) If you use QGIS
The result is not correct with GeoJSON (or shapefiles)

But you only need a topological GIS where the common border exists once and is shared between the two areas as GRASS GIS. And GRASS GIS is integrated in the "Processing/Sextante" menu and you can use v.dissolve
The process is (in a transparent manner):

*

*the layer is imported and cleaned (topology) in GRASS GIS

*the command v.dissolve is applied

*the resulting layer is exported to QGIS

A: Removed the others with the "Node Tool".
Clicking a node to make nodes editable (nodes get surrounded by square boxes), then making a rectangular selection and pressing Delete does the trick.
It still has some bugs, though. Sometimes a group of connected nodes have to be deleted at a specific order, because they cannot be deleted all at once. (QGIS Dufour 2.0.0)


text:
Q: How to remove copy option from shared folders?
My organisation uses WS2012 and want to share some files over the network. My question is how to copy protect a folder/file which is being shared?
The scenario is that, I want the users to access the folders but not to copy, delete or paste anything from or on it.
Please suggest how to achieve that, any help is appreciated.
P.S : I do not prefer using any third-party tool on a server, although heard of doing it through regedit but I do no know much about the registry keys, so a little guidance is needed.
Thanks!!!

A: If you want to share something with your users, by definition you are making it available to them to read/view and copy.
Preventing delete and editing files is easy, just use Read permissions exclusively on the share or the files.
But the user will be able to copy the content of the shared files. If you want to prevent that, you have to lock down the user's workstation to prevent that the data is leaving that PC. Disallow an USB devices and removable disks, and prevent any other network access especially to the public internet.

A: I suggest to read Active Directory Rights Management Services at this link AD RMS

redpajama_set_name: RedPajamaStackExchange


text:
Q: Importing classes from dependencies to JBPM process in JBPM 7.23 Currently I am trying to import some classes in JBPM process, which are required in script task. And I am not able to add it through jbpm-console. I don't see the option of adding imports. This was possible in jbpm 6.5. Am I missing something..?

A: You can import it in the script. I also do not see it in the new modeler import for the whole process model.

A: Importing dependencies should be under settings in a jBPM project.

A: You can add imports on process level setting (where process variables are defined).


text:
Q: AppleScript to rename Safari Tab There is an option in Keyboard Maestro to rename any tab on safari with the name you want
I'm trying to do the same using AppleScript but is this even possible?
I have nothing so far, I'm guessing JavaScript would be the way to do it
tell application "Safari"
    tell front window to make new tab at after first tab with properties {URL:myLink}
    -- need to rename tab here
    tell front window to make new tab at after second tab with properties {URL:myLink}
    -- need to rename tab here
    tell front window to make new tab at after third tab with properties {URL:myLink}
    -- need to rename tab here
end tell

A: Found the solution using JavaScript:
tell application "Safari"
    do JavaScript "document.title = 'Hello!';" in tab 1 of window 1
end tell


text:
Q: setResult works MOST of the time I've worked with setResult(RESULT_OK, intent) for a while now, and am experiencing something strange.
MOST of the time, about 3/4 of the time that I enter an activity then exit from it using the following code which is ALWAYS executed:
Intent intent = new Intent();
intent.putExtra(KEY_ENVIRONMENT_SURVEY, esurvey);
setResult(RESULT_OK, intent);
finish();

In the activity being returned to, most of the time, RESULT_OK is returned, but sometimes RESULT_CANCELLED is returned, seemingly quite randomly. What could be causing this? Could finish() be called before the esurvey is attached (it's parcelable) and the default is RESULT_CANCELLED? If so how can I fix this? Use a handler and use postDelayed or check to see if RESULT_OK was set (I don't know how to do this, so please specify if that's the solution)?
Thanks!

A: Try to move this code into overridden finish() method. This will ensure it's called every time activity is finished.
@Override
public void finish() {
    Intent intent = new Intent();
    intent.putExtra(KEY_ENVIRONMENT_SURVEY, esurvey);
    setResult(RESULT_OK, intent);
    super.finish();
}

A: I'm revisiting this because I found the glitch in my application. The "back" button was very close to a button I had designated as moving to the next activity. I was allowing button presses to be registered after the first one, so sometimes the activity would seem to have completed by touching the "done" button, but was actually being navigated back to by the "back" button.
I fixed this using a boolean flag, checking to see if it was true upon a butotn press, and then setting it to true if it equaled false.


text:
Q: Import from ipython If I use IDLE with python 2.7
import cv
import cv2

and it works
but if I use ipython notebook
it gives me error

ImportError                               Traceback (most recent call
   last)  in ()
   ----> 1 import cv
ImportError: No module named cv

So how to use OpenCV from iPython?
EDIT:
from IDLE

['', 'C:\Python27\Lib\idlelib',
  'C:\Python27\lib\site-packages\pip-1.1-py2.7.egg',
  'C:\Python27\lib\site-packages\gensim-0.8.6-py2.7.egg',
  'C:\WINDOWS\system32\python27.zip', 'C:\Python27\DLLs',
  'C:\Python27\lib', 'C:\Python27\lib\plat-win',
  'C:\Python27\lib\lib-tk', 'C:\Python27',
  'C:\Python27\lib\site-packages',
  'C:\Python27\lib\site-packages\PIL']

from ipython anaconda

['', 'C:\Anaconda\python27.zip', 'C:\Anaconda\DLLs',
  'C:\Anaconda\lib', 'C:\Anaconda\lib\plat-win',
  'C:\Anaconda\lib\lib-tk', 'C:\Anaconda',
  'C:\Anaconda\lib\site-packages',
  'C:\Anaconda\lib\site-packages\PIL',
  'C:\Anaconda\lib\site-packages\win32',
  'C:\Anaconda\lib\site-packages\win32\lib',
  'C:\Anaconda\lib\site-packages\Pythonwin',
  'C:\Anaconda\lib\site-packages\setuptools-0.6c11-py2.7.egg-info',
  'C:\Anaconda\lib\site-packages\IPython\extensions']

so the questions seems to be how to install opencv in ipython anaconda? (and why it doesn't use standard python packages)

A: is your PYTHONPATH different in ipython and IDLE?
try the following
import sys
print(sys.path)

I suspect the two won't match. have you launched IDLE and ipython from the same terminal?


text:
Q: nosql dynamodb sort and partition key I have created a dynamodb server, which is nosql.
My table is like this:
+----------------------------------------------------------------------------+
|    product_id     section product_name  partition_key             sort_key |
+----------------------------------------------------------------------------+
| 0         100  electronic        mouse              0  2022-05-28 15:02:13 |
| 1         200  electronic    key board              1  2022-05-28 15:02:13 |
| 2         300        cats   cat feeder              2  2022-05-28 15:02:13 |
| 3         400        cats  cat drinker              3  2022-05-28 15:02:13 |
| 4         500        food        pizza              4  2022-05-28 15:02:13 |
+----------------------------------------------------------------------------+

This is what I did in pandas:
df['partition_key'] = df.index + len(len_tbl)

sql_format = '%Y-%m-%d %H:%M:%S'
add_date = datetime.now(pytz.timezone('America/Sao_Paulo')).strftime(sql_format)
df['sort_key'] = add_date  # creationDate

My doubt is related to the most efficient way to build either partition_key and sort_key due the shape of this table, and I'm gonna insert like 500k~1m+ lines per month, so its gonna be huge after some time.
Never worked with nosql, just sql.
Can you share some hints with me?


text:
Q: How do I change this string into a date format? I have a string from a data export that reads "2019-04-04T16:11:50Z" how do I convert this to a date format in excel?

A: Find one way below.
Have a great day

A: You can also try the below formula:
=LEFT(A1,4)&"-"&MID(A1,6,2)&"-"&MID(A1,9,2)&" "&MID(A1,12,2)&":"&MID(A1,15,2)&":"&MID(A1,18,2)


text:
Q: Convert MutbleArray to NSString in iphone SDKs - (IBAction)doUpload:(id)sender
{

    NSMutableArray *selected_items = [[NSMutableArray alloc] init];

    for (int i = 0; i<[appDelegate.notesArray count]; i++) {
        if (selected[i]) [selected_items addObject:[appDelegate.notesArray objectAtIndex:i]];

            UploadView *uploadview = (UploadView *)self.view;
            if (uploadview != nil)
            {

                [m_owner uploadString:here i want to pass the value];
                //[self dismissModalViewControllerAnimated:YES];
            }

        }
}

on my move code i want to pass the multiple values from UITableView to  [m_owner uploadString:here i want to pass the value];but i am only ble to pas the string to GDoc how to convert or split the mutbleArray to the Uplod string?
My DidSelecetRowAtIndexPathe code looks like this
 NSUInteger row = [indexPath row];

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        selected[row] = NO;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        selected[row] = YES;
    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

A: I don't understand very well what you want to do, but I think that you need the method to join the element of an array into a string, separated by commas or whatever you want.
NSString *uploadString = [[array valueForKey:@"description"] componentsJoinedByString:@","];

The method description of NSArray (as documented here) returns a string that represents the contents of the array, formatted as a property list so it's useless for your purposes (in fact it inserts newlines and the outer parentheses).


text:
Q: Missing permissions required by MobileAds.initialize? I got a warning in Android Studio:
Missing permissions required by MobileAds.initialize...
in the following Java code.
MobileAds.initialize(this,"ca-app-pub-3940256099942544~3347511713");
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);

But build is successfully done.
Why does this occur?


text:
Q: Fitting impedance of simple randles circuit to Fourier transform formula I have this simple circuit that i want to find parameters of,

and its real-world magnitude frequency response derived from impedance spectroscopy.

(magnitude frequency response.Frequency is 10-10000Hz with 10Hz step.)
R1=100Ω, R2=2200Ω, C=1E-7 F
Now, i have derived the fourier transform of this impedance:

Whose magnitude i found:

However trying to fit this last equation with matlab CFTOOL gives nonsense. What am i doing wrong??

A: Here are the new fit options: I don't know really if the function termination tolerance is significant, it seems it helps to reduce it to 1e-10.


text:
Q: Mapping interval using map function in python Given a sequence of numbers, first convert to interval and convert to dictionary as per sequence of number and then after that map it with a column in DataFrame as shown in DataFrame below.
Query-1 how to create interval from above sequence into dictionary
given_sequence = [-100, 2, 5, 8, 10, 15]# Given sequence

idict = {-100: '<2',
2:'2-5',
5:'5-8',
8:'8-10',
10:'10-15',
15:'>15'}

Query-2 how to map to a column as shown in below screen shot with dictionary and map function
import pandas as pd
import random
# create an Empty DataFrame object
df = pd.DataFrame()
df['col1'] = [random.randint(1, 10) for i in range(0, 10)]
df['mapped']  = df['col1'].map(idict)

** Expected Output**

A: Your desired outcome can be obtained using pd.cut. It creates a categorical variable from a continuous variable.
df['mapped'] = pd.cut(df['col1'], right=False, bins=given_sequence+[float('inf')],
                      labels=['<2', '2-5', '5-8','8-10','10-15','>15'])

Output:
   col1 mapped
0     6    5-8
1     1     <2
2    10  10-15
3     7    5-8
4     7    5-8
5     8   8-10
6     4    2-5
7     7    5-8
8    10  10-15
9     6    5-8

A: If values in dictionary are sorted like in sample data add bins and labels parameters from dictionary keys and values in cut:
#if necessary sorting dict by keys
#idict = {k: v for k, v in sorted(idict.items(), key=lambda item: item[0])}

df['mapped'] = pd.cut(df['col1'],
                      right=False,
                      bins=[*list(idict.keys()), np.inf],
                      labels=list(idict.values()))


text:
Q: Solve $|2x−3| < |x+5|$ I've tried solving $$|2x-3|=|x+5|$$ but the same method does not look applicable here.
$$2x-3 = x+5, \text{if}\; x>3/2$$
$$2x-3= -(x+5), \text{if} \; x<3/2$$
This method was not working here.

A: You have\begin{align}|2x-3|<|x+5|&\iff|2x-3|^2<|x+5|^2\\&\iff3x^2-22x-16<0\\&\iff3\left(x+\frac23\right)(x-8)<0\\&\iff x\in\left(-\frac23,8\right).\end{align}

A: I'll just leave a less conventional approach for discussion. Once you solve $|2x-3| =|x+5|$, leading to $x=-\frac 23 \vee x = 8$, by continuity, you know that on each interval
$$
(-\infty,-\frac23), \quad (-\frac 23, 8), \quad (8,+\infty)
$$
Either the ">" or "<" inequalities are satisfied. To determine which holds on each interval, just probe it with specific points. For instance, using $x = -1, 0, 9$, you conclude that

*

*$|2(-1)-3| > |-1+5| \Rightarrow |2x-3|>|x+5| $ on $(-\infty, -\frac 23)$

*$|2(0)-3| < |0+5| \Rightarrow |2x-3|< |x+5|$ on $(-\frac 23, 8)$

*$|2(9)-3| > |9+5| \Rightarrow |2x-3| > |x+5|$ on $(8,+\infty)$.

A: There are two nodes $x=3/2$ and $x=-5$, so we have to consider the in-equation $|2x-3|< |x+5|$ in three regions three regions
I: $x\le -5 \implies 3-2x<-(x+5) \implies x>8$ (A contradiction).
II:$-5 <x\le 3/2 \implies 3-2x<x+5 \implies x>-2/3 \implies -2/3<x\le 3/2$
III: $x>3/2 \implies 2x-3 <x+5 \implies x<8 \implies 3/2<x \le 8$
Finally, by combining I and II we get the total solution as $x\in (-2/3,8].$

A: You have
$$|a|=a,\text{if } a\ge0$$
and
$$|a|=-a, \text{if } a\le0$$
Similar holds for $b$.
So to solve
$$|a|<|b$$
you have four cases
case 1:
$$a<b, a\ge0, b\ge 0$$
case 2:
$$-a<b, a\le0, b\ge 0$$
case 3:
$$a<-b, a\ge0, b\le0$$
case 4:
$$-a<-b,a\le0,b\le0$$
So can you solve it noe?


text:
Q: pdf.js gem producing errors I am a rails novice and trying to create my web portfolio in Cloud9. I wanted to display my resume.pdf in the user browser so I installed this gem gem 'pdfjs_rails' now my app doesn't even start in cloud 9. It show the following error messages in the terminal:

Please help me. How can i revert it back? thanks

A: Doesn't look like anything related to pdfjs (no point in that direction). Are you sure you've selected the right runner in Cloud9? See:
https://community.c9.io/t/error-when-running-ruby-project/11799/4
More in general: if you think an issue would be related to a gem, you can simply remove it from the Gemfile and run gem bundle to 'revert' to a previous state.


text:
Q: AWS Signature Version 4 IAM authorization If we want to use AWS Signature Version 4 IAM authorization to add some security controls to some functions in our AWS API,
so only a salesforce user can use these particular functions.
Do salesforce support AWS Signature Version 4 IAM authorization when calling out to REST API services?

A: Salesforce now has native support for AWS v4 signature generation.
Create a new Named Credential for the service endpoint, for example:

*

*Name: S3

*URL: https://s3.us-east-1.amazonaws.com

*Identity Type: Named Principal

*Auth Protocol: AWS Signature V4

*AWS Access Key ID: [your key here]

*AWS Secret Access Key: [your secret here]

*AWS Region: us-east-1

*AWS Service: s3
Then send an HTTP request according to the API docs, eg:
String url = 'callout:S3/bucket/file.ext';

HttpRequest request = new HttpRequest();
request.setMethod('GET');
request.setEndpoint(url);
HttpResponse response = new Http().send(request);

Keys are generated from AWS Console > Security Credentials > Access Keys


text:
Q: How to transform this portion of webconfig in my web.config.release? I need to change SMTP host value on web.config transform. Here is what I have:
<system.net>
    <mailSettings>
      <smtp from="some@sioem.com">
        <network host="localhost" userName="" password=""/>
      </smtp>
    </mailSettings>
  </system.net>

How should I put it in web.release.config so instead of localhost it says 192.168.1.9 ?
I transform connection string like this but not sure how to do it with smtp
<connectionStrings>
  <add name="CoreModelContext"
    connectionString="metadata=&"" providerName="System.Data.EntityClient"
    xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>

A: <system.net>
  <mailSettings>
    <smtp>
      <network xdt:Transform="Replace" host="192.168.1.9" userName="" password="" />
    </smtp>
  </mailSettings>
</system.net>


text:
Q: XML field within the XML Dataset DBUnit I'm fairly new at the dbUnit and I'm facing a bit of a problem. In my source table I have a column which is "XML_HEADER", the contents of this will always be in the XML format. Now, I am creating a sample dataset for my testing and I have put the XML for the field in the dataset.xml like:
    XML_HEADER="<?xml version='1.0' encoding='IBM-1140'?><Data><...></Data>"

But I'm getting the error:
    Caused by: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 239;
    The value of attribute "XML_HEADER" associated with an element type "Table" must not contain the '<' character.

How do I format the sample data? Do I need to make changes in order to handle the incoming field?

A: Wrap the XML value string in CDATA, e.g. "<![CDATA[<?xml version='1.0' encoding='IBM-1140'?><Data><...>]]>"


text:
Q: Postgres or MapReduce to Match Reciprocal Needle Pairs from a Stack of Needles? I have a Postgres (latest version) table with about a million lines (a_lat, a_lon, b_lat, b_lon) that each have about a dozen criteria.
These lines go together in reciprocal pairs (A - B, B - A), which I need to determine. There may be multiple lines with similar A and B lat/lon, with similar but different criteria.
The criteria matching isn't exact, so many passes are done with less and less strict criteria (exact match on early rounds, +/- 1 one on later rounds, then +/- 1.5, etc). Matches in each pass are removed from subsequent passes.
I'm currently doing the matching in Postgres by looping over each row in the table and doing a query to find matches:
SELECT
    id
FROM
    locations
WHERE
    a_lat BETWEEN SYMMETRIC (38.5565 - 0.00055533333334) AND (38.5565 + 0.00055533333334) AND
    a_lon BETWEEN SYMMETRIC (-77.2797222222222 - 0.00055533333334) AND (-77.2797222222222 + 0.00055533333334) AND
    criteria_1 BETWEEN SYMMETRIC (42.7 - 1.5) AND (42.7 + 1.5) AND
    criteria_2 = 23 AND
    criteria_3 = 'ABCD' AND
    (criteria_4 = '0014980726' OR criteria_4 IS NULL) AND
    criteria_5 = 'A' AND
    criteria_6 = 1

If there is exactly one match then it's recorded and that row removed from future passes.
If you do the math its a ridiculous amount of queries (billions) and takes days to run. All fields have been optimized (floats and integers where possible) and indexed.
Is this type of problem suitable for a MapReduce type solution?
Can MapReduce handle multiple criteria, and criteria ranges (+/- 1)?  Can a performance gain be expected on the same hardware (384 GB RAM, 64 core Xeon), or is the performance increase only due to the ability of MapReduce solutions to scale to multiple machines?
Thanks!

A: I think it could be helpful for you to think of MapReduce as (essentially) a distributed query engine.  I know it isn't one-to-one, but with SELECT and aggregate functions such as sum(), max(), etc being very much like a Map() operation, and GROUP BY being very much like a Reduce(), there is quite a bit of similarity.
In your case, on the same hardware, I think the only benefit you will be able gain from using MapReduce is the distribution to multiple cores.  Remember that query processes in PostgreSQL only use a single core per query, so there is a lot of waste of your 64 cores if you're running this one query at a time.
Parallelization
Perhaps you'd be able to break up the query and run it over only segments of your locations table, and then run these queries in parallel using a connection pooler like pgBouncer?
For some good info about access data in sequential chunks (pagination), check out this amazing blog post by Markus Winand.
An example of how you might break this into chunks might be (warning:untested SQL ahead)
SELECT
id
FROM
(SELECT * FROM locations LIMIT x OFFSET y) AS locs_fragment
WHERE
a_lat BETWEEN SYMMETRIC (38.5565 - 0.00055533333334) AND (38.5565 + 0.00055533333334) AND
a_lon BETWEEN SYMMETRIC (-77.2797222222222 - 0.00055533333334) AND (-77.2797222222222 + 0.00055533333334) AND
criteria_1 BETWEEN SYMMETRIC (42.7 - 1.5) AND (42.7 + 1.5) AND
criteria_2 = 23 AND
criteria_3 = 'ABCD' AND
(criteria_4 = '0014980726' OR criteria_4 IS NULL) AND
criteria_5 = 'A' AND
criteria_6 = 1;

Note that the sub-select SELECT * FROM locations LIMIT x OFFSET y, given no additional criteria, will extract rows in ctid order. By selecting appropriate LIMIT and OFFSET values for a rnage of queries, you can essentially run the query in parallel.
Denormalization
Don't rule out denormalization as an option as well. In this case, it can help you to much more quickly get you the results you want. Of course, denormalization will only really help if your query criteria will be fairly stable over time, so that you can effectively pre-calculate results sets.
I'd say there are two decent options:
(1)  Use partial indexing, where a given index is designed around some set of criteria, as
CREATE INDEX idx_locations_criteria_set_0
ON locations (id)
WHERE
a_lat BETWEEN SYMMETRIC (38.5565 - 0.00055533333334) AND (38.5565 + 0.00055533333334) AND
a_lon BETWEEN SYMMETRIC (-77.2797222222222 - 0.00055533333334) AND (-77.2797222222222 + 0.00055533333334) AND
criteria_1 BETWEEN SYMMETRIC (42.7 - 1.5) AND (42.7 + 1.5) AND
criteria_2 = 23 AND
criteria_3 = 'ABCD' AND
(criteria_4 = '0014980726' OR criteria_4 IS NULL) AND
criteria_5 = 'A' AND
criteria_6 = 1;

With such an index defined, if you make a query with a matching predicate, an index scan is performed rather than having to perform all the calculations for the SELECT statement.
(2)  Another denormalization option is to use triggers during INSERT on your locations table to verify if certain conditions are met, and when they are met, store the id of that locations entry in another table, thus making a simple table scan all you need to do at a later time to find matching entries.
Both of these cases will require additional storage space, as well as some minor INSERT overhead for predicate checking, but it allows you to distribute your predicate checking over time, rather than being forced to do it all at once when a query is issued.
Conclusions
As with any advice on the internet, take mine with a grain of salt! :P  I've done some work in both of these areas, but that doesn't make me an expert in your application area. Run some small scale tests on either approach to see what works best for your application.


text:
Q: How to fetch urls in array from paragraphs in javascript I want to fetch all urls available in paragraph or sentence in javascript in array. For example check paragraph below:

Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.

From above string, We have to get array of these two url.Solution 1: Solution 1, I know is to split paragraph with space, iterate over array and check for url one by one and push into url's array. But, It's a time taking solution.Are there better solution for finding it or above solution is fastest and good to go?Thank you.

A: Is this what you are looking for?
var list = [];
var sentence = "Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.";

var result = checkForURL(sentence);

function checkForURL(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function (url) {
        return '' + url + '';
    })
}
var number = result.split('');

for (var i = 1; i < number.length; i++) {
        list.push(number[i].split(".")[0]);
}
alert(list);

A: You might want to split on :// to get a smaller array to iterate over.
Example:
Demo
JSFiddle
HTML

Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.

URLs

Javascript
findUrls();

function findUrls(){
  var p = document.getElementById('p');
  var res = document.getElementById('results');
  var pStr = p.innerText;
  var parts = pStr.split(/:\/\//);
  if (parts.length < 2)
    return;
  for (var i = 1 ; i < parts.length ; i++){
    var part = parts[i];
    var lastPart = parts[i-1];
    if (lastPart.length < 4 )
      continue;
    if (lastPart.length >= 4 && lastPart.substr(-4) == 'http')
      part = 'http://' + part;
    else if (lastPart.length >= 5 && lastPart.substr(-5) == 'https')
      part = 'https://' + part;
    var firstSpace = part.indexOf(' ');
    if (firstSpace > -1)
      part = part.substring(0, firstSpace);
    var lastChar = part.charAt(part.length - 1);
    if (lastChar == ',' || lastChar == '.' /* || ... */)
      part = part.substring(0,part.length - 1);
    res.innerHTML += '
' + part + '
'; // or push part to some result array
  }
}

A: Try this approach. It might need some fine tuning..

var paragraphs = document.getElementsByTagName('p')
var regex = /(https?:\/\/.*?)(\s|$)/g;
var urls = [];
var badLastChars = [".", ","];

for (var i = 0; i < paragraphs.length; i++) {
  var p = paragraphs[i].innerText;
  var match;
  while (match = regex.exec(p)) {
    var url = match[1];
    var lastChar = url[url.length-1];
    if (badLastChars.indexOf(lastChar) > -1 ) {
      url = url.slice(0,url.length-1);
    }
    console.log(url);
    urls.push(url);
  }
}

 Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.

 Another  paragraph https://stackexchange.com. and here is another url I am making up: https://mycoolurlexample.com/this/is/an/example


text:
Q: How to get the height and width of ImageView? I am trying to get the height & width of ImageView bot it's returning 0
public class FullScreenImage extends FragmentActivity {
    ImageView full_view;
    int width;
    int height;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);

        setContentView(R.layout.full_screen);

        full_view   = (ImageView)findViewById(R.id.full_view);

        Bundle bundle=getIntent().getExtras();
        byte[] image=   bundle.getByteArray("image");

        width       =     full_view.getWidth();
        height      =     full_view.getHeight();

        Bitmap theImage = BitmapFactory.decodeByteArray(image, 0, image.length);
        Bitmap resized = Bitmap.createScaledBitmap(theImage,width , height, true);

        full_view.setImageBitmap(resized);
    }

}

Please help me, how to find it from ImageView?

A: A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view's constructor is called, Android doesn't know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but before anything is drawn. You can use the onSizeChanged() method to be notified of the values when they are known, or you can use the getWidth() and getHeight() methods later, such as in the onDraw() method.

A: see this
int finalHeight, finalWidth;
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
final TextView tv = (TextView)findViewById(R.id.size_label);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
    finalHeight = iv.getMeasuredHeight();
    finalWidth = iv.getMeasuredWidth();
    tv.setText("Height: " + finalHeight + " Width: " + finalWidth);
    return true;
  }
});

A: IF you  first time get height and width that time there are no image available so result is 0.
Please use this code:
 setContentView(R.layout.full_screen);

    full_view   = (ImageView)findViewById(R.id.full_view);

    Bundle bundle=getIntent().getExtras();
    byte[] image=   bundle.getByteArray("image");

    Bitmap theImage = BitmapFactory.decodeByteArray(image, 0, image.length);
    Bitmap resized = Bitmap.createScaledBitmap(theImage,width , height, true);

    full_view.setImageBitmap(resized);

    width       =     full_view.getWidth();
    height      =     full_view.getHeight();


text:
Q: Rails: two attributes diffrent tables in view I have been trying trying to use two attributes from two different models so they can be used with the calendar_for method provided by the table_builder plugin in the index view. I have been through the Rails guides for http://guides.rubyonrails.org/active_record_querying.html#retrieving-multiple-objects and posts such as Ruby on Rails: How to join two tables however i must be doing something wrong.
My models are as follows:
Class Event < ActiveRecord::Base
belongs_to :user

and
class User < ActiveRecord::Base
User has_many :events

The different ways I have tried in the controller (not all at once) are:
@event.user.name
@users = User.joins(:event).where(:event => {:event_date => true})
@users = User.where(:event => :event_date)

Amoung others, my view looks like:
my view code:
<% calendar_for @users, :year => @date.year, :month => @date.month do |calendar| %>
<%= calendar.head('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',   'Saturday') %>
<% calendar.day(:day_method => :created_at) do |date, users| %>
<%= date.day %>

    <% for user in users %>

<%= link_to h(user.name), user %>

    <% end %>

<% end %>
<% end %>

I have tried changing the variables in the view accordingly however to no avail. I would like to show the users name and a link to the user on the specific day that their event is booked.

A: Two issues I see, though I'm not familiar with the calendar library.
First, make sure your query in the controller returns something useful.  Of the three lines you gave us, the first doesn't even search, it calls methods on an undefined variable.  The second is close to working, but you are searching for a date and matching it to true... How about:
@users = User.joins(:event).where('events.event_date is not null')

Furthermore, if you have a date range, you might include that in the search:
@users = User.joins(:event).where('events.event_date > ? and events.event_date < ?', start_date, end_date)

Next in the view, you aren't consistent with your variable naming.  The controller sets up the @users variable, which you access once, but then later you are missing the @ in front of it, which is not the same thing.  I don't know what the calendar part wants as input, but at least the for loop should be:
for user in @users

That said, for loops are not very rubyish. The ruby way is to use each:
@users.each do |user|
  ...
end

or even better, to make all of your links:

<%= @users.collect {|user| content_tag(:li, link_to h(user.name), user).join } %>

edit
Based on more information, I think you are starting at the wrong place. Let's start with events.
Event.joins(:users).where('events.event_date is not null')

<% calendar_for @events, :year => @date.year, :month => @date.month do |calendar| %>
  <%= calendar.head('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',   'Saturday') %>
  <% calendar.day(:day_method => :event_date) do |date, events| %>
    <%= date.day %>

      <% for event in events %>

<%= link_to h(event.user.name), event.user %>

      <% end %>

  <% end %>
<% end %>


text:
Q: Collapsingtoolbarbar issue with no scrolling content inside fragment I have,in my code, only one activity and many fragments.
The structure is this one :
<android.support.v4.widget.DrawerLayout>

    <android.support.design.widget.CoordinatorLayout>

        <android.support.design.widget.AppBarLayout>

            <android.support.design.widget.CollapsingToolbarLayout>
                <ImageView/>
                <android.support.v7.widget.Toolbar/>
            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>

        <FrameLayout/>

    <android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView/>

</android.support.v4.widget.DrawerLayout>

and
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.0'

I don't need the collapsing toolbar in all fragments but I prefered to do that instead of putting a appbarlayout in each fragment.
The problem is when I launch my app :
1) I am on a fragment where the collapsing toolbar is not usefull( I don't have scrolling content) BUT I can still expand the collapsing toolbar if I scroll on the toolbar (This is the issue...).
2) Now,I go in a fragment with scrolling content and I expand the collapsing toolbar with a recyclerview , the collapsing toolbar works normally.
3) I want to repeat the bug of 1), the bug is not present anymore.
Like scrolling with a recyclerview has solved the bug?
The collapsing toolbar does not expand if I scroll on the toolbar. And I would like it to be like till the launch of the app.
I don't won't to go on a fragment scrolling content to disable this bug.
You can see this gif which represent what I'm talking about via GIPHY
Can you help me? :)

A: If you want to change the scroll behavior you can do that programmatically by changing the Scroll Flags on the AppBarLayout.LayoutParams of the CollapsingToolbarLayout.
CollapsingToolbarLayout ctl= (CollapsingToolbarLayout) findViewById(R.id.collapsing_appbar);
AppBarLayout.LayoutParams params = ctl.getLayoutParams();
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);//or a combination of flags
ctl.setLayoutParams(params);

Another trick to make the CollapsingToolbarLayout scroll 'with no scrolling content' is to put
  'your layout' in a NestedScrollView and set a *1000dp min height value
  to the child of the NestedScrollView ('your layout').
android:minHeight="1000dp"

Layout:
<android.support.v4.widget.NestedScrollView
app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <!--your layout-->
    <FrameLayout android:minHeight="1000dp"/>

</android.support.v4.widget.NestedScrollView>

*SupportDesignDemos example here: https://github.com/android/platform_development/blob/master/samples/SupportDesignDemos/res/layout/include_appbar_scrollview.xml


text:
Q: Obtener el nombre del equipo en el que esta logueado un usuario Tenemos un sistemita que busca y obtiene la información de todos los trabajadores de un active directory, queremos saber como podemos hacer para saber que EQUIPO dentro de la red de la empresa esta usando en ese momento ese trabajador cuando lo busquemos, por ejemplo:
busco al empleado 1111 y dentro la informacion que ya me muestra además me muestre el nombre del equipo en el que está logueado esto porque en active directory no vemos ningún field que lo diga como tal, como por ejemplo si lo hace el givenName, o el sn que nos devuelven nombre y apellido.
Agradecemos cualquier ayuda o sugerencia que se nos pueda brindar

A: Tendrias que tener conexion al active directory para hacerlo y obtener la información que tiene ahi te dejo un codigo generico solo tendrias que poner los datos de conexión que serian la url el usuario y password.
  //los using que use
  using System;
  using System.DirectoryServices;

   try {
        var ldap = new DirectoryEntry("LDAP://tu url AD", "usuario", "password");
        var searcher = new DirectorySearcher(ldap) { Filter = "(objectClass=user)" };

         foreach (SearchResult result in searcher.FindAll())
         {
           DirectoryEntry dirEntry = result.GetDirectoryEntry();
                // Puede encontrar la lista de atributos aquí http://msdn.microsoft.com/en-us/library/ms675090.aspx
                Console.WriteLine("Server name : " + dirEntry.Properties["ServerName"].Value);
                Console.WriteLine("IP : " + dirEntry.Properties["ipHostNumber"].Value);
                Console.WriteLine("User name : " + dirEntry.Properties["sn"].Value);
                Console.WriteLine("Email : " + dirEntry.Properties["mail"].Value);
                Console.WriteLine("Tel : " + dirEntry.Properties["TelephoneNumber"].Value);
                Console.WriteLine("Description : " + dirEntry.Properties["description"].Value);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }


text:
Q: Implement adding content only by some pople. Rails I am working on dictionary-like web page and I want to implement adding/changing phrases only by few people (my client - which is some small organisation wants to be able to do this by himself). The page does not have any login/registration mechanism etc. (for regular users at least) so I do not want It to have any login button. I wondered if making admin model ( few admins made in seeds for example) and adding login button that is invisible - I thought of using CSS opacity for this one. Is this a good solution ? Is there any other good practice in these sitations? Please dont be afraid to post suggestions. Additionally this is a serious page (my first job as freelancer), so I wonder if my solution is... acceptable? Thanks in advance for any answers!

A: Even though this is simple I would still suggest adding a role to a user model. After all he may want to have some user functionality later on. The simplest way to do this would be to use devise and add a role enum column.
Check out the article below and look under the "Enum" section.
http://railsapps.github.io/rails-authorization.html

A: This quite a standard thing in the web. Most of the websites consists of two parts, customer facing part (sometimes called frontend) and admin panel (called backend). In your case you don't need any login to access frontend part, but you need one for backend part.
Creating hidden button is not needed at all. There simply should be no button at all. If you want to log in as an admin, you simply navigate to http://my-website-url.com/admin.
I wouldn't bother with roles et unless your client specified clearly that he needs them.


text:
Q: Using Username and email as login in wso2 I followed the document
http://xacmlinfo.org/2014/10/07/email-username-with-identity-server/ to allow users login with their Email ID.But it is is mentioned if we enable
<EnableEmailUserName>true</EnableEmailUserName>

then users cannot login with their username or any attribute other than email.
Our use case as LDAP as a secondary user store and we also do in time provisioning.So we will need to allow users to login with either email or username. Is there any way to achieve this.

A: You have to follow this guide to achieve this. Following are the steps you need follow.
Step 1
Configure the LDAP user store related configurations using the
    user-mgt.xml file found in the /repository/conf directory.
Configure UserNameSearchFilter that helps to search for the user object in the LDAP using both mail and uid attributes.
<Property
name="UserNameSearchFilter">(&(objectClass=person)(|(mail=?)(uid=?)))</Property>

Disable UserDNPattern property, if it is currently enabled.
<!--Property
name="UserDNPattern">uid={0},ou=Users,dc=wso2,dc=org</Property-->

The mail attribute has requirements that are unique. If you are
    using the mail attribute, you need to open the carbon.xml file found
    in the /repository/conf directory and uncomment the
    following. See here for more information on email authentication.
<EnableEmailUserName>true</EnableEmailUserName>

Step 2
If you want to work with multiple attributes (basically to retrieve internal roles with multiple attributes), you must add following property in the /repository/conf/user-mgt.xml file. This can be done only once you have installed the WSO2 Identity Server 5.0.0 along with the Service Pack.
 <Property name="MultipleAttributeEnable">true</Property>

Step 3
To test this, restart
    the Identity Server and try to log in to the management console by
    providing both the mail and uid with the same password.

A: Multi-attribute login is not supported for the versions before 5.10.0. The above suggested approach too could cause some inconsistencies during some flows.(Refer here for the reason).
Solution to adopt multi-attribute login for earlier Identity Server versions is described in this blog post
But from 5.10.0, WSO2 supports this by introducing new set of user store managers as explained here.


text:
Q: Laravel Socialite facebook exception a have some strange issue.
I use laravel 5.4 and Socialite.
The issue is:
When i move to /auth/social/facebook it redirects me to facebook, and all fine, but, when it redirect me to my web site, it can't get access_token.
That's my social Controller (it works fine with other social providers)
public function handle($provider, SocialAccountService $service)
{
    try {
        $userData = Socialite::driver($provider)->user();
    } catch (Exception $e) {
        return redirect(route('auth.social', ['provider' => $provider]));
    }
    $user = $service->findOrCreateUser($userData, $provider);
    auth()->login($user);

    return redirect()->to('/');
}

public function redirect($provider)
{
    return Socialite::driver($provider)->redirect();
}

The exception i get from facebook

GET https://graph.facebook.com/v2.8/me?access_token=&fields=name,email,gender,verified,link&appsecret_proof={sometoken} resulted in a 400 Bad Request response:
  {"error":{"message":"An active access token must be used to query information about the current user."

A: Solution is, require package again
composer require laravel/socialite
composer update

it will update packages, and all works fine


text:
Q: VHDL: (Data Flow and Control Unit) calculate log2, represented as an unsigned 8-bit integer I need to design a digital circuit, in the form of Data Flow and Control, to calculate the entire portion of the logarithm at base 2 of a positive number N, represented as an unsigned 8-bit integer in VHDL.
Basically I'll do this:
int log2 (int N) {

    int count = -1;
    while (N>0){
        N = N >> 1;
        count++
    }
    return count;
}

I'll use 8-bit integer to represent the number N and dislocate with 0's to the right. Then, the number of dislocation minus 1, is equal to the log2.
I have already made the entity:
entity log2 is

    port (
        clock, reset: in bit; -- global control: clock and reset
        start: in bit;
        ready: out bit; -- finished execution (equal to 1 when the calculation is finished)
        N: in bit_vector(7 downto 0);
        logval: out bit_vetor(3 downto 0) -- log2(N)
        );
end entity log2;

But I'm struggling with the following process.
I've made a ASM diagram to help, and there it is:

And I also know that I need some data flow elements like:

*

*for the "reg" i'll need a shift register,

*for the log i'll need a counter register

I've only been able to see this at theory, i'm struggling to put all of this into code.
Does anybody know how can I start the architecture?


text:
Q: Optimal lookup table query for multiple products? If I have a lookup table with fields like so:
id, color_id, size_id, price
I can easily get all the sizes/prices available for a specific color using:
SELECT size_id, price from TABLE where color_id = 2

But, if I want to show a price table like so:
    red     blue    green   yellow

xs  1.20    1.20    1.29    1.39
sm  1.40    1.40    1.49    1.59
md  1.40    1.40    1.19    1.59
lg  1.55    1.55    1.80    1.94
xl  1.55    1.55    1.80    1.99
xx  2.01    2.05    2.40    2.68

Is there a way to do so w/o doing a query for each color? Or is there a better way to structure the data?
Thanks for any help!

A: select size_id, sum(if(color_id=1,price,0)) c1, sum(if(color_id=2,price,0)) c2, sum(if(color_id=3,price,0)) c3, sum(if(color_id=4,price,0)) c4 from TABLE group by size_id

At least this works nicely if you do not have a variable number of colors.


text:
Q: How to pass two LINQ joined tables from Controller to View I have three objects:
public class Part
{
    [Key]
    public int ID { get; set; }
    public string Number { get; set; }
    public string Name { get; set; }
    public int descID { get; set; }
}

public class Description
{
    [Key]
    public int descID { get; set; }
    public string descName { get; set; }
    public string description { get; set; }
}

public class GridPart
{
    public string name{ get; set; }
    public string number { get; set; }
    public string description { get; set; }
}

I'm using LINQ to join Part and Description on the descID column:
public ActionResult Index()
{
    var myParts = from p in db.Parts
                  join d in db.Description on p.descID equals d.DescriptorID
                  select new { Description = d.description, Name = p.name};
    List<GridPart> partsList = new List<GridPart>();

    foreach (var m in myParts)
    {
        GridPart gp = new GridPart();
        gp.Name = m.name;
        gp.description = m.description;
        partsList.Add(gp);
    }
    return View(partsList);
}

If I was just using the Parts table, in the view I would do:
@model IEnumerable<MyApp.Models.Part>

What do I do if I'm using the joined table?  This uses both Parts and Description, not to mention my List of GridParts, how do I pass this through to display all of the data I need?
Any advice is greatly appreciated.

A: If you pass an anonymous type to your view it won't be strongly typed. You can refer to your model like this instead
@Html.TextBox("Name")

or
@Html.Display("Name")

Although this will work I would advice against it - The better solution would be to go with a Viewmodel instead. This will make your view strongly typed.
Edit: Looking on this again I see that your actually not parsing the anonymous type to your view. Your parsing a list of GridParts.
You should be able to strongly type your view like your tried - just refer to GridParts instead of parts.
@model IEnumerable<MyApp.Models.GridPart>


text:
Q: Query is updating the RequestOBject to DB in spring Microservices based application Need some clarifications on the best practises that needs to be followed while updating data into the DB in a spring microservices  based webapplication
Scenario
We have a webapplication, in which when the user sends request from the UI, for processing the request, at the backend the request goes to a microservice and we have to update the request and response objects in a particular table in the database. I wanted to know the right approach for updating the data in the databse. Below are my queries.

*

*Should we insert the request Object as soon as we receive it in the microservices or

*Should we process the request and after the processing, once we receive the response, should we do a single insert to the database with both request and response Object to avoid multiple DB calls.

Please Advise. Any help on this is much appreciated.


text:
Q: IBM Sales Center Client I want to run IBM Sales Center Client on eclipse. I read the IBM Infocenter document. But I can not configure it. I searched for plugins, but dint find any. Please guide me, How to run Sales Center Client on eclipse. Sales Center Developer App is already installed on my machine.
Thanks

A: You will need to find the update site jar files within the installation directory/CD and add them into your version of eclipse. The jar/zip files are usually in a folder marked updates or update_sites.
Once found, follow these instructions to import and add them into your eclipse.

Select File > Application > Install
  Select Search for new features to install and click Next.
Click on Add Folder Location and browse to the folder
  drive:\DRE\updates\client and click OK.
  Note: By default, drive is your DVD drive containing the IBM Sales
  Center DVD.
In the Name field, provide a value (for example, DRE) and click OK.
Click on Add Folder Location and browse to the folder drive:\SPRFix
  and click OK.
  Note: By default, drive is your DVD drive containing the IBM Sales
  Center DVD.
In the Name field, provide a value (for example, SPRFix) and click OK.
Click on Add Folder Location and browse to the folder drive:\ISCWC and
  click OK. Notes:
By default, drive is your DVD drive containing the IBM Sales Center
  DVD.
If you have moved the installation packages into a ZIP/JAR file, or on
  to a remote Web server, you can select the Add Zip/Jar Location or Add
  Remote Location options.
In the Name field, provide a value (for example, ISCWC) and click OK.
Make sure all of the update sites you added are selected and click
  Finish.
On the Search Results panel, select Core JVM Feature –J2SE and UI
  Widgets under the Runtime Components and select everything under the
  IBM Sales Center for WebSphere Commerce. Click Next.
Read and accept the license agreement and click Next.
Review the summary and click Finish to start installing. Wait for the
Provisioning Operation to finish.
Once the provisioning is finished, click Restart Now to restart Lotus
  Expeditor.
To verify that Sales Center is installed, click the Open button and
  you should see any WebSphere Commerce stores you have created in the
  list.


text:
Q: A functional equation problem over integers: $f(m+n)=g(m,n)+h(m,n)$ and $f(m-n)=g(m,n)-h(m,n)$ I was working in a problem in number theory and I blocked over the problem:

Given functions $f:\mathbb{Z}\to \mathbb{Z}$, $g:\mathbb{Z^2}\to \mathbb{Z}$ and $h:\mathbb{Z^2}\to \mathbb{Z}$ such that $ \forall m,n \in \mathbb{Z}$:
$$ f(m+n)=g(m,n)+h(m,n) $$
$$ f(m-n)=g(m,n)-h(m,n) $$
can we prove that $g$ depends only on $m$ and $h$ depends only on $n$.

I'm working in a problem similar but more complicated, for which are interested, given a quadratic form with two variables $Q(m,n)$, I'm looking for a characterization of functions $f$ such that $f\big(Q(m,n)\big)$ can be written as $Q(m',n')$ for all integers $m,n$.

A: No, for example $f(n)=n^2$ gives $g(m,n)=m^2+n^2$. There are many more examples, since what you're asking is essentially that $f(m+n)+f(m-n)$ is a function of $m$ (taking even values only) and that $f(m+n)-f(m-n)$ is a function of $n$ (taking even values). These requirements are clearly not satisfied in general.


text:
Q: HTTP Error 502.5 - Process Failure when trying to run my project I am trying to follow this tutorial, my program has the API template
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio
but when I run the program it gives me this error HTTP Error 502.5 - Process Failure
it also says
The application to execute does not exist: 'C:\Users\Cristina\Desktop\roweb proj\TodoApi\TodoApi\bin\Debug\netcoreapp2.2\TodoApi.dll'
even though it did not create those files when I created the folder.

A: There are multiple reasons as to why this error may arise.
Call your .dll file of your project in the cmd using the dotnet command will help you understand exactly what the issue is. In my case there was a version error for ASP.NET core. Make sure all your project dependencies in the .csproj file of your project use the same version of ASP.NET core SDK and runtime bundle. You can check the versions present on your system through the dotnet command on cmd:
dotnet --info

Take a moment to read this link, there may be a solution for your problem .


text:
Q: How to write a LINQ join for two classes in ASP.NET MVC4 I am having trouble accessing a property from a joined table, using EF Code First.  Here is my query in my home controller:
var pcs = from h in db.Hardwares
    join hwt in db.HardwareTypes
    on h.HardwareTypeId equals hwt.Id
    where h.HardwareType.HType == "PC"
    select new { Hardware = h, HardwareType = hwt };

ViewBag.Pcs = pcs.ToList();

Here is my HardwareTypes class:
public class HardwareType
    {
        public int Id { get; set; }
        //[Required]
        //[StringLength(128)]
        public string HType { get; set; }

    }

Here is my Hardware class:
public class Hardware
    {
        public int Id { get; set; }
        public int HardwareTypeId { get; set;}
        public virtual HardwareType HardwareType { get; set; }

    }

How do I change my LINQ query so HType is in my ViewBag?  The database seems to be generating correctly, it's just I can't seem to access HType.  I get an error 'object' does not contain a definition for 'HType'

A: Ok, time for a full reset. Based on the chat, I want you to try the following:
1) Keep your original LINQ query, but don't make it an anonymous type. Create another object type that will have a Hardware and a HardwareType property in it. This will make Pcs (as well as ViewBag.Pcs) a List of that particular type.
2) Put the following foreach loop in your View code:
foreach (var item in ViewBag.Pcs as List<YourTypeName>)
{
   var htype = item.HardwareType.HType;
}

And if you don't want to do some lazy loading each time through the loop, you can do the following in the controller to just load up the entities right away:
var hardwareTypes = pcs.Select(p => p.HardwareType).ToList();

Let me know if that works.


text:
Q: VBScript : How to identify the hidden excel tabs in excel using vbscript How to identify the hidden excel tabs in excel Workbook using vbscript, but not VBA. How to get the properties of  each tab like name, color, visibility using VBScript

A: Assuming objExcel is your Excel application object:
For i = 1 To objExcel.Sheets.Count

    ' Display the name of hidden worksheets...
    If Not objExcel.Sheets(i).Visible Then
        WScript.Echo objExcel.Sheets(i).Name & " is not visible."
    End If

    ' Get the tab color value of each worksheet...
    WScript.Echo "Tab color value = " & objExcel.Sheets(i).Tab.Color

Next


text:
Q: Migrating MySQL from Windows to Linux I'm new to MySQL.  However I am very familiar with Oracle and MSSQL.  This is what I have done so far:

*

*Installed MySQL 5.7 on RHEL 7.2

*Created a test db called "mydb" and test table called "employee".

*Location of these files are
/usr/var/lib/mydb
/usr/var/lib/mydb/employee.frm
/usr/var/lib/mydb/employee.idb

*Able to connect to MySQL from a client machine and can see the "mydb".

So my server and connectivity are fine.  Now I want to move some of the MySQL 5.0 databases from an old Windows box to this new RHEL Linux box.
Sample of old MySQL 5.0 database files:

*region.myd
region.myi
region.frm

I don't have much knowledge of the MySQL database architecture.  I just noticed the MySQL 5.0 has extensions of .frm, .myd and myi while the MySQL 5.7 has .frm and the .ibd
My question is: How can I quickly migrate those two "region" files to my new RHEL box so they conform to the .frm and .ibd file format?
Thank you

A: OK Brace yourself. You can migrate the table from Windows by copying it and converting it.
STEP 01
Copy those three(3) files into the data folder /usr/var/lib/mydb in Linux
You should have

*

*/usr/var/lib/mydb/region.frm

*/usr/var/lib/mydb/region.myd

*/usr/var/lib/mydb/region.myi
STEP 02
Change the filename name extensions of two of the files
cd /usr/var/lib/mydb
mv region.myd region.MYD
mv region.myi region.MYI

Required for MyISAM tables in Linux

*

*See my old post Error When Restoring Backed Up Tables

*See the chat session that I used to troubleshoot this question
STEP 03
Change the owner of the three files
cd /usr/var/lib/mydb
chown mysql:mysql region.frm
chown mysql:mysql region.MYD
chown mysql:mysql region.MYI

STEP 04
Convert the Table to InnoDB
mysql> use mydb
mysql> ALTER TABLE region ENGINE=InnoDB;

That's it.
GIVE IT A TRY !!!

A: You are migrating from 5.0 to 5.7, so the safest way is to dump and restore using mysqldump, you can find this link useful http://mysqlserverteam.com/upgrading-directly-from-mysql-5-0-to-5-7-with-mysqldump/


text:
Q: DBA - Checklist Question- TempDB Is Full I'm trying to create some checklists for troubleshooting various issues, in this case, when TempDb is full.   I'd like a prioritized repeatable process where possible to help me out in a hurry.
When TempDB is full, what are the steps you take to troubleshoot that and fix it?  Here is what I have so far, but I know it's far from being adequate as I don't yet know the best steps to take to troubleshoot it.
To me, there are a couple of checklists needed for this.  When the server will let you connect, and when it won't.
When the server will let you connect:

*

*Run Sp_Who2 - check for any blocks

*Run Sp_WhoIsActive to try to see what is filling up TempDB

*Kill any SPID's that could be filling up TempDb

*Restart the SQL Server service.

When the server won't let you connect:

*

*Restart the SQL Server service.

What other steps do you take, in order, to help you troubleshoot and fix full TempDB?
Thanks for the help!

A: There is so many use cases..
Here's what I would check first:
1- If you connect and tempdb is no longer full:

*

*Usually, this happen because some process ran out of space and SQL rolled back that transaction (releasing space in tempdb). If your Tempdb is small and you can have extra space added to the disk where your tempdb live, this is the easiest approch. Just add space and make sure auto-growth is enable (check for the required trace flag if you have many data file on version older then 2016).

*If you cannot add space, then you get into the harder step to identify which process is using that much space in tempdb. You can work with the application team (usually, they should get an error in there log when SQL rollback the transaction). You can also try to build some kind of alert when tempdb reach a certain threshold and then run and collect info from sp_whoisactive to identify which query is causing it. Once you know what it is, you can try to tune it so that it uses less space.
2- If tempdb is still full:

*

*I then check what is filling up tempdb (temp table, row versionning, etc). I'll also check who is filling it up.

*Then, if it's row versionning, I'll check for a long running transaction or for a transaction that has an open transaction but doesn't seem to be active. Once I found it, I'll kill that session (If I can reach the dev team first, I usually do it so that I can show them exactly what's going on (there is good chance that if that happen once, it will happen again and most of the time, it needs to be fix in the code)

*If it's user object (temp table), I'll try to contact the user running the query. If the query can be written in a better way, I'll let him know and help him improve the query. If he simply ran it with a begin tran and forgot to commit/rollback, then I'll ask him to do it. I'm always carefull with killing sessions (specially if they have been running for a while as the rollback could take even longer).
I will not reboot the instance for a full tempdb... this is a very last resort option.

A: Get the TempDBInfo stored procedure from link below, deploy (create) it to any user database
https://github.com/aleksey-vitsko/Database-Administrator-Tools

*

*Run exec TempDBInfo and it will show you TempDB information such number of data files, their fullness, log file, sessions that consume most of TempDB, etc.

*Kill the sessions that consume most (if these are really a problem)

No need to restart the SQL Server service after killing the sessions


text:
Q: d3 dragging event does not terminate in Firefox I am using the d3 force directed graph animation.
Steps to reproduce problem:

*

*Fire up Firefox browser

*visit provemath.org

*click the x in the top right or log in (nodes should appear at this point)

*click on any node

*click on the back arrow on the top left

The result is that the node you clicked is still attached to your mouse as if you are dragging it around.  The desired result is that this doesn't happen :)
Insights:
This only occurs in Firefox.
d3 relevant code:
When data is bound to nodes, we use .call(gA.drag) where gA.drag = gA.force.drag(), and in the d3 library itself, we have:
    force.drag = function() {
      if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend);
      if (!arguments.length) return drag;
      this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag);
    };
    function dragmove(d) {
      d.px = d3.event.x, d.py = d3.event.y;
      force.resume();
    }
    return d3.rebind(force, event, "on");
  };
  function d3_layout_forceDragstart(d) {
    d.fixed |= 2;
  }
  function d3_layout_forceDragend(d) {
    d.fixed &= ~6;
  }
  function d3_layout_forceMouseover(d) {
    d.fixed |= 4;
    d.px = d.x, d.py = d.y;
  }
  function d3_layout_forceMouseout(d) {
    d.fixed &= ~4;
  }

Also when data is bound to nodes, I use .on('mousedown', mousedown) and .on('mouseup', mouseup).  I wrote those functions and they are:
function mousedown(node) {
    node.time_before = getShortTime(new Date())
    node.client_x_before = d3.event.clientX
    node.client_y_before = d3.event.clientY
    // d3.event.stopPropagation() // need cancelBubble for MS
}
function mouseup(node) {
    if( mod(getShortTime(new Date()) - node.time_before, 60) < 0.85
            && cartesianDistance([node.client_x_before, node.client_y_before], [d3.event.clientX, d3.event.clientY]) < 55
        ) {
        $.event.trigger({ type: 'node-click', message: node.id })
    }
    delete node.time_before
    delete node.client_x_before
    delete node.client_y_before
}
function getShortTime(date) {
  return date.getSeconds() + date.getMilliseconds()/1000
}
function mod(m, n) {
    return (m % n + n) % n;
}

I have tried using both d3.event.stopPropagation() and       d3.event.dataTransfer.setData('text', 'anything') as suggested in this question at various points in my code, to no avail.  The setData code seems to have the effect of halting events dead in their tracks as soon as the line is run, which doesn't make sense to me.
One possible, but not entirely satisfactory solution might be to manually find and destroy the drag event when a user clicks the back arrow.
UPDATE: I AM INCLUDING SOME MORE CODE EXCERPTS:
main.py
$(document).on('node-click', function(Event){
    current_node = graph.nodes[Event.message] // graph.nodes is a DICTIONARY of nodes
    updateNodeTemplateLearnedState()
    blinds.open({ // in this module, new DOM elements are added with jQuery's .append() method
        object: current_node,
    })
    hide('svg')
    hide('#overlay')
    show('#node-template') // This DOM element is the container that blinds.open() populated.  Event WITHOUT adding new DOM elements, it is possible that the mere putting of this guy in front of the vertices is causing the issue
    if( false /*mode !== 'learn'*/){
        ws.jsend({ command: "re-center-graph", central_node_id: current_node.id })
    }
})

function show(css_selector) { // this stuff fails for svg when using .addClass, so we can just leave show and hide stuff in the JS.
    let $selected = $(css_selector)
    if( !_.contains(css_show_hide_array, css_selector) ){
        $selected.css('height', '100%')
        $selected.css('width', '100%')
        $selected.css('overflow', 'scroll')
    }else{
        // $selected.removeClass('hidden')
        $selected.css('visibility', 'visible')
    }
}

meetamit's suggestion of using a timeout, even with a time of "0":
setTimeout(function() {
            $.event.trigger({ type: 'node-click', message: node.id })
        }, 0);

is in fact working, so I think his theory is correct.

A: Did you use d3.event.dataTransfer.setData('text', 'anything') as is? Firefox breaks when you set text as the mime-type, you need to use text/plain.
PSA: In IE11, it's the other way around. In fact, IE11 breaks when you set anything but 'Text' as the mime-type!

A: It's hard to diagnose this issue without access to the full code and the ability to insert debugging calls and testing potential fixes. Ideally you'd have a jsFiddle that reproduces this problem while isolating things just the relevant code (with fake hardcoded data if needed). If you can create that jsFiddle, I'll happily try to fix it there and revise my answer here. Otherwise, here goes:
I suspect that the problem is that in Firefox d3 completely misses the dragend event , because mouseup is triggered prior to it and from mouseup you're triggering node-click. I can't see further, but I'm guessing that triggering node-click immediately (meaning synchronously) results in changes to the DOM, making another element appear in front of the dragged node, and hence causing the missed dragend. It's just a theory, and it could be that it's only partially accurate and that the details of why dragend is missed are somewhat more nuanced.
There's probably a proper fix, but as mentioned, that requires a jsFiddle isolating the problem. However, I'm guessing that there's also the following hack that would workaround this problem: Wrapping the call to $.event.trigger in a setTimeout, something like
function mouseup(node) {
  if( mod(getShortTime(new Date()) - node.time_before, 60) < 0.85
        && cartesianDistance([node.client_x_before, node.client_y_before], [d3.event.clientX, d3.event.clientY]) < 55
    ) {
    setTimeout(function() {
      $.event.trigger({ type: 'node-click', message: node.id })
    }, 100);
  }
  delete node.time_before
  delete node.client_x_before
  delete node.client_y_before

}
Using setTimeout will delay the node-click event a bit, giving the browser and/or d3 a chance to finish up the drag business prior to modifying the DOM. It's not pretty, and there are usually better way to fix synchronization issues that don't involve setTimeout, which tends to pile on new problems rather than avoid it. But maybe you'll be lucky and this will fix it without causing new problems ¯\_(ツ)_/¯
The 2nd argument to setTimeout (shown as 100) is something you should experiment with. Could be that 0 would work or it might need to be even greater than 100.
Also, it could be that the delete statements need to be moved into the setTimeout function handler as well. Not sure, because it's unclear what they do.


text:
Q: PIC 32 TTL communication I've been given a PIC32mx795f512L in order to build a spy for I2C, I will connect 3 wires on SDA, SCL and GND and then I have to detect the sent data. This part is ok. Now, once I have the data, I have to send it via RX, TX to a computer (in fact, I send it to an adapter which convert it to RS232) and here is my problem.
I do not really know how to initialise this communication.
For now I put:
mPORTFClearBits(BIT_8);
TRISFbits.TRISF8=0;        // RF8 output==>TX1
TRISFbits.TRISF2=1;        // RF1 input==>RX1
U1STA = 0x1400; // Enable Tx(inv) and Rx
U1BRG = 8332; // value = (80000000 / BAUD) - 1 = 9600
U1MODE = 0x8008; // Enable UART with 1 stop bit, no parity and BRGH
OpenUART1(UART_EN | UART_BRGH_FOUR, UART_RX_ENABLE | UART_TX_ENABLE, UBRG(UART1_BAUD));

By checking the data sheet but I actually don't know if everything needed is set up.
And nonetheless, I don't get how to send data via TX.
I've found this topic
where it says:

To make some char output (a - into this example) on the UART simply write this code:
   if(!BusyUART1())
   putsUART1("-\r\n"); "

But I can't find where "a" is used.
So please, If someone feels able to help me, feel free to do it.

A: Basically following things are important while setting up UART communication

*

*UART Baud rate

*UART pin initialization (TRIS bits in PIC)

*How many Data bits (7 or 8)

*How many Stop bits (1 or 1.5 or 2)

*Parity (No or Odd or Even)

I can see all these things initialized in your code, which are all necessary. So this is answer to your first question.
For your second question, UART busy bit is checked and minus sign '-' followed by CRLF is sent over the UART Tx

A: Follow these steps to set up a UART transmission:

*

*Initialize the UxBRG register for the appropriate baud rate (refer to 21.3 "UART Baud Rate Generator").

*Set the number of data and Stop bits, and parity selection by writing to the PDSEL<1:0>
bits (UxMODE<2:1>) and STSEL bit (UxMODE<0>).

*If transmit interrupts are desired, set the UxTXIE control bit in the corresponding Interrupt
Enable Control register (IEC). Specify the interrupt priority and subpriority for the transmit
interrupt using the UxIP<2:0> and UxIS<1:0> control bits in the corresponding Interrupt
Priority Control register (IPC). Also, select the Transmit Interrupt mode by writing to the
UTXISEL bits (UxSTA<15:14>).

*Enable the transmission by setting the UTXEN bit (UxSTA<10>), which also sets the
UxTXIF bit. The UxTXIF bit should be cleared in the software routine that services the
UART transmit interrupt. The operation of the UxTXIF bit is controlled by the UTXISEL
control bits.

*Enable the UART module by setting the ON bit (UxMODE<15>).

*Load data to the UxTXREG register (starts transmission)

The following steps are performed to set up a UART reception:

*

*Initialize the UxBRG register for the appropriate baud rate (see 21.3 "UART Baud Rate Generator").

*Set the number of data and Stop bits, and parity selection by writing to the PDSEL<1:0>
(UxMODE<2:1>) and STSEL (UxMODE<0>) bits.

*If interrupts are desired, set the UxRXIE bit in the corresponding Interrupt Enable Control
register (IEC). Specify the priority and subpriority for the interrupt using the UxIP<2:0> and
UxIS<1:0> control bits in the corresponding Interrupt Priority Control register (IPC). Also,
select the Receive Interrupt mode by writing to the URXISEL<1:0> bits (UxSTA<7:6>).

*Enable the UART receiver by setting the URXEN bit (UxSTA<12>).

*Enable the UART module by setting the ON bit (UxMODE<15>).

*Receive interrupts are dependent on the URXISEL<1:0> bit settings. If receive interrupts
are not enabled, the user can poll the URXDA bit (UxSTA<0>). The UxRXIF bit should be
cleared in the software routine that services the UART receive interrupt.

*Read data from the receive buffer. If 9-bit transmission is selected, read a word; otherwise,
read a byte. The URXDA bit is set whenever data is available in the buffer.


text:
Q: What is the "shape" of the electric potential of a moving charge? Can the field be derived as its gradient? This is motivated by Electricity and Magnetism, 3rd Ed., by Purcell and Morin, Section 5.6.
Below is my derivation of the Lorentz transformation of the electric field due to a moving charge whose rest frame is represented by unbarred components.  The charge $Q$ moves at speed $\beta$ in the direction indicated by ${\parallel }$ subscripted coordinates.  It coincides with the 3-space origin of the barred system at $t=0.$
As pointed out in the book, the field is parallel to the radial direction from the origin where the moving source charge is instantaneously located, but changes strength with the angle of the radial position vector of the test particle.
In the case of a static potential the field is simply the 3-space gradient of the potential, and for a point charge the potential and electric field are both spherically symmetric.  The gradient points in a direction normal to equipotential surfaces.
On a plane lying parallel to the direction of motion at rest in the unbarred system (charge rest frame), we draw concentric circles around the charge, representing equipotential surfaces.  From the barred system, those circle will be foreshortened in the direction of travel.  Thus the field vectors will no longer be normal to the equipotential surfaces except at $\theta=0$ and $\theta=\frac{\pi}{2}.$
On one hand, the fact that the electric field is directed radial from the instantaneous location of the moving source charge seems intuitively obvious.  Lorentz contraction is an affine transformation of 3-space preserving lines and points of intersection.
On the other hand, the electric field no longer appears to be parallel to the gradient of the potential, except in the special cases already addressed.
Is there a way of explaining this apparent contradiction?  Can a useful visual representation of a moving source charge's potential be produced?
First do the transformation algebra.

Plug the results into the Coulomb's law expression.

A: Congratulations!  You have discovered an important fact about dynamic electromagnetic fields.  For dynamic fields, the electric field is no longer simply given by the gradient of the potential $V$, but is instead given by
$$
\vec{E} = - \vec{\nabla} V - \frac{\partial \vec{A}}{\partial t}
$$
where $\vec{A}$ is the vector potential (i.e., the field for which $\vec{\nabla} \times \vec{A} = \vec{B}$.)  In general, the equation $\vec{E} = - \vec{\nabla} V$ is only true for static (or approximately static) fields.
For further details on this, you'll need to look at higher-level texts than Purcell & Morin.  The standard undergraduate text for such material, at least here in the USA, is Introduction to Electrodynamics by Griffiths.  IIRC, this material is discussed in Chapter 10, though you'll need a full understanding of Maxwell's equations (Chapter 7) before you delve into that.


text:
Q: Expand polygon envelop to square using decimal degrees(wgs 84) I working in wgs64 gis.
I have the coordinates of polygon given by decimal degrees.
I trying to expand the polygon envelop from a rectangle to a square.
I understand that a rectangle of one degree of latitude and longitude on the sphere has not the same length in km unless it is situated on the equator.
But I don't understand the math behind how to fix my envelop.
I am doing this:
Envelope contextEnvelope = CurrElement.Envelope;
double Max = Math.Max(contextEnvelope.Width, contextEnvelope.Height);
contextEnvelope.Expand((Max * 15 - contextEnvelope.Width) / 2, (Max * 15 - contextEnvelope.Height) / 2);


text:
Q: Branch - Fetch / Pull from remote using TortoiseGit I am using TortoiseGit v 1.8.9.0 as my client.
I have a git repository with currently has 2 branches. The HEAD branch and also the 1.0.0-Enhancements branch.

The 1.0.0-Enhancements branch is not up to date in my local repository. So when I look at the commit history of this branch on my local using TortoiseGit it does not show the commits on this branch that I can see on the remote in GitWeb.
Here are two screenshots which illustrate that my local copy of the 1.0.0-Enhancements branch is missing commits.
-->History on my local using TortoiseGit

-->History of remote on GitWeb

My ultimate goal is to merge the 1.0.0-Enhancements branch into the HEAD branch however before I do this I believe that the 1.0.0-Enhancements branch should be up to date on my local.
I have been trying for a couple of hours now to try and find a way to fetch 1.0.0-Enhancements commit from the remote to my local but can't find a way. This is what I tried ...

*

*Make tortoise Git Switch to 1.0.0-Enhancements branch.

*Use tortoiseGit to fetch from the remote branch.

But after doing this when I look at the history of my 1.0.0-Enhancements branch the missing commits are still missing. Can someone help me with how I might fix this?
--Update for answer byt @CupCake--
TortoiseGit also comes with a bash prompt. I tried both your suggestions using the command line but they did not work. Here are the results.

But I did seem to make some progress with trying a git pull from the TortoiseGit UI.

Which seemed to work except it came back with an error:

git.exe pull -v --progress       "origin" 1.0.0-ENHANCEMENTS
From ssh://upredmine/cvs/repo/codeRepository/git/repo04/EPOS/EPOSWeb
  * branch            1.0.0-ENHANCEMENTS -> FETCH_HEAD Updating 67b6537..ee38b20
  error: The following untracked working tree files
  would be overwritten by merge:
  .metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.core.resources.prefs
  .metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.ui.prefs
  .metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.m2e.discovery.prefs
  .metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.mylyn.context.core.prefs
.metadata/version.ini Please move or remove them before you can merge.
  Aborting
git did not exit cleanly (exit code 1) (1094 ms @ 16/07/2014 3:32:47
  PM)

Can you give me some feedback on this. Do I need to force an update or synch?

A: It looks like the problem that you're having is that you're only fetching your enhancements branch into your local repo, but you're not actually merging the remote-tracking branch origin/1.0.0-Enhancements into your local 1.0.0-Enhancements branch.
Basically, you're branches are set up like this (let X represent your enhancements branch):

As you see in the diagram above, there are 3 branches involved:

*

*The local version of X.

*The remote version of X.

*A local remote-tracking branch origin/X, which keeps track of where the remote version of X is.

By using git fetch, you update the local remote-tracking branch origin/1.0.0-Enhancements in your local repo...but that's a separate branch from your local 1.0.0-Enhancements branch.
So, what you want to do is either:

*

*git pull, or

*git merge the remote-tracking branch.

Note that git pull is really just a combination of git fetch followed by git merge of the branch that you just fetched.
Option 1: Merge
Since you've already fetched, you just need to merge origin/1.0.0-Enhancements into your local 1.0.0-Enhancements branch. I don't know how you do this in TortoiseGit (I stopped using that years ago), but if you want to do it from the command line, you simply do
git checkout 1.0.0-Enhancements
git merge origin/1.0.0-Enhancements

Option 2: Pull
In the future, in cases where you didn't fetch first, you can execute a pull into your local branch from the remote branch instead. Again, I don't know how to do this in TortoiseGit anymore, but if you wanted to do it from the command line, you simply do
git checkout 1.0.0-Enhancements
git pull origin 1.0.0-Enhancements

Note on the HEAD symbolic reference
So the symbolic reference origin/HEAD is not a branch. It's simply a special reference that points to the default branch in the (bare) remote repo...the same branch that gets checked out by default by any clones of that repo.
In a non-bare repo, HEAD is still a symbolic reference, but instead of pointing to a default branch, it instead points to either the currently checked out branch, or the currently checked out commit, if you're not currently on the tip of a branch (e.g. "detached HEAD" state).
Documentation

*

*git-pull(1) Manual Page

*git-fetch(1) Manual Page

*git-merge(1) Manual Page


text:
Q: Perfect hashing function in a hash table implementation of a sparse matrix class I'm currently implementing a sparse matrix for my matrix library - it will be a hash table. I already implemented a dense matrix as a nested vector, and since I'm doing it just to learn new stuff, I decided that my matrices will be multi-dimensional (not just a 2D table of numbers, but also cubes, tesseracts, etc).
I use an index type which holds n numbers of type size_t, n being a number of dimensions for this particular index. Index of dimension n may be used only as an address of an element in a matrix of appropriate dimension. It is simply a tuple with implicit constructor for easy indexing, like Matrix[{1,2,3}].
My question is centered around the hashing function I plan on using for my sparse matrix implementation. I think that the function is always minimal, but is perfect only up to a certain point - to the point of size_t overflow, or an overflow of intermediate operation of the hashing function (they are actually unsigned long long). Sparse matrices have huge boundaries, so it's practically guaranteed to overflow at some point (see below).
What the hashing function does is assign consecutive numbers to matrix elements as follows:
[1 2 3 4 5 6 7 8 ...]^T //transposed 1-dimensional matrix

1 4 7
2 5 8
3 6 9 //2-dimensional matrix

and so on. Unfortunately, I'm unable show you the ordering for higher order matrices, but I hope that you get the idea - the value increases top to bottom, left to right, back to front (for cube matrices), etc.
The hashing function is defined like this:
value = x1+d1*x2+d1*d2*x3+d1*d2*d3*x3+...+d1*d2*d3*...*d|n-1|*xn
where:

*

*x1...xn are index members - row, column, height, etc - {x1, x2, x3,
..., xn}

*d1...d|n-1| are matrix boundary dimensions - one past the end of matrix in the appropriate direction

I'm actually using a recursive form of this function (simple factoring, but complexity becomes O(n) instead of O(n^2)):
value = x1+d1(x2+d2(x3+d3(...(x|n-1|+d|n-1|(xn))...)))
I'm assuming that elements will be distributed randomly (uniform) across the matrix, but the bucket number is hash(key) mod numberOfBuckets, so it is practically guaranteed to have collisions despite the fact, that the function is perfect.

*

*Is there any way to exploit the features of my hash function in order to minimize collisions?

*How should I choose the load factor? Should I leave the choice to the user? Is there any good default value for this case?

*Is the hash table actually a good solution for this problem? Are there any other data structures that guarantee average O(1) complexity given that I can roll the index into  a number and a number into an index (mind the size_t overflow)? I am aware of different ways to store a sparse matrix, but I want to try the DOK way first.


text:
Q: EF insert related objects I am using silverlight client with ado.net dataservices on entity framework.
I have an Entity Contact and an Entity Address which is related with a foreign key relation ship...
A contact can have 1 or more Adresses but a Address needs always at least 1 contact..
pretty basic...
I have a Repository for my contacts and Address which has a Method Add(T entity),...
On my Client I have a form with allows users to add a contact with an address
and I want to save both away to the database...
Address a = new Address();
a.Street="Street",
a.City = "City"
a.Contact =
 new Contact(){ Name="Name",Age="60"}

_repository.Add(a);

....

Ok i figured out that I can not save a related object graph right away so i did something like this
DataBaseEntities.AddToContact(obj2Badded.Contact);
DataBaseEntities.AddToAddress(obj2Badded);
DataBaseEntities.SetLink(obj2Badded,"Contact",object2Badded.Contact);
DataBaseEinties.BeginSaveChanges(...)

Is there away to do this in transations like when contact is not added address will also not be added and vice versa...
... and all what I have tried is not working...
It would be great if someone can point me in the right direction on this topic I simply want to add a related object graph =} ...

A: Your first example should work just fine, related entities and all. There is no need to add related entities to the context separately, if you are inserting new objects for both of them. So unless you tell us what the problem is when you ran this code, it will be hard to help.

A: I had a similar problem and it worked for me after adding something like
DatabaseEntities.UpdateObject(obj2Badded);

just before
DatabaseEntities.BeginSavingChanged();

This isn't needed if you include the edmx in your project en use the ObjectContext, but it is needed if you create a Service reference and use the generated DataServiceContext.


text:
Q: Updating Magento 2 product attribute, Import Add/Update feature always create a duplicate new item, instead of updating i'm trying to update a custom product attribute called is_eol, but when i use the system->data transfer->import -> import behavior (add/update), it always created a duplicate item with same sku number.
for example, my csv file looks like:
sku, is_eol
abc, eol
where sku:abc is already exist in the catalog.


text:
Q: React-Native Generating Signed APK (Error: Missing keystore) I recently switched to mac and am not being able to generate signed Apk. Previously I used ubuntu and everything was working fine. I think I missed some configuration on my part but couldn't findout what. I started a new react-native app and followed the react-native guide to generate keystore file and to configure gradle.
I get following error when I try generate signed Apk with ./gradlew assembleRelease --stacktrace
:app:compileReleaseSources UP-TO-DATE
:app:lintVitalRelease
:app:transformClassesWithDexForRelease UP-TO-DATE
:app:mergeReleaseJniLibFolders UP-TO-DATE
:app:transformNative_libsWithMergeJniLibsForRelease UP-TO-DATE
:app:processReleaseJavaRes UP-TO-DATE
:app:transformResourcesWithMergeJavaResForRelease UP-TO-DATE
:app:validateSigningRelease FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:validateSigningRelease'.
> Keystore file /Users/infiniahub/Documents/sandbox/testapp/android/app/my-release-key.keystore  not found for signing config 'release'.

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:validateSigningRelease'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:25)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:153)
        at org.gradle.internal.Factories$1.create(Factories.java:22)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:53)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:150)
        at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
        at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:98)
        at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:92)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:63)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:92)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:83)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:99)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:48)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
        at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:81)
        at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:46)
        at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:51)
        at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:28)
        at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:43)
        at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:173)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:239)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:212)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:205)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
        at org.gradle.launcher.Main.doAction(Main.java:33)
        at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:55)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:36)
        at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
        at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:30)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:127)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Caused by: java.lang.IllegalArgumentException: Keystore file /Users/infiniahub/Documents/sandbox/testapp/android/app/my-release-key.keystore  not found for signing config 'release'.
        at com.android.build.gradle.internal.tasks.ValidateSigningTask.validate(ValidateSigningTask.java:107)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:228)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:221)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:210)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:621)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:604)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
        ... 60 more

BUILD FAILED

Total time: 10.797 secs

But I have keystore file on that path and ls shows following
Infinias-MacBook-Pro:android infiniahub$ ls -alh /Users/infiniahub/Documents/sandbox/testapp/android/app/
total 40
drwxr-xr-x   8 infiniahub  staff   272B Apr  2 12:36 .
drwxr-xr-x  12 infiniahub  staff   408B Apr  2 12:38 ..
-rw-r--r--   1 infiniahub  staff   1.5K Apr  2 12:30 BUCK
drwxr-xr-x   6 infiniahub  staff   204B Apr  2 12:37 build
-rw-r--r--   1 infiniahub  staff   5.7K Apr  2 12:36 build.gradle
-rw-r--r--   1 infiniahub  staff   2.2K Apr  2 12:32 my-release-key.keystore
-rw-r--r--   1 infiniahub  staff   2.4K Apr  2 12:30 proguard-rules.pro
drwxr-xr-x   3 infiniahub  staff   102B Apr  2 12:30 src

My Gradle configs
cat ~/.gradle/gradle.properties
MYAPP_RELEASE_STORE_FILE=my-release-key.keystore
MYAPP_RELEASE_KEY_ALIAS=my-key-alias
MYAPP_RELEASE_STORE_PASSWORD=password
MYAPP_RELEASE_KEY_PASSWORD=password

cat android/app/build.gradle
defaultConfig {
......
}
signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
                }
            }
    }
    splits {
        ..........
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        signingConfig signingConfigs.release
        }
    }

Has anyone seen this before? Any help would be greatly appreciated!

A: After 5 days of searching and hair pulling, I finally found the issue. The issue was on my ~/.gradle/gradle.properties file.
MYAPP_RELEASE_STORE_FILE=my-release-key.keystore had extra space appended. Removed the extra space and everything is back to normal.


text:
Q: Java function not working when called twice public static int getMinor(int[][] mat, int r, int c) {
  int minor = 0;
  int[] min = new int[4];
  int x = 0;
  while (x <= 3) {
    for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
        if (i != r && j != c && mat[i][j] != 100) {
          min[x] = mat[i][j];
          x += 1;
          mat[i][j] = 100;
        }
      }
    }
  }
  minor = min[0] * min[3] - min[1] * min[2];
  return minor;
}

public static void main(String[] args) {
  int[][] mat = getMatrix();
  System.out.println(getMinor(mat, 0, 0));
  System.out.println(getMinor(mat, 1, 1));
}

for some reason when I call getMinor function again the code stops working.
It prints the minor the first time but does not work when I call it again in the next line.
getMatrix function just gets the matrix.

A: Your code contains the potential for an infinite loop. It is possible for (x <= 3) to never become false, and so for your while loop to run forever.  You haven't given your input matrix, but I assume that what is happening is that the first call to getMinor returns and so println prints the returned result, but then the execution goes into getMinor the second time and gets stuck...never comes out, and so the second println never occurs and the program never exits.
Yes, that's what's going on. I just made up an arbitrary matrix, and my run prints a 0 and then locks up in the second call to getMinor, going around and around in the while loop forever with if (i != r && j != c && mat[i][j] != 100) never being true, and so x never changing.  This occurs because you're operating on the same matrix the second time, and the locations already set to 100 are sufficient to cause the while loop to never exit.
If you start with a fresh matrix the second time, this doesn't so easily occur. This code, at least with my sample matrix, completes:
int[][] mat = getMatrix();
System.out.println(getMinor(mat, 0, 0));
mat = getMatrix();
System.out.println(getMinor(mat, 1, 1));

Another potential problem with your code (I say potential because maybe you will never use the wrong parameters so that this happens) is if you pass in r and c values that are larger than the w/h bounds of the matrix, then the program crashes with an index out of bounds error because the if clause succeeds more than 4 times in a run through the matrix, and so you haven't allocated enough slots in the min array, and min[x] = mat[i][j]; goes bang!.

A: *

*You've changed the value of "mat" in "getMinor", so 2ed call dose not have same input as the 1st one . (You may read this to figure out java's "pass by reference" VS  "pass by value")

*It's not a good practice to modify input within a function named as "getXXX"