text:
Q: How to take users email address from a datagrid and populate it in an email in asp.net Currently my application is able to open up a Outlook email with a default recipient once a user has clicked Image button which is located inside a Grid View. The aspx code for this is as follows;
<asp:ImageButton ID="LinkEmail" OnClick="openClient" CommandArgument='<%# Eval("customerId") %>'
                                            ToolTip="Send a Email to this customer" ImageUrl="~/SiteElements/Images/email_icon.jpg"
                                            Width="16px" Height="16px" runat="server" />

I have a Bound Field Data Field with the ID "custEmail" which shows a customers email in the Data Grid if one is linked to their account. The code used to open the Outlook application was taken from this question and the only addition I have added is the address the email is being sent to;
Protected Sub openClient(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim Out1 As Object
    Out1 = CreateObject("Outlook.Application")
    If Out1 IsNot Nothing Then
        Dim omsg As Object
        omsg = Out1.CreateItem(0) '=Outlook.OlItemType.olMailItem'
        omsg.To = "sample.email@test.com"
        'set message properties here...'
        omsg.Display(True)

    End If

What I would like to do is replace the sample email with the email showing for the customer in the data grid. When I try to do this like this;
omsg.To = custEmail

The code behind doesn't find this Bound Field Data Field.
How do I allow my code-behind to see the "custEmail" BoundField so I can popular "omsg.To" with a customers email address?

A: I suggest you to pass Customer Email address as CommandArgument in ImageButton and add another property CommandName.
<asp:ImageButton ID="LinkEmail" OnClick="openClient"
       CommandName="SendEmail"
       CommandArgument='<%# Eval("CustomerEmail") %>'
       ToolTip="Send a Email to this customer"
       ImageUrl="~/SiteElements/Images/email_icon.jpg"
       Width="16px" Height="16px" runat="server" />

Next add OnRowCommand event in GridView:
<asp:GridView ID="GridView1" runat="server"
        OnRowCommand="GridView1_RowCommand">
    </asp:GridView>

In your code-behind:
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)

    If e.CommandName = "SendEmail" Then
        Dim CustomerEmailAddress = e.CommandArgument

        Dim Out1 As Object
        Out1 = CreateObject("Outlook.Application")
        If Out1 IsNot Nothing Then
            Dim omsg As Object
            omsg = Out1.CreateItem(0) '=Outlook.OlItemType.olMailItem'
            omsg.To = CustomerEmailAddress
            'set message properties here...'
            omsg.Display(True)

        End If
    End If

End Sub


text:
Q: How to Waiting Webbrowser (Window Form) run Script C#? I have one problem when using Webbrowser to control website.
After i load a website
webBrowser.Navigate(pageURL);
                while (webBrowser.ReadyState != WebBrowserReadyState.Complete)
                    System.Windows.Forms.Application.DoEvents();

This website have 2 Select list
Select Distrcit ||||||||||||||||||||||
Select Ward ||||||||||||||||||||||||||
First i select District
elementDistrict.Children()[2].SetAttribute("selected", "selected");
elementDistrict.InvokeMember("onchange");

and Sleep (warting for "Select Ward" load data)
Thread.Sleep(1000)

after that, i select Ward
elementDistrict.Children()[3].SetAttribute("selected", "selected")

I can not select a ward because "Select Ward" data is not load yet.
HTML page before select district:
<select id="cboDistrictPost" onchange="ChangeDistrictPost($(this).val())" class="select" tabindex="5">
    <option value="1">District 1 </option>
    <option value="2">District 2 </option>
</select>

<select id="cboWardPost" class="select" tabindex="5">
    <option value="-1">---Select Ward---</option>
</select>

A: It sounds like you are setting the thread to sleep that the web browser is on. If you set the UI thread to sleep the web browser will not continue loading.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What happens to the sealed object when unsealing it in TPM? What happens when I unseal a sealed piece of data in TPM? Does the sealed data still exist?
For example, I have a handle to sealed data hSealedData, and I do TPM_Unseal(hSealedData,...) twice in a row. Will both calls return the same unsealed data?
I couldn't find documentation about this.

A: What happens is that the current PCR values will be compared to the PCR values recorded at the time of sealing and, if they match, the object will be decrypted and sent back. Nothing will happen to the sealed data as the sealed data is not stored in the TPM, it is returned to the user at the time of sealing.


text:
Q: PHPDoc to assign @param as a referened @property I'm trying to define a param for a method as being the ID field from another class. Basically this idea...
/**
 * @param \Database\Member::id $memberId
 * @return MemberEntity
 */
public function getMember( int $memberId ) : MemberEntity
{
...
}

the @see command doesn't seem to be the right solution for this. Is there something I'm missing here? The PHPDoc website is surprisingly minimal...
thanks!

A: The @param tag receives the values: type, name and description. Apparently the type of your variable is int. If the \Database\Member::id attribute is not a native type of php or a class, it can not be used that way. So it is not possible to do this type of reference you want in traditional PHPDoc.
Syntax
@param [Type] [name] [<description>]


text:
Q: A weird automorphism Consider the polynomial $f(t) = t^5 -4t+2$ over $\mathbb{Q}$. By Eisenstein's criterion, this is irreducible. By graphing this function, we see that it has 3 real roots, hence 2 (distinct, because they are conjugates) non-real roots. Therefore as 5 is prime, we can use a well known lemma to see that the Galois group of group of $f$ over $\mathbb{Q}$ is $S_5$. Now I want to look at the Galois group of $f$ over $\mathbb{Q}(i)$. Now I have managed to show that the group is either $A_5$ or $S_5$. Let the roots of $f$ be $\alpha_1,...,\alpha_5$ with $$\alpha_1 = x +iy$$ $$\alpha_2 = x-iy$$ $$y\ne0$$
Complex conjugates. Now let $\phi$ be the element of $Gal(f)$ over $\mathbb{Q}$ defined by complex conjugation. I.e. it fixes $\alpha_3,\alpha_4,\alpha_5$ and swaps $\alpha_1$ with $ \alpha_2$. This clearly does $not$ fix $i$, so $Gal(f)$ over $\mathbb{Q}(i)$ (call this group $G$) is not all of $S_5$, hence is $A_5$.
Although the line of reasoning here seems valid, it leads to some weird consequences. Given that $G$ = $A_5$, when we represent automorphisms by cycle types, any double transposition must be in the Galois group, i.e. must fix $i$. In particular $$(\alpha_1,\alpha_2)(\alpha_3,\alpha_4)$$
Must fix $i$. But when we apply this to $\alpha_1$, say, it would seem to involve conjugating it, and hence moving $i$. A contradiction. Yet if my line of reasoning is correct, this double transposition must leave $i$ fixed. How is this possible? Have I made an error somewhere, or just missing something obvious?
Many thanks.


text:
Q: How to design notification for group chat in sql? I want to do this below to notify user but I am not sure about quality and slow query:
When someone insert new message to group chat SQL will select all members of group chat and then in the loop for each user it will insert user_id group_id unseen_message_count.Is that too heavy to do for each message in the chat because sometime people write really fast and doing this for each message?Have better option?
Update version
My sql is like below:
chat_seen table

user_id | group_id | unseen_count

when new chat inserted I will update unseen_count for each user then when they see unseen_count,I will update unseen_count to 0.I think it is heavy if I do this for each member of group,Is not it?

A: Your question is a bit vague, and it doesn't sound like a great solution, but not terrible either. The important thing to remember, is to ensure there are indexes on all the fields in your WHERE statements (e.g. group_id, user_id, etc).
You should also think about whether simply storing the id of the last message read for each user, might be enough to calculate that count without having to constantly update so many rows every time a message is posted.


text:
Q: A* path finding: backed into a corner, now what? I'm writing a tower defense game, and I'm implementing the A* path finding algorithm from tutorials and what not, but I've encountered a situation I can't code out of as of yet!  Consider the graphic below.  The cyan nodes represent the shortest path found so far, the violet nodes represent inspected nodes, and the dark gray nodes represent a wall.
From what I know of the A* algorithm, to calculate a path for the situation below, it...

*

*Starts at "start" and checks if the upper node is available.  It is.  It calculates its G and H scores.  It does the same to the right, lower, and left nodes.

*Finds that the right node has the lowest F score (F = G + H).  It then repeats the same method as step #1 to find the next node, marking the "start" node as the parent.

*Continues this pattern and lands on the node in the center of the "C trap," as this node has the lowest F score so far.

*Discovers that the upper, right, lower, and left nodes are all closed.  A* then marks this node as closed and starts over, understanding to leave this node alone.

What happens immediately after #4?  Would A* re-examine the G and H scores along the same path, skipping that newly-closed node?  Also, when drawing this scenario with this SWF, it indicates that more nodes are discovered to make up for the trap, as suggested here.  Why?

A: What you seem to be missing is that A* is not like a single unit moving along the grid, and backtracking when it hits a wall; it's more like an observer looking at various nodes around the graph, always considering next the node "most likely" to be in the shortest path.
So, step 4 above never happens.  A* doesn't mark a node as closed when it determines it can't be part of the best-path - it simply puts every single node it vists in the closed list, as soon as it visits it.  And it doesn't ever "start over" - it's always looking at the next "most likely" node, where "most likely" means the front of the priority queue ordered by f(x).
So, in your example above, A* will jump to one of the blue-nodes next, since they are all in the open list, and all have the same f(x) value.  Though it could technically consider any one of them next, if you use the correct tie-breaking criteria, it will take one of the two that are closest to the end.


text:
Q: Can you tell me Step-By-Step Guidelines of How to use HtmlUnit to make GWT app Crawlable? Making your GWT app to be indexed by Search Engine is very important, but very very little info to tell you Step-By-Step Guidelines of How to make GWT app Crawlable dynamically.
Ok, Here is what I understood but I am not sure 100% I am correct or not. SO please correct me if you can.
To make a Gwt page ex myDomain.com#article;articleID=1 to be indexed by search engine, you need to:
-1st, convert myDomain.com#article;articleID=1 to myDomain.com#!article;articleID=1
-2nd, when Google /Yahoo bot visits that page (myDomain.com#!article;articleID=1), it will convert that page into (myDomain.com?_escaped_fragment_=article&articleID=1) & request that page into your webserver.The Web server then will try to render that page to the Bot.
So if we have a static page of myDomain.com?_escaped_fragment_=article&articleID=1, then the content of that page will be read by the Bot & can be indexed.
But the article is dynamic cos user could enter myDomain.com?_escaped_fragment_=article&articleID=2 or ...article=3... but we can't manually make the static page for each of article.
So the solution is HtmlUnit.
A tool like HtmlUnit will dynamically convert myDomain.com?_escaped_fragment_=article&articleID=2 into a page that the bot can read.
But I don't know step-by-step guidelines of How to set HtmlUnit up?
Is HtmlUnit like a jar file that we can put into lib? what should we do next?
used solution from Patrik, then compile then out int into webapp of Tomcat7 but got this err in the browser
type Exception report

message Filter execution threw an exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Filter execution threw an exception
    com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:66)
    com.gwtplatform.dispatch.server.AbstractHttpSessionSecurityCookieFilter.doFilter(AbstractHttpSessionSecurityCookieFilter.java:67)
    com.google.inject.servlet.FilterDefinition.doFilter(FilterDefinition.java:163)
    com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:58)
    com.google.inject.servlet.ManagedFilterPipeline.dispatch(ManagedFilterPipeline.java:118)
    com.google.inject.servlet.GuiceFilter.doFilter(GuiceFilter.java:113)
root cause

java.lang.NoClassDefFoundError: org/w3c/css/sac/ErrorHandler
    myproject.server.CrawlFilter.doFilter(CrawlFilter.java:101)
    com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:66)
    com.gwtplatform.dispatch.server.AbstractHttpSessionSecurityCookieFilter.doFilter(AbstractHttpSessionSecurityCookieFilter.java:67)
    com.google.inject.servlet.FilterDefinition.doFilter(FilterDefinition.java:163)
    com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:58)
    com.google.inject.servlet.ManagedFilterPipeline.dispatch(ManagedFilterPipeline.java:118)
    com.google.inject.servlet.GuiceFilter.doFilter(GuiceFilter.java:113)
root cause

java.lang.ClassNotFoundException: org.w3c.css.sac.ErrorHandler
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
    myproject.server.CrawlFilter.doFilter(CrawlFilter.java:101)
    com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:66)
    com.gwtplatform.dispatch.server.AbstractHttpSessionSecurityCookieFilter.doFilter(AbstractHttpSessionSecurityCookieFilter.java:67)
    com.google.inject.servlet.FilterDefinition.doFilter(FilterDefinition.java:163)
    com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:58)
    com.google.inject.servlet.ManagedFilterPipeline.dispatch(ManagedFilterPipeline.java:118)
    com.google.inject.servlet.GuiceFilter.doFilter(GuiceFilter.java:113)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.53 logs.

A: See this SO working example inspired from this gwt-platform example and this Google documentation among others.
You setup HtmlUnit on the server side like any other library by adding their jar in you lib folder -- as far as I recall, that's all there is to it.


text:
Q: Replace string in system path with Powershell I need to change C:\Program Files (x86) in C:\Progra~2 in the system path variable. I was thinking to do this with Powershell, so I came up with the following script.
$NewPath = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path

$OldValue = ${Program Files (x86)}
$NewValue = "Progra~2"

$NewPath = $NewPath -replace $OldValue, $NewValue

Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH –Value $newPath

$NewPath

The output is unfortunately not what I expected.
Progra~2oProgra~2mProgra~2eProgra~21Progra~2\Progra~2oProgra~2pProgra~2mProgra~2nProgra~2\Progra~2bProgra~2iProgra~2nProgra~2;Progra~2CProgra~2:
Progra~2\Progra~2OProgra~2rProgra~2aProgra~2cProgra~2lProgra~2eProgra~2\Progra~2MProgra~2iProgra~2dProgra~2dProgra~2lProgra~2eProgra~2wProgra~2a

Can anyone help me out with this?

A: $OldValue = ${Program Files (x86)}

should be replaced by
$OldValue = "Program Files \(x86\)"

Backslashes \ escape the parens interpreted as a regex by -replace


text:
Q: Вопрос по поводу ввода: заменить строковую константу в коде на пользовательский ввод Можно ли в этом коде самому задавать нужные значения?Вместо 'dfR56*Jvn' из клавиатуры вводить не изменяя в самом коде
import re
a=re.findall('[a-z]','dfR56*Jvn')
print (len(a))

A: Используйте просто ввод данных через input()
import re
a = re.findall('[a-zа-я]', input(""))
print(len(a))

Реализация через список
import re
a = list(filter(None, list(map(lambda x: re.findall('[a-zа-я]', x), list(input())))))
print(len(a))

Проверка
Hello World Привет Мир
15


text:
Q: Good jQuery Plugin for a Form Field Initial or Default Value? What is a good jQuery plugin for a showing default value in an input box that disappears when it gets focus or a user starts entering text?

A: The class/type of plugins you're looking for are called watermark plugins, there are quite a few out there, for example check jquery-watermark out.
It depends on how much you want from it, there are also very minimal versions, like In-Field.

A: I used this one and it works pretty well. http://fuelyourcoding.com/scripts/infield/
It's a bit quirky but works once you understand it


text:
Q: Apache with php on subdirectory of main site My current configuration consists of this, where :8000 is a nodejs app with express.
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com

    Alias /old /var/www/php-site
    <Directory "/var/www/php-site">
        Options Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
        Require all granted
    </Directory>

    ProxyRequests on
    <Location />
        ProxyPass http://localhost:8000/
        ProxyPassReverse http://localhost:8000/
    </Location>

</VirtualHost>

How do I get this to work where /old directs to the old site? For some reason it wont recognize it. Or even better, how do I keep both at the "/" level where "/page" will go to the app with a matching directory. For instance, if php-site has the page /intro but the express site doesn't, it will pull the page from the php site. And if the express site has the page "/about" it will pull it from there?


text:
Q: Cpp copy to clipboard event As the topic, i know that is a way to get clipboard text but i wanna get the data from clipboard only when user click copy or trigger CTRL+C.
I found this X11 Wait for and Get Clipboard Text
but isn't for windows.
I tried also that but the result doesn't satisfy me.
std::string GetClipboardText() {
  // Try opening the clipboard
  if (! OpenClipboard(nullptr))
    ... // error

  // Get handle of clipboard object for ANSI text
  HANDLE hData = GetClipboardData(CF_TEXT);
  if (hData == nullptr)
    ... // error

  // Lock the handle to get the actual text pointer
  char * pszText = static_cast<char*>( GlobalLock(hData) );
  if (pszText == nullptr)
    ... // error

  // Save text in a string class instance
  std::string text( pszText );

  // Release the lock
  GlobalUnlock( hData );

  // Release the clipboard
  CloseClipboard();

  return text;
 }


text:
Q: Integer values considered by VB.Net datatable as decimals after MySQL query In VB (Winforms) I am extracting statistics from MySQL database and the resulting datatable is used to build different charts. What made me impression is that depending on MySQL query in some cases pure integer values are considered as decimals in datatable and thus my charts look strange with their grid lines depicted with fractions of 1. Examples are below.
When I use in my query grouing the result is not what I expect. Query looks like following:
select Cell,Time,
sum(counter12) as counter
from h_cell
where cell='ABC' and time>='2018-05-26' and time<='2018-06-01'
group by Cell,Time

In this case the datatype of datatable's column 'counter' is 'System.Decimal'. I need to stress that the value is always integer. Also I cannot avoid grouing in my query. The problem is that my chart looks not right with grid lines showing values less than one.

When I design my query without grouping then datatype of the column in datatable is 'System.Int32' and then chart looks as it should.
select Cell,Time,
(counter12) as counter
from h_cell
where cell='ABC' and time>='2018-05-26' and time<='2018-06-01'

Is there a way to avoid this inconsistency?

A: You might want to take a look at the table structure in MySQL and refer to this page for the equivalent to see why you might be getting a Decimal type: Visual Basic / MySQL Datatypes
Something else you might try (as someone else suggested) is to cast to the data type you are expecting. The only difference is that I would not cast your column, but the result of your sum as follows:
select Cell,Time,
Cast(sum(counter12) As SIGNED) as counter
from h_cell
where cell='ABC' and time>='2018-05-26' and time<='2018-06-01'
group by Cell,Time


text:
Q: Where are Adobe Flash cookies (sol files) stored? Adobe Flash cookies (files with .sol extension) used to be located in ~/.macromedia. This folder no longer exists in Ubuntu 14.04LTS and newer. If the method of installing Flash has any effect on the location, the Ubuntu Installer option is how I installed it. So where are the Flash Cookies now located? I've tried searching for .sol files with no luck - and yes I have "Show Hidden Files" enabled in File Manager. Does anyone know where they're stored now?

A: If you checked the "Install this third party software" option during Ubuntu installation process, you're using NPAPI Adobe Flash plugin installed through flashplugin-installer package. The same plugin is provided by adobe-flashplugin package from Canonical Partner repo as well. This is the plugin generally used by Firefox and all other browsers not based on Chromium. In this case, the cookies are stored at:
~/.macromedia/Flash_Player/#SharedObjects/
~/.macromedia/Flash_Player/macromedia.com/support/flashplayer/sys/

Google Chrome bundles a Pepper Plugin API (PPAPI) based Flash plugin. For this plugin, the .sol files are stored at:
~/.config/google-chrome/Default/Pepper Data/Shockwave Flash/WritableRoot/#SharedObjects/

If you use the PPAPI Flash plugin on other Chromium based browsers, replace google-chrome in the path given above with name of your browser. For example, with Chromium:
~/.config/chromium/Default/Pepper Data/Shockwave Flash/WritableRoot/#SharedObjects/

Tested on Adobe Flash 21.0 PPAPI and 11.2 NPAPI plugins.
Source : Wikipedia page on Local Shared Object
Thanks to Xen2050 for providing info about Flash plugin on Chromium!

A: There is the ~/.macromedia folder in 11.04. Your flash cookies are located in ~/.macromedia/Flash_Player/macromedia.com/support/flashplayer/sys directory.
There is another way to see your flash cookies and make whatever you want with them  in the Global Storage Settings panel from the Adobe Flash Player Website.
Also, if you want to find out more about flash cookies, there are many things to know about them here.

A: Type this in terminal:
locate *.sol
Or to remove all flash cookies:
rm `locate *.sol`

Note that locate isn't updated very fast, so if you run locate *.sol again after removing them. It'll indicate that the files still exists. Try to remove them again, an you'll get a couple of messages indicating that the files do not exist anymore.
This method is fairly reliable, but won't remove very fresh flash cookies, since they haven't been indexed yet, and so 'locate' doesn't know about them yet.

A: If you download and install a flash game on your computer, you can find it in:
Home/.wine/drive_c/user/"User name"/Application Data/Macromedia/Flash Player/#SharedObjects/"some random code?"/localhost/Downloads/...

hope it useful


text:
Q: Undefined property: stdClass::$category I have a json file that looks like this
{
    "Product_1": {
        "name": "Product 1",
        "category": "Yellow"
    },
    "Product_2": {
        "name": "Product 2",
        "category": "Blue"
    },
    "Product_3": {
        "name": "Product 3",
        "category": "Yellow"
    }
}

I need to do a bulk change on all my categories if that category is yellow. When I try to do it I get this error
Undefined property: stdClass::$category

Here is my code
$products = Product::all();

foreach($products as $product)
{
    $json = file_get_contents(storage_path("products/$product->id/products.json"));
    $productJson = json_decode($json);

    if($productJson->category == 'Yellow')
    {
        $productJson->category = 'Green';
        file_put_contents(storage_path("products/$product->id/products.json"), json_encode($productJson, JSON_PRETTY_PRINT));
    }
}

I get this when I dd($productJson)
{
  +"name": "Product 1"
  +"category": "Yellow"
}

and if I var_dump($productJson) I get my json output but then I also get the error afterwards.


text:
Q: YouTube embeds not working in WordPress after import from Blogger I imported a series of blogger posts (via xml) into WordPress, and the YouTube embed tags were removed.
YouTube URLs in posts are not identified. Instead, just the text of the url is left. Possibly as opposed to full embed tags.
I'm trying to restore the embed codes so it's seen.
Another fact that is notable in the XML import is that [EMBLED CONTENT] appears instead of the url, that is, the video...

A:

…by default, WordPress filters imported XML by removing possible troublesome tags…unfortunateely, including things like <embed> and <iframe> and other instances where you've included content in your posts. WordPress does so via a file you can find in /wp-includes called kses.php. In kses.php, you'll want to scroll down to line 1309 and comment out the three lines under //Post filtering so that they look like this:

// Post filtering
#add_filter('content_save_pre', 'wp_filter_post_kses');
#add_filter('excerpt_save_pre', 'wp_filter_post_kses');
#add_filter('content_filtered_save_pre', 'wp_filter_post_kses');

Source: http://jasongriffey.net/wp/2010/06/21/moving-to-wordpress-3-0/ and http://wordpress.org/support/topic/youtube-embeds-not-working-after-import

A: I think you have a couple of options here:

*

*You could undo the import and
re-import using another means, from
RSS for instance.  The value of this
depends on how much effort you have
in the posts as they are in
WordPress now - are you willing to
dump the posts and try again?

*You go to the forums, post a bug in
trac, go to the IRC channel and try
to find some more information;
you're apparently not the only
person to have this problem
(unless, of course, that's you)

*if you have db access you could
update the posts table to add the
appropriate code back in.

*you could manually re-add the embed
codes (obviously).

How many posts are we talking about?

A: This all really depends on HOW you imported the blog posts. What was your method?
When you view the raw source of the posts in wordpress (plain text view) - what does the post look like (a copy of the HTML would be nice)
-- Note - edit your original post to give the answers, a reply doesn't really work if other people answer too.

A: When I moved from blogger to wordpress my YouTube videos moved over just fine. Martin is right, a view of the post source code is probably required to be helpful.
One thing to note on a side issue though. When you use the wordpress "blogger importer" the image links will not be updated. When you view your blog everything will look ok, but in fact the images will still be referencing the blogger site.
There is a plugin on wordpress.org that will help with this, but some manual updating may / will be required for a 100% perfect move.
I think this is the one I used.
http://wordpress.org/extend/plugins/blogger-image-import/

A: Here's the solution I found on a wordpress forums.
Find in /wp-includes a file called kses.php. In kses.php, you'll want to scroll down to line 1309 and comment out the three lines under //Post filtering so that they look like this:
// Post filtering
#add_filter('content_save_pre', 'wp_filter_post_kses');
#add_filter('excerpt_save_pre', 'wp_filter_post_kses');
#add_filter('content_filtered_save_pre', 'wp_filter_post_kses');

This will prevent the filter from removing all your YouTube videos, SlideShare embed, Scribd documents, etc.


text:
Q: Can not call procedure by JPA - could not determine data type of parameter When trying to call procedure with timestamp parameters by the code:
        SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(dataSource)
                .withSchemaName("time_series")
                .withProcedureName("refresh_continuous_aggregate")
                .declareParameters(new SqlParameter("continuous_aggregate", Types.VARCHAR),
                        new SqlParameter("window_start", Types.TIMESTAMP),
                        new SqlParameter("window_end", Types.TIMESTAMP));

        MapSqlParameterSource inParams = new MapSqlParameterSource()
                .addValue("continuous_aggregate", "time_series.current_data_hourly", Types.VARCHAR)
                .addValue("window_start", "2020-11-12 01:02:03.123456789", Types.TIMESTAMP)
                .addValue("window_end", "2021-02-12 01:02:03.123456789", Types.TIMESTAMP);
        Map<String, Object> execute = simpleJdbcCall.execute(inParams);

I'm getting error:

ERROR o.s.i.handler.LoggingHandler ->
org.springframework.jdbc.BadSqlGrammarException:
CallableStatementCallback; bad SQL grammar [{call
time_series.refresh_continuous_aggregate(?, ?, ?)}]; nested exception
is org.postgresql.util.PSQLException: ERROR: could not determine data
type of parameter $2

The similar error I'm getting when I try to use native query with dynamic parameters:
String queryStr = "CALL time_series.refresh_continuous_aggregate(?1, ?2, ?3)";
Query query = entityManager.createNativeQuery(queryStr)
        .setParameter(1, continuousAggregate)
        .setParameter(2, windowStart, TemporalType.TIMESTAMP)
        .setParameter(3, windowEnd, TemporalType.TIMESTAMP);
Object singleResult = query.getSingleResult();

ERROR o.h.e.jdbc.spi.SqlExceptionHelper -> ERROR: syntax error at or
near "$2"

And by using StoredProcedureQuery:
StoredProcedureQuery query = entityManager.createStoredProcedureQuery("time_series.refresh_continuous_aggregate")
        .registerStoredProcedureParameter("continuous_aggregate", String.class, ParameterMode.IN)
        .registerStoredProcedureParameter("window_start", Date.class, ParameterMode.IN)
        .registerStoredProcedureParameter("window_end", Date.class, ParameterMode.IN)
        .setParameter("continuous_aggregate", "time_series.current_data_hourly")
        .setParameter("window_start", new Date(), TemporalType.TIMESTAMP)
        .setParameter("window_end", new Date(), TemporalType.TIMESTAMP);
query.execute();

WARN  o.h.e.jdbc.spi.SqlExceptionHelper -> SQL Error: 0, SQLState:
42P18 ERROR o.h.e.jdbc.spi.SqlExceptionHelper -> ERROR: could not
determine data type of parameter $2

It looks like JDBC drivers issue.


text:
Q: Angular 7 array change value I am working on a complex array in which questions and its related answers are coming from the service. After receiving the array I want to change the attribute 'IsChecked' of the Answers to false. My code for this is
this.questions.forEach( elm => {
                  elm.Awnsers.forEach( ans => {
                    ans.IsChekced = false;
                  });
                });

and the output coming is
{Awnser: "Periapical radiograph(s).", IsChecked: true, Qid: 1, IsChekced: false}

As you can see instead of changing the value of IsChecked the code is adding another attribute with the same name. What is wrong am I doing?

A: IsChekced is spelled incorrectly. It is not IsChecked
k <==> c

A: I think you misspelled the IsChecked key with IsChekced
Just update below code it will work.
this.questions.forEach( elm => {
                  elm.Awnsers.forEach( ans => {
                    ans.IsChecked= false;
                  });
                });

Hope this will help

A: Yes you just misspelled the IsChecked you can do this by below code
this.questions.forEach( elm => {
    elm.Awnsers.forEach( ans => {
      ans.IsChecked = false;
    });
  });
  console.log(this.questions);


text:
Q: broadcast receiver on android 8.0 not working I am trying to make app that launch activity from broadcast receiver when
call was incoming and it is working on below android 8.0 but it not working on above android 8.0.
here is my code.
MyReceiver
public void onReceive(final Context context, final Intent intent) {

      try {
        tm = (TelephonyManager)context.getSystemService(context.TELEPHONY_SERVICE);
          PhoneStateListener psl = new PhoneStateListener(){
              @Override
              public void onCallStateChanged(int state,final  String num){

                  if (state == TelephonyManager.CALL_STATE_RINGING){
                      try {

                          new  Handler().postDelayed(new Runnable() {
                              @Override
                              public void run() {
                                  i = new Intent(context, MainActivity.class);
                                  i.putExtra("num", num);

                                  i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                  i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                                  i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                  context.startActivity(i);
                              }
                          }, 300);

                      }catch (Exception e){

                      }
                  }

in manifest
  <receiver android:name="com.deva.caller.Receiver">
<intent-filter>
    <action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
        </receiver>


text:
Q: How can I find out if a subset of Stack Exchange users increase/decrease their post rate based on badges earned? I'm trying to mine that Stack Exchange data dump to find out whether there is a cluster of users that may be positively or negatively affected by the number of badges they've been awarded. The theory I'm working on is that for some people who were motivated by badges, that they eventually lose their appeal and they stop posting.
Currently, I've filtered the raw data down to a set of:

*

*User ID

*Year and Month

*Posts made during that month

*Total badges that user has earned up to that month

I'm not sure how to proceed in order to find these users. I'm not even sure how to formulate this question into something I can take action on. If I visualize it in my head, what I'm thinking is seeing a chart of an x-axis of badges earned, a y-axis of posts made per month, and then seeing the line dip after a certain number of badges. But this only works on a per user level. I want to find the cluster of users for whom that chart would hold.
Any ideas?
Thank you!

A: In order to fully understand my answer and the references that I will provide, I will first (informally) introduce some concepts related to biology - most of the techniques that I will refer to are used in computational biology and therefore most of the reference you will find will assume a basic familiarity with the terms.
A gene is a unit from a living organism that can be "expressed" when required - that is, the gene will perform the action that it is associated with (often by coding the proteins that it represents that will perform the desired action).  e.g. a cell may build a variable amount of proteins from a gene that regulate its metabolism.
Biologists are often interested in tracking these genes and/or their expressions through time or evolution.
In your case, you are interested in understanding how the individual actions of the users (similar to a gene) are expressed through activity over time.  A user (similar to the organism) has several different actions that he can perform and we are assuming that the type of user and his current situation has some form of correlation with the actions that he will perform.
I would consider looking at two or three different techniques that are available - biclustering (sometimes row and column clustering, see figure 1 in link) and perhaps some sort of evolutionary tree (which is taken from this article) or a Hidden Markov Model.

In the case of biclustering, the idea is as follows, place the users on one axis and the actions on another axis of a matrix.  The values in this matrix will represent the number of actions that said user has made of the relevant type.  Reorder the users and actions in a way that groups similar items near each other 1, 2 and then use some form of clustering to group your users automatically (some algorithms can be find here).
The result of biclustering is that you can group users into subgroups and identify their traits in terms of actions.  Note that in this case, you will only have a "snapshot" of users and their actions - in order to better understand the trends through which user actions evolve, you might need to perform several biclusters for different scenarios.  Perhaps you might create biclusters for users that have spent a particular amount of time using Stack Exchange (say 1month, 3months, 6months, 1year) or users that have undergone a particular event (say just been awarded a badge yesterday).  This will allow you to analyse the trends better - although the exact statistics and interpretation should be properly interpreted.
As @AndyW pointed out in his link to How can I improve my analysis of the effects of reputation on voting? there are several problems that can arise from the data.  Misrepresentation, missing data, inaccurate data and small amount of data are but some problems that you might encounter.  Baldi and Brunak explain some of the problems that are typically encountered in data found in biological databases.  In particular note that there might be non-trivial redundancies in your data that you might need to normalise in some way (e.g. the same user in different stack exchange forums).

The alternative technique that I might suggest is based on evolutionary trees and/or Markov Models (HMM) - I grouped the discussion on these techniques because you could potentially use them in a similar manner.  In this case, we might visualise a starting point from which all users start and the users "evolve" or "change state" due to different phenomena.  After each state change, they are likely to perform a different volume and/or proportion of actions.
The main problem here will be creating the ideal taxonomy or HMM topology.  If (perhaps through biclustering as above) we identify four different types of user, a user will start by being assigned to one of these states and while in each of these state he will perform a different volume and proportion of actions.  From this point onwards I will focus on the use of HMMs as evolutionary trees are not designed to model cycles or transfers from one groups to another - which might make them better suited.
The work to be done in this case is to train the HMM from the data and identify how likely a user is to move from one state to another - notably from one state to the inactive user end state, where a user is no longer active.  This will allow you to create a model of user behaviour.
Now, once you have this HMM trained, all you need to do is get the list of user actions and trace this user through the most probable path - while in a particular state a user will be considered to be "of that type".
HTH


text:
Q: finding IOSurface headers I'm getting this error when I try to compile my tweak.
'IOSurface/IOSurfaceAPI.h' file not found
#include <IOSurface/IOSurfaceAPI.h>

I've tried this answer, but I can't find /System/Library/Frameworks/IOSurface.framework/Headers on my computer. I'm running osx 10.9.1. Thanks for the help.

A: Try this, not sure about the version it comes from:
http://ios-toolchain-based-on-clang-for-linux.googlecode.com/files/IOSurfaceAPI.h


text:
Q: Debugg ES6 Mocha tests with node-debugger I have a ES6 Babel project set up and everything is working fine. I run my tests using Mocha. Now I want to be able to run a debugger while running tests. This is what I have done so far:
npm install -g node-inspector
npm install -g babel-register

created a file called babel-hook.js
require('babel/register')({
  stage: 1,
  sourceMap: 'inline',
});

Now in one console I run:
node-inspector

Open Chrome
Then from project root I run:
mocha --debug-brk test/my-test-file.js

Then I put a breakpoint in my test:
When I hit F8 I get the following error:
/Users/h/Documents/code/js/test/my-test-file.js:1
(function (exports, require, module, __filename, __dirname) { import { assert } from 'chai';
                                                              ^^^^^^

SyntaxError: Unexpected token import
...

Now what am I missing to get this working???

A: You probably want the --compilers flag for mocha, which specifies how to compile the input files. For example, https://babeljs.io/docs/setup/#installation gives the example
mocha --compilers js:babel-register
Also, try running your tests without the --debug-brk to help isolate whether the breakpoints are the issue, or whether it's mocha in general (the solution described here is for the latter).
Finally, if this doesn't work, you may have better results installing babel-register non-globally (without the -g flag to npm install) as shown in the documentation: https://babeljs.io/docs/usage/require/


text:
Q: Path variable not recognized in Android Studio (ndk-build command is not recognized) I have an Android Studio project which won't recognize the PATH variable set for ndk-build.
If I run ndk-build from Terminal I get:
stpns-MacBook-Pro:~ stepanboltalin$ ndk-build
  Android NDK: Could not find application project directory !
  Android NDK: Please define the NDK_PROJECT_PATH variable to point to it.
  /usr/local/Cellar/android-ndk/r10b/build/core/build-local.mk:148: *** Android NDK: Aborting    .  Stop.

But if I try to compile project in Android Studio, I get error at 'ndk-build' commmandLine (below is the excerpt from build.gradle:
task ndkBuild(type: Exec) {

 # some stuff...

    if (ant.properties.os == 'windows') {
        commandLine 'ndk-build.cmd'
    } else {
        commandLine 'ndk-build'
    }

}

Now if I add the absolute path everything works fine:
task ndkBuild(type: Exec) {

 # some stuff...

    if (ant.properties.os == 'windows') {
        commandLine 'ndk-build.cmd'
    } else {
        commandLine '/usr/local/opt/ndk-build'
    }

}

Although the problem is seemingly solved, having build.gradle like that is sub-optimal for development. How can I fix this?

A: You can add the path to your NDK in the local.properties file of the root project:
ndk.dir=/opt/android/ndk

Then replace the invocation of ndk-build like this:
def localProperties = new Properties()
localProperties.load(project.rootProject.file('local.properties').newDataInputStream())
def ndkDir = localProperties.getProperty('ndk.dir')
def ndkBuildPrefix = ndkDir != null ? ndkDir + '/' : '';

if (ant.properties.os == 'windows') {
    commandLine ndkBuildPrefix + 'ndk-build.cmd'
} else {
    commandLine ndkBuildPrefix + 'ndk-build'
}


text:
Q: Pass object or pointer as value when not changing that object in function In c++ there are multiple ways of passing an object as parameter to a function. I have been reading up on passing by value and reference.
These links were very useful:
http://www.yoda.arachsys.com/java/passing.html
http://www.yoda.arachsys.com/csharp/parameters.html
And in the case of c++, which I am wondering about now, I saw this article as well:
http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
These go into the differences between passing by value and reference. And this last article also depicts a few pros and cons on the matter. I would like to know though the pros and cons of passing a parameter as a value in the case the object is not modified in the function.
int f(sockaddr_in s) {
// Don't change anything about s
}

int f(sockaddr_in *s) {
// Don't change anything about s
}

Both allow me to access the variables it has. But I would like to know which one I should use, and why.

A: In the first example f() obtains a copy of the original object and hence cannot possibly change the latter. However, the copy constructor is invoked, which may be quite expensive and is therefore not advisable as a general method.
In the second example f() either obtains a pointer or (for f(obj&x)) a reference to the original object and is allowed to modify it. If the function only takes a const pointer or reference, as in f(const object&x), it cannot legally change the object. Here, no copy is made. Therefore, passing by const reference is the standard approach for parameter that shall not be modified.

A: You are ignoring a fundamental thing of c++: const correctness: The declaration 'int f(sockaddr_in *s)' violates that. The 'int f(sockaddr_in s)' does not and might be reasonable (sockaddr_in is small or copied anyway). Hence, both 'int f(const sockaddr_in& s)' and 'int f(sockaddr_in s)' might be a good choice.


text:
Q: Unexpected output in multiple test cases.What is wrong with my solution? Codeforces problem 158B-http://codeforces.com/problemset/problem/158/B
My solution is giving unexpected output in several cases.I am currently stuck at test case 4.I am not able to find mistakes in my solution.What am I missing?My code:
#include<iostream>
using namespace std;
int n,a[100000],i,b,c,d,e,f,g,h;
int main()
{
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
    b=0;
    c=0;
    d=0;
    e=0;
    for(i=0;i<n;i++)
    {
        if(a[i]==1) //To check for number of 1,2,3 and 4 membered groups.
        b=b+1;
        if(a[i]==2)
        c=c+1;
        if(a[i]==3)
        d=d+1;
        if(a[i]==4)
        e=e+1;
    }
    f=e;
    if(d>b) //More 3 member groups than 1.
    {
        f=f+d; //f=f+b+(g-b) 3 and 1 member groups combine.Remaining 3 i.e. (g-b) member groups will can't combine with 2 member groups.Hence,they take separate taxies.
        g=-1;
    }
    if(b>=d) //More 1 member groups than 3.
    {
        f=f+d;
        g=b-d; //g=remaining 1 member groups.
    }
    h=(2*c)%4; //Empty seats in last taxi.Possible values can be 0,1,2,3.
    if(h==0)
    f=f+(c/2);
    else
    {
        f=f+((c+1)/2);
    }
    if(g!=-1)
    {
        g=g-h; //Remaining 1 member groups after combining with remaining seats in last 2 member taxi.
        f=f+g;
    }
    cout<<f;
}

Judge's log:
Test: #4, time: 0 ms., memory: 380 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER
Input
12
1 1 1 1 1 1 1 1 1 1 1 1
Output
12
Answer
3
Checker Log
wrong answer expected 3, found 12

A: g=g-h; //Remaining 1 member groups after combining with remaining seats in last 2 member taxi.
f=f+g;

This is incorrect IMO. should be something like f = f + (g+3)/4
Also, please give meaningful names to your variables to enable quick debugging.

A: In the if(g!=-1) statement you have g remaining groups of 1 person. They have to take (g+3)/4 taxis, and not g.
In other words change this line f=f+g; to f=f+(g+3)/4;.
Btw, you can use the operator += for such operations. For example, e=e+1 will become e += 1 or even better e++; (when you increase the number with exactly one).


text:
Q: Single quote paste problem MSSQL When I'm pasting text in to my query window from Office the single quotes are being changed to a backtick. I have been through all the options in both Office and SQL but I can't find the/a setting to stop this happening. Is there such an option?

A: What I believe you're talking about is Microsoft Office changing single quotes to Smart Quotes.
It's an Autoformatting setting that you can change through the Options menu in Microsoft Word.
Go to Options -> Proofing -> Autocorrect Options
There are two places to change this:

*

*Under 'Autoformat', untick Replace -> Straight Quotes with Smart Quotes

*Under 'Autoformat as you type', untick Replace as you Type -> Straight Quotes with Smart Quotes

Alternatively, stop copying SQL from Microsoft Word.
https://www.simple-talk.com/blogs/2011/11/09/how-to-stop-office-2010-changing-and-to-smart-quotes/


text:
Q: How can I host multiple Flask Apps for Multiple Domains on Digital Ocean? Using this guide I created a basic Flask App in Python. This worked well, and without nginx I could connect to it using my domain. The issue is, that this wasn't scaleable to multiple apps on one droplet. To do so, I tried this:

*

*I connected my domain via the DNS Settings in Digital Domain, and linked my domain to to route to the IP. I did this by pointing an A record from my domain to my IP, and NS records to the Digital Ocean servers. Here are the screenshots:
Domain Host
Digital Ocean DNS Host
An example setup from the DNS

*I fresh installed NGINX:
sudo aptitude install nginx

*I made /etc/nginx/sites-enabled/default this:
upstream app_server_one {
    server 127.0.0.1:7000 fail_timeout=0;
}

upstream app_server_two {
    server 127.0.0.1:8000 fail_timeout=0;
}

server {
    listen 80 default_server;
    server_name: cloud.ajnin.me

    # [snip...]

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app_server_one;
    }
}

server {
    listen 80 default_server;
    server_name: cloud2.ajnin.me

    # [snip...]

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app_server_two;
    }
}

*I started my nginx server:
sudo service nginx start

*I created my two apps (note how both run on separate ports). Both of these run separately with nginx on default:
app.py
    from flask import Flask
    app = Flask(__name__)

    @app.route('/')
    def index():
        return 'Cloud'

    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=7000, debug=True)

app2.py
    from flask import Flask
    app = Flask(__name__)

    @app.route('/')
    def index():
        return 'Cloud2'

    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=8000, debug=True)

*

*I started my two apps:
sudo (nohup) python app.py &
sudo (nohup) python app2.py &

Doing this, I got the Error 'This webpage is not available' from Chrome. Testing each app, it works by typing the server ip and port, but connecting with the domain doesn't seem to work. Would anyone be able to point me in the right direction to how I can make this work?
Thanks,
Aj.
UPDATE: This is the output for netstat -plunt:
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
    tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1085/sshd
    tcp        0      0 0.0.0.0:7000            0.0.0.0:*               LISTEN      25111/python
    tcp        0      0 0.0.0.0:8000            0.0.0.0:*               LISTEN      10265/python
    tcp6       0      0 :::22                   :::*                    LISTEN      1085/sshd

UPDATE: FIXED!
See https://gist.github.com/soheilhy/8b94347ff8336d971ad0 for more info


text:
Q: What equation would you use to solve this cyclist problem? In an 80 mile relay race, two cyclists exchange at the mid-point of the race. The winning cyclist crossed the finish line at 3 hours and 36 minutes. What was the speed of each cyclist if the losing cyclist was 5 mph slower than the winning one?
I thought that maybe finding the LCM would work but since I don't know the losing cyclist's time, that's not an option. Should I be using a velocity formula?
(The answer is 25 miles per hour for the winning one and 20 miles per hour for the losing one but I'm not sure how to get there.)

A: If the speed of the slower cyclist is $x$ kh/h
the total time taken by both the cyclist together
$$\dfrac{40}x+\dfrac{40}{x+5}=\dfrac{36}{60}+3$$


text:
Q: Detect launch of an external application I would like to know if it is possible to detect when the window of a named external application is launched and how to.
Example:
When firefox or notepad(preferably by process name. Not notepad.exe for example) is ran, minimize my application.

A: For each p as process in process.GetProcesses()
If p.processname = "notepad" then
'Do something
Else
'Do Else Something
End If
Next

A: Here two ways, that would work:
 Dim plist() As Process = Process.GetProcessesByName("notepad")
 If plist.Length > 0 Then
      ' notepad is running at least once
 Else
      ' notepad is not running
 End If

or
    Dim notepadRunning As Boolean = False
    For Each p As Process In Process.GetProcesses
        If p.ProcessName = "notepad" Then notepadRunning = True
    Next
    If notepadRunning Then
        ' notepad is running at least once
    Else
        'notepad is not running
    End If

Note: the second way is just a glorified version of the first...


text:
Q: how to loop through 3 lists and get 3 columns in Python? I have three lists list1 is "Car Models" list2 is "price per galon (mpg)" and list3 is "total price for one year". I'm able to loop through the 3 columns, but I don't know how to get 3 columns one after the other. Please someone help me. Thank you in advance!!
Heres my code:
modelName = ['Toyota', 'Nissan',  'Honda']
fuelEfficiency = [15.0, 20.0, 30.0]
for i in range(len(modelName)):
print (modelName[i])

for i in range(len(fuelEfficiency )):
print (fuelEfficiency[i])

priceGas = 2.41

totalCost1 = (10000 * priceGas)/15.0
totalCost2 = (10000 * priceGas)/20.0
totalCost3 = (10000 * priceGas)/30.0

print (totalCost1)
print (totalCost2)
print (totalCost3)

The output I want is this:
MODEL    COST(MPG) TOTALCOST
Toyota   15.0      1606.66
Nissan   20.0      1205.0
Honda    30.0      803.33

A: Try this:
modelName = ['Toyota', 'Nissan',  'Honda']
fuelEfficiency = [15.0, 20.0, 30.0]
priceGas = 2.41
totalCost1 = (10000 * priceGas)/15.0
totalCost2 = (10000 * priceGas)/20.0      # totalCost = list(map(lambda x: (10000*priceGas)/x, fuelEfficiency))
totalCost3 = (10000 * priceGas)/30.0
totalCost = [totalCost1, totalCost2, totalCost3]

print("Model", "Cost(MPG)", "TOTALCOST")
for x in range(3):
    print(modelName[x], fuelEfficiency[x], totalCost[x])

for more better format, use format

A: Because every column that you want has the same amount of items, you only need to use one for loop.  You also need to make a totalCost array for this to work.
modelName = ['Toyota', 'Nissan',  'Honda']
fuelEfficiency = [15.0, 20.0, 30.0]

priceGas = 2.41

totalCost = [0, 0, 0] # Filler values
totalCost[0] = (10000 * priceGas)/15.0
totalCost[1] = (10000 * priceGas)/20.0
totalCost[2] = (10000 * priceGas)/30.0

for i in range(len(modelName)):
    print modelName[i], fuelEfficiency[i], totalCost[i]

This should work

A: I think below solution is more pythonic
modelName = ['Toyota', 'Nissan',  'Honda']
fuelEfficiency = [15.0, 20.0, 30.0]
priceGas = 2.41

totalcost = map(lambda x:(10000 * priceGas)/x,fuelEfficiency)

for a,b,c in zip(modelName,fuelEfficiency,totalcost ):
    print a,b ,c

A: Since you are talking about looping parallel, I would highly recommend to use zip. See the below example!
modelName = ['Toyota', 'Nissan',  'Honda']
fuelEfficiency = [15.0, 20.0, 30.0]
priceGas = 2.41
totalCost1 = (10000 * priceGas)/15.0
totalCost2 = (10000 * priceGas)/20.0
totalCost3 = (10000 * priceGas)/30.0
totalcost = [totalCost1, totalCost2, totalCost3]

print ("Model", "Cost(MPG)", "TOTALCOST")
for i in zip(modelName, fuelEfficiency, totalcost):
    print (" ".join(map(str, list(i))))

OUTPUT : I am running Python3.4
Model Cost(MPG) TOTALCOST
Toyota 15.0 1606.6666666666667
Nissan 20.0 1205.0
Honda 30.0 803.3333333333334

A: You can use pandas for working with data in a table-like (aka DataFrame) structure.
import pandas as pd

modelName = ['Toyota', 'Nissan',  'Honda']
fuelEfficiency = [15.0, 20.0, 30.0]
priceGas = 2.41

df = pd.DataFrame({'MODEL': modelName, 'COST(MPG)': fuelEfficiency})
df['TOTALCOST'] = (10000 * priceGas) / df['COST(MPG)']

print df[['MODEL', 'COST(MPG)', 'TOTALCOST']].to_string(index=False)

This has the advantage that if you end up wanting to do more advanced data manipulation or formatting, there are a lot of convenient options in the pandas.DataFrame data structure.

A: You can Try this.
modelName = ['Toyota', 'Nissan',  'Honda']
fuelEfficiency = [15.0, 20.0, 30.0]
for i in range(len(modelName)):
    print (modelName[i])

for i in range(len(fuelEfficiency )):
    print (fuelEfficiency[i])

priceGas = 2.41

totalCost=[0]*len(fuelEfficiency)

for i in range(len(fuelEfficiency)):
    totalCost[i]=(10000 * priceGas)/fuelEfficiency[i]

print "Model     Cost      Totalcost"
for i in range(len(fuelEfficiency)):
    print modelName[i],fuelEfficiency[i],totalCost[i]

Arrange the output according to your need.


text:
Q: Unable to download .jpg image and set into imageview using asynctask
I have a problem. I can't seem to download a .jpg image from a URL source and then set it into a imageview which is inside a listview. It gives me the error "NullPointerException". I am currently using the ImageDownloader class from here.
This are the lines of code where i download the image files:
onCreate()...

        for (int i = 0; i < listData.size(); i++) {
            imageISBN = listData.get(i).get("coverImage");
            String isbnURL = "http://lib.syndetics.com/index.aspx?isbn=" + imageISBN +
                                   "/SC.GIF&client=tpoly&type=xw12";
            ImageView iv = (ImageView) findViewById(R.id.cover_image);
            imageDownloader.download(isbnURL,iv);
        }

I'm thinking that it maybe due to my setContentView(R.layout.list) that's producing the error since it is just a listview and the imageview link is in another xml file.
Below is the LogCat:

05-11 09:26:58.063: ERROR/AndroidRuntime(305): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.TPLibrary/com.TPLibrary.Search.SearchResults}: java.lang.NullPointerException
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at android.os.Handler.dispatchMessage(Handler.java:99)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at android.os.Looper.loop(Looper.java:123)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at android.app.ActivityThread.main(ActivityThread.java:4627)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at java.lang.reflect.Method.invokeNative(Native Method)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at java.lang.reflect.Method.invoke(Method.java:521)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at dalvik.system.NativeStart.main(Native Method)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305): Caused by: java.lang.NullPointerException
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at com.TPLibrary.Search.ImageDownloader.forceDownload(ImageDownloader.java:80)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at com.TPLibrary.Search.ImageDownloader.download(ImageDownloader.java:49)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at com.TPLibrary.Search.SearchResults.onCreate(SearchResults.java:185)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
  05-11 09:26:58.063: ERROR/AndroidRuntime(305):     ... 11 more

So guys, any ideas? Could it be that i'm using the ImageDownloader class wrongly?

A: In ImageDownloader class, the mode is assigned to NO_ASYNC_TASK:
public enum Mode { NO_ASYNC_TASK, NO_DOWNLOADED_DRAWABLE, CORRECT }
private Mode mode = Mode.NO_ASYNC_TASK;

Your intention was to download the image. So try setting the mode variable to NO_DOWNLOADED_DRAWABLE.


text:
Q: How to Put Categorized Parsed JSON Items inside an Array in Swift 4 I have successfully parsed JSON data individually using Decodable.
What I need to do next is to put the same items into an Array. For instance, here's what I did to get the "dates" items:
struct Item : Decodable {
let date: String }

and retrieving it in a JSON parser function using:
let items = try JSONDecoder().decode([Item].self, from: data!)

for info in items {
        print(info.date) }

How do I put the said dates inside an Array?
(Note: There are many item categories inside the JSON data including: name, date, price, etc., I just need to get the "dates" item.)
What I tried so far is this:
var itemDate = [String]() // declare an Array

// Inside the JSON parser function:
self.itemDate.append(info.date)
let dateArrays = [self.itemDate]
print(dateArrays)

The result, however, shows up like this:

A: With let dateArrays = [self.itemDate], you are declaring an array inside an array (hence the print call is [[]]. You can just simply use the variable itemDate directly (it is already an array of your dates item) or if you like, use
let dateArrays = self.itemDate

Without the square brackets, it is just an array, not an array of arrays.

A: The map function is one way you could go.
From your items array, you could just map the Structs to an array containing only dates like so:
let justTheDatesArray = items.map{$0.date}

Alternatively, you could do it when you decode:
let items = try JSONDecoder().decode([Item].self, from: data!).map{$0.date}

You can read more about map, filter, and reduce here
Bonus:
If you want to pull actual Date objects out, you could use DateFormatter, like so:
let formatter = DateFormatter()
formatter.dateFormat = "mm/DD/yyyy"
let dateObjectArray = justTheDatesArray.flatMap{formatter.date(from: $0)}


text:
Q: python pywinauto does not recognize button on displayed by app I'm running a 4DD Database client using python pywinauto.
The image of the screen is attached.
However pywinauto is not recognizing buttons "Cancel" "OK".
pywinauto is not recognizing the tabs "Recent" "Available" "Custom".
I use this code:
from pywinauto import application
app=application.Application(backend="win32")
app.start("C:\Genie\Client\Genie Client.exe")
dlg=app['Connection to 4D Server']
dlg.set_focus()
<hwndwrapper.DialogWrapper - 'Connection to 4D Server', _ASI_THREED_, 6297110>
dlg.print_control_identifiers()
Control Identifiers:

_ASI_THREED_ - 'Connection to 4D Server'    (L684, T207, R1220, B696)
['Connection to 4D Server', 'Connection to 4D Server_ASI_THREED_', '_ASI_THREED_']
child_window(title="Connection to 4D Server", class_name="_ASI_THREED_")
|
| ScrollBar - ''    (L1195, T671, R1212, B688)
| ['Connection to 4D ServerScrollBar', 'ScrollBar']
| child_window(class_name="ScrollBar")

Can anyone tell me how to get pywinauto to discover the buttons and tabs on the screen?


text:
Q: Log in programmatically and redirection This is code which is responsible for log in user and redirect to specific place. But there is a problem, after redirection im not logged in, firewall stops me and redirects me to the login page. When i press F5 everything is ok, i'm logged in.
$response = new RedirectResponse($this->generateUrl('some_route'));

/**
 * @var $loginManager LoginManager
 */
$loginManager = $this->get('fos_user.security.login_manager');
$loginManager->loginUser('main', $client, $response);

/**
 * @var $eventDispatcher EventDispatcher
 */
$userEvent = new UserEvent($user, $request);
$eventDispatcher = $this->get('event_dispatcher');
$eventDispatcher->dispatch(FOSUserEvents::SECURITY_IMPLICIT_LOGIN, $userEvent);

return $response;

When i use forwarding instead of redirect everything is ok.
$response = $this->forward('AcmeExampleBundle:Controller:index');

Any suggestions?


text:
Q: Why is $Set$ not equivalent to $Set^{op}$? I understand this question already has an answer on here, but I do not understand how the answer justifies that $Set$ not equivalent to $Set^{op}$.
The explanation is that if they were equivalent and if the terminal object in $Set$ has an equivalence invariant property, then the initial object has the dual property.
The terminal objects are obviously singleton sets, and the initial object is the empty set. I can see that every map into the empty set is an isomorphism, and that there exists maps $\{a\}\to X$ which are not invertible, but how does this relate to the non-equivalence of $Set$ and $Set^{op}$?
If someone could elaborate further I would greatly appreciate it.
Thanks in advance.

A: Statement 1 : Let $C\simeq D$ be two categories which are equivalent thanks to a functor $F : C \to D$. If $X$ is an initial object in $C$ then $F(X)$ is an initial object in $D$.
Statement 2 : If $X$ is an initial object in $C$ (for some category $C$), it is a terminal object in $C^{op}.$
Statement 3 : If $F : C \to D$ is an equivalence between categories with products, one has $F(X \times Y) \simeq F(X) \times F(Y)$ for all $X,Y$.
Now suppose to have a functor $F : Set \to Set^{op}$ which gives an equivalence between them. Then, because $\emptyset$ is initial in $Set^{op}$, we get that $F(\emptyset)$ is initial in $Set^{op}$. (Statement 1). After that, we get that $F(\emptyset)$ is terminal in $Set$. (Statement 2). Hence, there is $a$ such that. $F(\emptyset) = \{a\} .$ Now apply statement 3 $$\{a\} = F(\emptyset) = F(\emptyset \times \emptyset) \simeq F(\emptyset) \times F(\emptyset) = \{a\} \bigsqcup \{a\}.$$ So you have established a bijection between $\{a\}$ and $\{a\} \bigsqcup \{a\},$ which leads to a contradiction.

A: Consider the following property of a category $\mathcal C$:

If $f: A\to B$ is a morphism and $B$ is an initial object, then $f$ is an isomorphism.

Since this property is stated only in terms of existence properties of certain morphisms (and does not depend on uniqueness of objects even if we unfold the definition of an initial object), if we have two equivalent categories they will either both have this property or both not have this property.
The explanation you reproduce consists of the observation that $\mathbf{Set}$ has this property (because the only morphism into an initial object is the empty function $\varnothing\to\varnothing$, which is an isomorphism), whereas $\mathbf{Set}^{\rm op}$ does not (there are functions with singleton domains that are not bijections, and such a function is in $\mathbf{Set}^{\rm op}$ a non-iso morphism into an initial object).

A: The opposite to Set is the category of Complete Atomic Boolean Algebras, see

https://ncatlab.org/nlab/show/Set#OppositeCategory


text:
Q: How to divide or multiply between elements of a tuple in python? I have the next tuple as result of a sql query:
tuple1 = [(245, 57)]
tuple2 = [(11249, 5728)]
tuple3 = [(435, 99)]

and I need to divide the 57 between 245 and the same with the rest.
I can access individual elements with:
[x[0] for x in rows]

but when I do:
a = [x[1] for x in rows] / [x[0] for x in rows]

I get TypeError: unsupported operand type(s) for /: 'list' and 'list'

A: a = [x[1] for x in rows] / [x[0] for x in rows]

will attempt to divide a list by a list.
What you meant to do is:
a = [x[1] / x[0] for x in rows]

which is divide elements per item in list.

A: Using multiple names can increase readability:
a = [y / x for x, y in rows]

A: Another option would be
list(map(lambda x: x[1]/x[0] if x[0] else 0,rows))


text:
Q: Powershell - Item Level Permission by Content Type Here is the scenario. I only need to run this once as business team just decided their contents are confidential. User Group is "Marketing", will use OOTB "Contribute" and all of marketing items are using "2011 Marketing" content type. The library name is "2011Sales". I need to take out current permissions (also remove inheritance) and only add "Marketing" group with "Contribute" right.
Updated Working Code:
$webUrl = "http://inside.national.com/Sales"
$web = Get-SPWeb $webUrl
$list = $web.Lists["2011Sales"]
$ct = "2011 Marketing"
$spgroup = "Custom SP Group"
$rd="Contribute"

foreach ($item in $list.items) {
    If ($item.ContentType.Name -eq $ct)
     {
        $item.ResetRoleInheritance() # Not sure if this line is needed
        $item.BreakRoleInheritance($false) # I tried $true but did not work, so leave it at $false
        $item.SystemUpdate() # update without changing the modification date

        $group = $web.AllUsers[$spgroup]
        $roledef = $web.RoleDefinitions[$rd]
        $roleass = New-Object Microsoft.SharePoint.SPRoleAssignment($web.SiteGroups[$spgroup])
        $roleass.RoleDefinitionBindings.Add($roledef)
        $item.RoleAssignments.Add($roleass)
        $item.SystemUpdate() # update without changing the modified date
        Write-Host $item.Name " permission applied"
     }
}
$web.dispose()

A: After breaking the inheritance of an item (item,list,web) you have to call update() on that object to make sure the settings are saved to the database. Once these are saved you can start adding/changing the permissions for that item.
BreakRoleInheritance(false) will not copy the permissions of the parent to the new permissionset, supplying true will copy the permissions.
Updates (see also Vedran Rasols answer)

*

*Using foreach(item in list.items) is not recommended, use an SPQuery to select the items and properties you really want, otherwise you will fetch all data from the DB. See also this MSDN Best Practices Article!

*In theory you shouldn't have to call update(), but in some strange way in helped solving this issue.

bonus: Note that when breaking inheritance on lists the AllowUnsafeUpdate property of the parent web reverts to false, which can be annoying.

A: You need to take advantage of SPQuery class. Using CAML query is much, much, much more faster then doing foreach.
Here is script you 'really' want:
$webUrl = "http://inside.national.com/Sales"
$listName = "2011Sales"
$ctname = "2011Sales"
$groupname = "Custom SP Group"

# Get web and list
$web = Get-SPWeb -Identity $webUrl
$list = $web.Lists[$listName]

# Build CAML query
$caml="<Where><Eq><FieldRef Name='ContentType'/><Value Type='Text'>{0}</Value></Eq></Where>" -f $ctname
$query = New-Object Microsoft.SharePoint.SPQuery
$query.Query = $caml
# Set scope to Recursive to include all items from folders and Document Sets
$query.ViewAttributes = "Scope='Recursive'"
# Get our data (only items with proper ct name)
$items = $list.GetItems($query)

# Set Role Assignment
$spGroup = $web.SiteGroups[$groupname]
$spRoleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($spGroup)
$sproledefinition = $web.RoleDefinitions["Contribute"]
$sproleassignment.RoleDefinitionBindings.Add($sproledefinition)

foreach ($item in $items) {
    # This is the fastest way of deleting all permissions
    # First you restore inheritance
    # And then you break it
    $item.ResetRoleInheritance()
    $item.BreakRoleInheritance($false)

    # Add new permission
    $item.RoleAssignments.Add($spRoleAssignment)
}

This script will update all items of desired Content Type (including items/files in folders and files in Document Sets). However it will not change permissions of parent Folders or Document Sets.
I have tested this on my dev machine. Feel free to ask additional questions.

A: Here is the working code in case someone needs it.
$webUrl = "http://inside.national.com/Sales"
$web = Get-SPWeb $webUrl
$list = $web.Lists["2011Sales"]
$ct = "2011 Marketing"
$spgroup = "Custom SP Group"
$rd="Contribute"

foreach ($item in $list.items) {
    If ($item.ContentType.Name -eq $ct)
     {
        $item.ResetRoleInheritance() # Not sure if this line is needed
        $item.BreakRoleInheritance($false) # I tried $true but did not work, so leave it at $false
        $item.SystemUpdate() # Very Important

        $group = $web.AllUsers[$spgroup]
        $roledef = $web.RoleDefinitions[$rd]
        $roleass = New-Object Microsoft.SharePoint.SPRoleAssignment($web.SiteGroups[$spgroup])
        $roleass.RoleDefinitionBindings.Add($roledef)
        $item.RoleAssignments.Add($roleass)
        $item.SystemUpdate() #Update item without changing the updated date
        Write-Host $item.Name " permission applied"
     }
}
$web.dispose()


text:
Q: IBM RTC - Precondition Plug-in for prohibit system out println I have got requirement to create plug-in that can be attached as pre-condition in 'deliver client'.
When I deliver my java code to stream, if there is any system.out.println call, deliver should fail.
Suppose, if I create the plug-in, how to attach that plugin in pre-condition UI.
Could you please guide me what needs to be done?

A: To put in place your precondition, you can follow "Team process preconditions for Rational Team Concert source control".
You can see example of existing preconditions in "Source control process recipes for Rational Team Concert", but in your case, this is a custom one.
See "Rational Team Concert - Creating Custom Operation Advisors": you will be able to create a new plugin.

You might need to work with the RTC admin in order to install that plugin on the RTC server.


text:
Q: How to remove a TFS Workspace Mapping? I had a project in tfs within a team project then we moved the project to a different location in another team project.
I had configured Jenkins to connect to the team project and build my solution but when I changed the settings to connect to the new tfs team project, it gives me the below error:
[workspace] $ "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\tf.exe" workspace -new Hudson-ProjectName1-Build-MASTER;domain1\username1 -noprompt -server:http://domain-eg.net:8080/tfs/newteamproject ********
The path D:\jenkins\jobs\ProjectName1-Build\workspace is already mapped in workspace Hudson-ProjectName1-Build-MASTER [http://domain-eg.net:8080/tfs/oldteamproject].

So the above shows that there is an existing workspace so I ran the below command to remove it
tf workspace -delete Hudson-ProjectName1-Build-MASTER;domain1\username1 -noprompt -server:http://domain-eg.net:8080/tfs/oldteamproject

and it prompted that the workspace has been removed but I'm still getting the same error.
I also checked whether the mapping has been removed or not by running the below command:
tf workspace -server:http://domain-eg.net:8080/tfs/oldteamproject Hudson-ProjectName1-Build-MASTER

but it says the workspace doesn't exist as expected.
So, I thought it might be caching it somewhere and ran the below command:
tf workspaces /remove:* /collection:http://domain-eg.net:8080/tfs/oldteamproject

and it said "No workspace in the cache matches * from server http://domain-eg.net:8080/tfs/oldteamproject"
so I'd guess it's not even cached.
So what's causing the error and how to resolve it?

A: Please follow the below steps:
Ctrl + Run

Copy and Past
%LocalAppData%\Microsoft\Team Foundation

You will get different version of TFS e.g

Click on each folder and you will get

Now Delete all data in these folder.
Reopen the Visual studio.
Thanks.

A: All of the answers here seem to be partial answers that don't work in all cases. I think this answer will work in all cases, assuming you have proper permissions.

*

*Open up the Developer Command Prompt. In my case, I've tested this with the Developer Command Prompt for VS 2019.

*Type this command: tf workspaces
Note that the results can list a couple tables with identical structure. If you only see one table, then some of the assumptions in the other answers can work for you. However, if you see two or more tables, then that Collection string is important! For our examples, we're going to assume you have two Collections (two is no different than four other than one is more tedious than the other to go through it):
https://dev.azure.com/foo and https://bar.visualstudio.com/
With luck, you will know which one of these two you want to work with. However, if you need to cycle through them all, then you'll just have to do that one collection at a time. Each "Collection" here is the same as an "Organization" in Azure DevOps (I think).
If you don't use this Collection detail, then you might see an error message:

Unable to determine the source control server.

*Next, type this command for the collection you want to use:
tf workspaces /computer:* /owner:* /collection:https://dev.azure.com/foo
This will give you a much more complete picture of what you're dealing with. This gets especially nasty if you have had multiple MSAs and Org accounts hitting this repo from the same computer. In fact, you might have multiple seemingly-identical entries. If you try to delete them based on what you currently know, it may not work. But we can get more information.

*Next, we're going to run the same command but append /format:xml to the end of it:
tf workspaces /computer:* /owner:* /collection:https://dev.azure.com/foo /format:xml
This now gives you a bunch of XML with some additional properties. The ones that we likely care about the most are the Owner Aliases. This is the missing information you need to now go through and delete these workspaces. Without this additional information, it's easy to hit a wall and be stuck with an error message:

Specify one workspace.

*Now we have all of the info we need. Given the additional OwernAliases entries, select the unique entry (or repeat if more than one) that you wish to delete and use this following command (a couple examples are listed):

*

*tf workspace /delete /collection:https://dev.azure.com/foo
"MyWorkspaceName;Windows Live ID\John.Doe@hotmail.com"

*tf workspace /delete /collection:https://dev.azure.com/foo
"MyWorkspaceName;John Doe"

*tf workspace
/delete /collection https://dev.azure.com/foo
"MyWorkspaceName;2C3E8474-A39C-4785-8794-DC72F09981E6\John.Doe@Example.com"
The GUID identifies an AAD directory and the quotes are there to handle any spaces that might be in an alias. The "MyWorkspaceName" comes from your previous queries listing out the workspaces.

Without this very thorough approach, it's possible that all of the other answers in this question will fail for you. While some of those efforts will clear out local workspaces, they will not clear out server workspaces, which you can still conflict with. Additionally, if you have previously used a different account things can get hairy, like if you switched from an MSA to an AAD account. And things get REALLY hairy if you have an MSA account and multiple AAD accounts all with the same email address that you have used from the same workstation. And then it gets super crazy hairy if multiple of those all used the default name for the workspace: your computer's hostname. In my case, I had four workspaces all with the same Workspace name, Owner name, and Computer name (i.e. the first query without the XML formatting had 4 identical records!).

I do not know if there's a more graphcial way to manage these than this. I have looked and not yet found a better way than this.

A: Update 2019-01-23
If you're repeatedly getting the following error The workspace wkspaceEg does not exist… even after employing the correct username (wkspcOwnerDomain\wkspcOwnerUsername) in the tf workspace command, e.g.,
tf workspace "wkspaceEg;wkspcOwnerDomain\wkspcOwnerUsername" /collection:http://tfs.example.com:8080/tfs/collectionEg /login:TFSUsername,TFSPassword
then the tf workfold command may help fix it. See this question.
If even that doesn't work and you're unable/unwilling to use TFS Sidekicks, proceed to the risky last-ditch option below.

I'm using TFS 2012. I tried everything that was suggested online: deleted cache folder, used the workspaces dropdown, tf workspaces /remove:*, cleared credentials from Control Panel, IE, etc.
Nothing worked, I believe my workspace got corrupted somehow. Finally, I went to the TFS database and ran the following queries. That worked! Of course be very careful when messing with the database, take backups, etc.
The database is called Tfs_<<your_TFS_collection_name>>. Ignore the Tfs_Configuration MSSQL database. I'm not sure but if you don't have a Tfs_<<your_TFS_collection_name>> database, settings might be in the Tfs_DefaultCollection database. Mapping is stored in tbl_WorkingFolder.LocalItem.
/*Find correct workspace*/
SELECT WorkspaceId, *
FROM tbl_Workspace
ORDER BY WorkspaceName

/*View the existing mapping*/
SELECT LocalItem, *
FROM tbl_WorkingFolder
WHERE WorkspaceId = <<WorkspaceId from above>>

/*Update mapping*/
UPDATE tbl_WorkingFolder
SET LocalItem = 'D:\Legacy.00\TFS\Source\Workspaces\teamProjEg' WHERE
/*LocalItem = NULL might work too but I haven't tried it*/
WorkspaceId = <<WorkspaceId from above>>

A: Team Explorer > Source Control Explorer >

A: I managed to remove the mapping using the /newowner command as suggested here:
How can I regain access to my Team Foundation Server Workspace?
The command opened an Edit Workspace windows where I removed the mapping. Afterwards I deleted the workspace I didn't need.

A: Follow these steps to remove mapping from TFS:

*

*Open team explorer

*Click Source Control

*Right click on you project

*Click on Remove Mapping

A: From VS:

*

*Open Team Explorer

*Click Source Control Explorer

*In the nav bar of the tool window there is a drop down labeled "Workspaces".

*Extend it and click on the "Workspaces..." option (yeah, a bit un-intuitive)

*The "Manage Workspaces" window comes up. Click edit and you can add / remove / edit your workspace

From VS on a different machine
You don't need VS to be on the same machine as the enlistment as you can edit remote enlistments! In the dialog that comes up when you press the "Workspaces..." item there is a check box stating "Show Remote Workspaces" - just tick that and you'll get a list of all your enlistments:

From the command line
Call "tf workspace" from a developer command prompt. It will bring up the "Manage Workspaces" directly!

A: None of the answers here removed my workspaces.  But here is one solution that may work for you.

*

*Open up a Visual Studio command prompt

*Close Visual Studio first or the delete command may not delete the workspace

*List the workspace commands -> tf /? to find the commands available to you from the version of TFS.

*List the workspaces -> tf workspaces

*Delete the workspace -> tf workspace YourWorkspace /delete

A: You don't have to delete the entire Cache folder. you lose all settings / preferences
The workspace mappings are stored in a file called:
VersionControl.config under the users local settings/application data directory.
located here in windows 7:

%LocalAppData%\Microsoft\Team Foundation\x.0\Cache\Volatile
where x= 3.0,4.0, 5.0,6.0 etc.

Inside this you will find guid named folders , open each of them, manually editing the forementioned file, to remove the workspace mapping(directory path will be present in mappedpaths attribute) from that local folder to the TFS server (which is no longer in usage).

A: File -> Source Control -> Advanced -> Workspaces -> Choose the workspace in Manage Workspaces and click "Edit" Then you can change the local folder.

A: I ran into the same problem, and was able to fix it by manually deleting all the files in the TFS cache, located here:
%LocalAppData%\Microsoft\Team Foundation\3.0\Cache

or 4.0, 5.0, etc.

A: The error is genuine. You might have created workspace with same name on different machine. Now you may have changed machine having different machine name.
So here is work-around that will definitely work.Following is work-around.

*

*Go to "Team-Explorer"

*Go to "Source-Control"

*Go to Workspace drop-down

*Click on "Workspaces..."

*A pop-up window will appear

*Click on "Show remote workspaces"

*Now delete the workspace which is conflicting and you can proceed your work.

A: Finally deleted ALL workspaces and started from scratch. Fixed.

A: I was prompted to login to our TFS server via Visual Studio, so I used my SU account which is typically required for server access. This led to some issues, and I ended up mapping to a different folder, not realizing I had just duplicated all my stuff. At some point, Visual Studio reverted back to my regular user, I "lost" pending changes, and noticed that new pending changes were placed by in my old mapping.
When I would try to remap to the new location (that the SU account was linked to) in an attempt to recover my pending changes, it would tell me it was already mapped to the SU, and I couldn't do that, but had no way of removing the map! Show remote workspaces, removing all workspaces via command line, etc revealed nothing. I then thought "what if it's actually linked to the SU user account on my computer, not the domain." I logged in as my SU locally, and sure enough, there was a workspace all setup for that user. I  removed the mapping, and was able to go back to my regular user and remap without issue.
Moral of the story, perhaps another user is logged in on the same machine, which isn't visible from the currently logged in user, thus you cannot remove or even see the mappings.

A: If the mentioned clues are not helping you then download Team Foundation Sidekick and using that you can delete the workspaces.

A: Following are the steps to remove mapping of a project from TFS:
(1) Click on View Button.
(2) Open Team Explorer
(3) Click on Source Control
(4) Right click on your project/Directory
(5) Click on Remove Mapping
(6) Finally Delete the Project form  local directory.

A: You can also remove a tfs mapping by simply editing your .sln file and removing the GlobalSection element for the tfs binding.

A: Thanks for your help!
Find problem workspace
SELECT * FROM tbl_Workspace
WHERE WorkspaceName like '%xxxxx%'
Find desired workspace
SELECT * FROM tbl_Workspace
WHERE WorkspaceName like '%zzzzz%'
Select Edit Top 200 tbl_WorkingFolder then Find the problem mapping
SELECT * FROM tbl_WorkingFolder WHERE WorkspaceId = Problem WorkspaceId from above
Change the WorkspaceId to the desired WorkspaceId
Finally goto Project Explorer and select Remove Mapping on the project
Modify VB6 MSSCCPRJ.SCC to match the desired WorkSpace

A: First download and install Team Explorer plugin in your system and then go to the Source Control Explorer. In the navigation pane find the Workspace field and click on Workspaces option.
After clicking on Workspaces option, you will see all the workspaces that are mapped. Click on the remove button and the remove the mapping for required workspaces.

A: Run tf workspaces to view current workspace mappings. Output looks like:

Then run tf workspace /delete "{workspace};{user}
Using output above, to delete workspace bi:
tf workspace /delete bi;James Wierzba

A: If mapping is proper then you can undo/checkin your changes, if you really want to change folder name.
Alternatively if you want to remove mapping then in Visual Studio go to
File-> Source Control-> Advanced-> Workspaces-> Edit
Now you can click on appropriate path and remove mapping.


text:
Q: Create array of dates based on inputs Given these two YYYYMM strings:
$start = "201301";
$end = "201303";

I would like to derive an array like this:
array (
  0 =>
  array (
    0 => '20130101',
    1 => '20130131',
  ),
  1 =>
  array (
    0 => '20130201',
    1 => '20130228',
  ),
  2 =>
  array (
    0 => '20130301',
    1 => '20130331',
  ),
)

I've tried a few things with date() and mktime() but nothing decent so far.
What's a nice way to do this?

A: With DateTime:
$start = "201301";
$end = "201303";

$dateNiceStart = substr($start,0,4).'-'.substr($start,4).'-01';
$dateNiceEnd = substr($end,0,4).'-'.substr($end,4).'-';

// Days count in month
$endDays = date('t',strtotime($dateNiceEnd.'01'));
$dateNiceEnd .= $endDays;

$startObj = new DateTime($dateNiceStart);
$endObj = new DateTime($dateNiceEnd);

$temp = clone $startObj;

$arr = array();
// Adding first month
//Using first day and last day
$temp->modify( 'first day of this month' );
$start = $temp->format('Ymd');
$temp->modify( 'last day of this month' );
$end = $temp->format('Ymd');

$arr[] = array($start, $end);
do{
    // for next month
    $temp->modify( 'first day of next month' );
    $start = $temp->format('Ymd');
    $temp->modify( 'last day of this month' );
    $end = $temp->format('Ymd');

    $arr[] = array($start, $end);

    // This line edited to work properly in different years, thanks to @Adidi
    $interval = $endObj->diff($temp)->format('%y%m%d');
}
while ($interval!=0);

print_R($arr);

Main key is first/last day of next/this month usage.

A: http://www.php.net/manual/en/function.date.php
Which you need is format string "t":

t Number of days in the given month    28 through 31

A: Here is easy way to loop it..
$start  = "201301";
$end    = "201303";

$start_time = strtotime(implode('-',str_split($start,4)));
$end_time = strtotime(implode('-',str_split($end,4)));

$array = array();
if($start_time <= $end_time){
    while($start_time <= $end_time){
        $month = date('F', $start_time);
        $array[] = array(
            date('Ymd', strtotime("first day of {$month}", $start_time)),
            date('Ymd', strtotime("last day of {$month}", $start_time)));
        $start_time = strtotime("next month", $start_time);
    }
}

A: Something like this?
for($i=1;$i<=12;$i++) {
    $first = '2013'.($i<10 ? '0'.$i : $i).'01';
    $last = date('Ymt', strtotime($first));
    $myArray[] = array($first, $last);
}

Not tested.

A: You can iterate over the months like so:
function date_range($start, $end)
{
    $start = strtotime("$start01");
    $end = strtotime("$end01");

    $res = array();

    while ($start < $end) {
        $next = strtotime("+1 month -1 day", $start);
        $res[] = array(
            date('Ymd', $start),
            date('Ymd', $next),
        );
        $start = $next;
    }

    return $res;
}

A: Working solution:
$start = "201301";
$end = "201309";

function getDateTimeByString($str_date){
    preg_match('/^([\d]{4})([\d]{2})$/',$str_date,$matches);
    $dt = null;
    if($matches){
        $dt = new DateTime();
        $dt->setDate($matches[1],$matches[2],1);
    }
    return $dt;
}

$start_dt = getDateTimeByString($start);
$end_dt = getDateTimeByString($end);

$output = array();

while($start_dt->getTimestamp() <= $end_dt->getTimestamp()){
    $arr = array();
    $arr[] = $start_dt->format('Ymd');
    $start_dt->modify('last day of this month');
    $arr[] = $start_dt->format('Ymd');

    $output[] = $arr;

    $start_dt->modify('first day of next month');
}

print_r($output);

prints:
Array
(
    [0] => Array
        (
            [0] => 20130101
            [1] => 20130131
        )

    [1] => Array
        (
            [0] => 20130201
            [1] => 20130228
        )

    [2] => Array
        (
            [0] => 20130301
            [1] => 20130331
        )

    [3] => Array
        (
            [0] => 20130401
            [1] => 20130430
        )

    [4] => Array
        (
            [0] => 20130501
            [1] => 20130531
        )

    [5] => Array
        (
            [0] => 20130601
            [1] => 20130630
        )

    [6] => Array
        (
            [0] => 20130701
            [1] => 20130731
        )

    [7] => Array
        (
            [0] => 20130801
            [1] => 20130831
        )

    [8] => Array
        (
            [0] => 20130901
            [1] => 20130930
        )

)

A: You can try with these functions :
function get_date_range ($start, $end) {

    $dates = array();

    $start = strtotime($start .'01');
    $end    = strtotime($end .'01');

    while ($start <= $end) {
        $dates [] = array(date('Ym01', $start), date('Ymt', $start));
        $start  = strtotime(add_month(date('Y-m-01', $start), 1));
    }

    return $dates;
}

function add_month($date_value, $months, $format = 'm/d/Y') {
    $date = new DateTime($date_value);
    $start_day = $date->format('j');

    $date->modify("+{$months} month");
    $end_day = $date->format('j');

    if ($start_day != $end_day)
        $date->modify('last day of last month');

    return $date->format($format);
}

$start = "201301";
$end    = "201303";

$dates = get_date_range($start, $end);

print_r($dates);

Here the add_month function will help you to avoid problems with the date when adding one month to January 31st.
If you use strtotime it will go to March when adding 1 month to January 31st..
Output will be :
Array
(
    [0] => Array
        (
            [0] => 2013-01-01
            [1] => 2013-01-31
        )

    [1] => Array
        (
            [0] => 2013-02-01
            [1] => 2013-02-28
        )

    [2] => Array
        (
            [0] => 2013-03-01
            [1] => 2013-03-31
        )

)

Hope this helps you :)


text:
Q: Retrofit2 Expected BEGIN_ARRAY but was BEGIN_OBJECT Reddit JSON response Before I start, I want to apologize for repeating the question but I just want to get better understanding of how this works because I've looked around but wasn't able to find an answer related to my JSON response.
This is the JSON response I am trying to read with Retrofit2.
(https://www.reddit.com/r/popular.json)
{
    kind: "Listing",
    data: {
        modhash: "9nsu2iqwupcf7d47e57c6f70795c9fde52e5566bf8b7731884",
        children: [
            {
                kind: "t3",
                data: {}
            },
            {
                kind: "t3",
                data: {}
            },
            {
                kind: "t3",
                data: {}
            },

            And so on...

I am new to programming and I've worked in the past with Retrofit for couple of my small projects. In those projects I was easily able to download the data as I always encountered with Array at start but in this case, it's Object.
I've just updated the classes with POJO to create the JSON Response structure yet it's still not returning anything after going into debug mode. If you need any further information, please let me know. Really appreciate your help guys
public void getPopularPost() {
    popularPosts = new ArrayList<>();

    Retrofit retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("https://www.reddit.com/")
            .build();

    FromAPI fromAPI = retrofit.create(FromAPI.class);
    final Call<Rootobject> call = fromAPI.getPopularPosts();
    call.enqueue(new Callback<Rootobject>() {
        @Override
        public void onResponse(Call<Rootobject> call, Response<Rootobject> response) {
            response.body();
        }

        @Override
        public void onFailure(Call<Rootobject> call, Throwable t) {

        }
    });
}

===========================================================================
public interface FromAPI {

    @GET("r/popular.json")
    Call<Rootobject> getPopularPosts();

}

===========================================================================
public class Rootobject {
    private String kind;
    private Data data;
}

public class Data {
    private String modhash;
    private ArrayList<Child> children;
//    private String after;
//    private Object before;
}

public class Child {
    private String kind;
    private Data2 data;
}

public class Data2 {
    private String domain;
    private String author;
    private String title;
    private int num_comments;
    private int ups;
    private String url;
}

A: Goto this site Json To Java Pojo paste the entire json there,it will show you all the pojo classes that need to be created.You are probably missing a few or have created some incorrectly.


text:
Q: Install Plone egg as a Python module on Windows I have a Plone site (Plone version 3.1.2) that I need to install a product called GrufSpaces on - (http://plone.org/products/grufspaces). However, it is a production site and so I can't easily take it down to upgrade Plone to 3.2+ in order to use buildout; using buildout would allow me to easily add Grufspaces (collective.groupspace.roles etc) as a Product.
I have downloaded the egg files separately (roles, workflow, mail, content) and placed them in a directory structure like so:

*

*collective/

*

*__init__.py

*groupspace/

*

*__init__.py

*content/...

*roles/...

*workflow/…

*mail/...

What I thought I could do is add this "collective" folder to [plone directory]/Zope/lib/python as a Python module. The idea being once its added I can restart Plone/Zope and it will automatically pick it up and make it available within Plone as a Python Module. Unfortunately it has not worked as of yet.
If I am going about this the wrong way I welcome any suggestion to try this a different way.

A: Did you check GrufSpaces' INSTALL.TXT? From there:

Unpack it into your Zope Products Folder

For Plone, the easiest way is probably to unpack it the top level products folder.
See also http://plone.org/documentation/kb/third-party-products/installing, section "Installing Zope 2-style Products Without Buildout".

A: If you are trying to install GrufSpaces 2.0 then you should consider upgrading to Plone 3.3 (see the install requirements)
Placing the collective.* packages to [plone directory]/Zope/lib/python should work. But these packages are not compatible with Plone 3.1. Here is the example of ImportError that I get when using collective.groupspace.roles with Plone 3.1:
  File "/home/andrey/tmp/zope/instance/lib/python/collective/groupspace/roles/browser/roles.py", line 23, in ?
    from plone.app.workflow import PloneMessageFactory as _
zope.configuration.xmlconfig.ZopeXMLConfigurationError: File "/home/andrey/tmp/zope/instance/etc/site.zcml", line 15.2-15.23
    ZopeXMLConfigurationError: File "/home/andrey/tmp/zope/instance/Products/GrufSpaces/configure.zcml", line 17.4-17.53
    ZopeXMLConfigurationError: File "/home/andrey/tmp/zope/instance/lib/python/collective/groupspace/roles/configure.zcml", line 7.4-7.34
    ZopeXMLConfigurationError: File "/home/andrey/tmp/zope/instance/lib/python/collective/groupspace/roles/browser/configure.zcml", line 5.4-10.10
    ImportError: cannot import name PloneMessageFactory

Besides collective.* packages you have to download GrufSpaces product from SVN (download link at plone.org doesn't work for me) and place it in Products folder.

A: No advice specific to GruffSpaces as I've never used it but it sounds like you may be under the mistaken impression that you need Plone 3.2+ for buildout.  This is incorrect.  Buildout works just fine with Plone 3.1.2.  I've also done buildouts for Plone 2.5.5 and even one for Plone 2.1 (although this last one was a bit tricky because the required python for that version doesn't do buildout).
So if you prefer the buildout route, just do it.  Although upgrading your Plone is probably still good advice.