text:
Q: Search two columns in LINQ to SQL? I am trying to make a simple search method using LINQ to SQL in Visual Studio. In my database, I have the fields "Firstname" and "Lastname", and my search string is "name". How can I make a simple LINQ query which searches both fields?
In plain SQL I would do something like this:
SELECT (Firstname + Lastname) as 'Fullname'
FROM   table
WHERE  Fullname LIKE '%searchstring%'

A: var result = from p in db.Table
             let fullname = p.FirstName + " " + p.Lastname
             where fullname.Contains(searchString)
             select new { Fullname = fullname };

A: The usual thing to do is this:
var users =
    from user in db.Users
    where user.FirstName.Contains(searchString) ||
        user.LastName.Contains(searchString)
    select user;

This however is not equivalent to your SQL query. The following is equivalent:
var users =
    from user in db.Users
    let fullName = user.FirstName + user.LastName
    where fullName.Contains(searchString)
    select user;

A: // get all items from table where firstname like searchstring or lastname like searchstring
var result = from p in db.Table
             where (p.Firstname.Contains(searchString) || p.Lastname.Contains(searchString))
             select p;


text:
Q: How to return all records on nested association in active record, rails 5 I'm struggling to figure out the proper active record query on a nested association.  I'm trying to get all users that belong to any communities that contain a pod with a particular id.
So as an example, you might have a pod which belongs to three different communities which all have their own list of members (some of which might be the same across communities).  Given that pod's id, I want to have a unique list of all the associated members that belong to all of the pod's communities.
class Pod
    has_many :pod_communities
    has_many :communities, through: :pod_communities
end

class Community
    has_many :pod_communities, dependent: :delete_all
    has_many :pods, through: :pod_communities

    has_many :community_members, dependent: :delete_all
    has_many :members, through: :community_members, class_name: "User", foreign_key: "user_id"
end

class User
    has_many :community_members, dependent: :delete_all
    has_many :communities, through: :community_members
end

A: Please try the following code
class Pod
  has_many :pod_communities
  has_many :communities, through: :pod_communities
  has_many :members, through: :communities
end

Pod.first.members # Will give all the users which belongs to any community which is associated with POD 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как окрасить нужные строки таблицы, если в каждой второй имеется rowspan=2? Добрый день!
Имеется таблица:

Нужно за счёт лишь CSS (без использования js) окрасить каждую вторую строку в нужный цвет. Как это можно сделать?
Следует обратить особое внимание на то, что в таблице имеются двойные строки, которые должны быть одного цвета.
Добавлено после первого ответа:
Следует так же учесть то, что первая и последняя строки динамически добавляются за счёт js. Нужно сделать так, чтобы не городить сложные манипуляции в разных местах, а обойтись лишь CSS правилами.

A:

table, tr, td {
  border: 1px solid;
  border-collapse: collapse;
  width: 100%;
  table-layout: fixed;
  height: 1em;
}

tr:nth-child(even) {
  background: silver;
}

PS: Честно говоря, вообще не понял, как rowspan влияет на окрашивание...

A: Сам справился с задачей!
Просто добавил в добавляемые строки за счёт js ещё одну строку tr с колонкой со стилем display: none и код получился примерно следующим:

CSS же такой:
table tr:nth-child(4n+2){
    background: rgba(0,0,0,0.05);
}
table tr:nth-child(4n+3){
    background: rgba(0,0,0,0.05);
}

Всем спасибо!

A: Самое первое что приходит в голову - добавить к каждой второй строке класс, и уже к этому классу добавить,например background-color: red;


text:
Q: Building GNU part of GNU/Linux I have successfully built the Linux Kernel 3.13.6 and ran it in QEMU. Since it is just the kernel, it will eventually complain that it cannot find init or sh, etc.
Therefore, it is necessary to build the GNU utilities for Linux (which makes it GNU/Linux). However, how would someone do that? How do you build the utilities for Linux?
Is it as simple as downloading & compiling w/ GCC and then copying onto a formatted disk?

A: Most of the very basic UNIX commands are part of GNU coreutils if that's what you mean, like ls, mv, etc.

How do you build the utilities for Linux?

Like you build anything else under Linux.  Download the source, read the instructions the developer has provided, and follow them - typically involving making sure you have the prerequisites such as libraries, etc. available, changing to the source directory, maybe running a configure script, and then issuing a make command or two.
In coreutils case, you want to read and follow this.


text:
Q: How to redirect myurl.com/targeturl.com to to myurl.com/?site=targeturl (PHP/Apache/Linux)? I'm writing a website that allows people to asses a web page's readability (Flesch-Kincaid Reading Ease, thank kind of thing).
Ideally I'd like the user to be able merely to preceed the target URL with mine (like many mirror sites do), and hey presto they can see the results.
I'm guessing it's got to be done with mod_rewrite, but I'm not sure how to write it, especially given that URLs may contain so much potential junk.
How would I say:
if request is mysite.com/anything-at-all ).
redirect to mysite.com/?site=anything-at-all
Except in cases where the request is for:

*

*just for mysite.com/

*The request is for mysite.com/ajaxresponse.php?target=something

*Where the request is for about.php or loading.gif
Sadly everything that I have tried so far ends up in an redirect loop...
Many thanks,
Jack

A: Edit your .htaccess to have:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.+)$ ?site=$1 [NC]

The + in the regex will take care of the index page being left as is. Edit otherwise as you deem necessary (make it a 302 permanent redirect, etc...)
For excluding the specific pages you should add a line:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(ajax\.php|whatever\.gif) - [L]
RewriteRule ^(.+)$ ?site=$1 [NC]

A: Try this rule:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{QUERY_STRING} !(^|&)site=[^&]
RewriteRule .+ /?site=$0 [QSA]

The first condition is to exclude requests to existing files and the second is to avoid a redirect is there already is a site URL argument.


text:
Q: Symfony: any way to show the global errors only if there isn't any field error? in a form if there is a field and a global error both messages are showed.
I would like to show the global errors only if there isn't any field error.
Any idea?

A: This snippet should do the job
<?php if (0 == ( count($form->getErrorSchema()->getErrors()) - count($form->getErrorSchema()->getGlobalErrors()) ) ):?>
<?php echo $form->renderGlobalErrors()?>
<?php endif?>


text:
Q: How to expand all variables in java class I want to expand all variables in a class, then convert them to json string.
For example:
class A {
   int a1;
   double a2;
   public A(int a1, double a2) {
      this.a1 = a1;
      this.a2 = a2;
   }
}

class B {
   string b1;
   A a;
   public B(A a, string b1) {
      this.a = a;
      this.b1 = b1;
   }
}

now I have B-class object.
B b = new B(new A(1, 2.5), "test");

Finally, I want to convert B to JSON, but it's not a normal JSON, I want to expand all variables
like this:
{
  "a1": 1,
  "a2": 2.5,
  "b1": "test"
}

not below one
{
  "a": {"a1": 1, "a2": 2.5},
  "b1": "test"
}

I use Jackson, how to realize it in a general way. I think I can put all elements into a map, then finally writeValueAsString, but seems not elegant

A: Use reflection. You can get an array of declared fields in a class, then (via recursion) you can create JSON data from them.
Object o=yourobject;
for(Field field : o.getClass().getFields()) {
        String name=field.getName();
        Class<?> type=field.getType();
        Object value=field.get(o);//you can recursively parse 'value' as well
}

Then you can just use the primivive fields' values directly in json.
A useful post about reflection: What is reflection and why is it useful?


text:
Q: Running commands inside docker container created using Dockerfile in Jenkinsfile I have created a Jenkins pipeline file and created a Jenkinsfile. Inside Jenkinsfile I have used Dockerfile agent and then running some steps. The steps are supposed to run inside docker but they are running on the host.
Hers the code.
#!/usr/bin/env groovy
@Library(['abc-jenkins','xyz-jenkins-library']) _
pipeline {
agent {
    dockerfile{
        dir 'TEST'
        filename 'dockerfile'
        label 'docker'
    }
}
stages {
    stage('Build Stage') {
        steps {
            echo 'testing stage running'
            sh "ls"
        }
    }
}
}

A: You misunderstand it according to the output of ls.
For Jenkins pipeline docker DSL, it will mount the jenkins job workspace to docker container and change the docker WORKDIR to the jenkins job workspace.
Therefor when you execute ls inside container, it will print the files & fodler under your jenkins job workspace.
You can try other cmd or ls other folder that not exists in host to approve it's really be executed inside container rather than host.

A: You may using -> docker.image('image').inside{..}
stage('BuildInside') {
         docker.image('ubuntu1804').withRun('-d=true -p 8888:8080') {c ->
            docker.image('ubuntu1804').inside{
               /*  Do something here inside container  */
               sh "ls"
            }
        }
  }

A: You have to write the agent creation stage inside the stages brackets:
stages {
    stage('Build Stage') {
        agent {
           dockerfile{
           dir 'TEST'
           filename 'dockerfile'
           label 'docker'
        }
        steps {
           echo 'testing stage running'
           sh "ls"
       }
}


text:
Q: What is the best way to protect against DDOS attacks? I live in an open community.. I run a game on a dedicated server and have no idea about ddos security, I am trying to stop concurrent attacks against my game server but have no idea where to make my first movie, its like I am checkmated in an intense game of chess, do I use another hosts protection? do I build my own kind of protection.. what is the best wya to go here. I am looking to protect my game from http attacks and tcp attacks.

A: DDOS protection is a process where you plan for, put things ready, act when needed and learn lessons from past incidents.
The whole has to be made to measure to fit your needs and possibilities.
Some ideas:

*

*DDOS is used as an attack by the bad guys for typically two reasons:

*

*to make your service unavailable

*to demand money for protection from the perps themselves (maffia technique)

*The amount of traffic even a wannabe perpetrator could send you is typically enough to saturate any incoming connection money can buy. The reason is that "botnets" can be rented real cheap and their combined output bandwidth by far exceeds any incoming bandwidth one could afford continuously (or for most even as a one-off).
This means that if it comes to a "mine is larger than yours" situation: the victim always looses.

*You can do things up front:

*

*make sure to be "mobile": Be ready to swiftly change where your service is located (e.g.: make sure to use relative small caching times (time to live) for DNS names, so you can quickly and nimbly switch servers for genuine users each time side-stepping the ongoing attack)

*have fallback servers ready: if you need to sidestep an attack, it really helps to have servers idling that can take over the real users at any time. CDNs can help here too, but make sure they won't abandon you or charge you excessive amount if you're under attack. This might well mean you want to replicate e.g. (crucial) (parts of) your databases on an ongoing basis as to make sure the alternate servers have the data they need.

*explore contracts up front: if you need to negotiate, your downtime will be longer. The important parts are to mitigate your costs while under attack for e.g. incoming bandwidth that you cannot control. Similarly that they won't drop you as a customer because you're under attack. For your alternate servers, you might want to minimise costs while not under attack. Etc.

*prioritise: What services do you really need while under attack ? Have smaller, lighter versions of your service ready to react on overload. For added bonus: make your services aware of "current" load and overload conditions and adapt the service accordingly automatically.

*low impact services: the less impact a visitor has on your server resources, the harder it is to take you out (or the les effect there is). e.g. Make sure the costly services are for authenticated users only, not for public consumption. (that way you can lock out abusive users more easily)

*Have communication plans made up: determine what is going to be communicated by whom (to whom) over what medium up front. Don't worry too much about info you give to your attacker: they know already if they're a tiny bit smart. You need to inform your regular customers/users and gain a bit of PR back for a diminished service/quality you're able to provide under the difficult circumstances.

*Make sure every decision maker agrees to have a policy to NEVER EVER pay for the attack to stop, as it will only come back worse. If you're a likely target, make this policy public.

A: I see a lot of websites using CloudFlare to protect from DDOS
https://www.cloudflare.com/case-studies-eurovision/
If you were interested in learning how to stop it all by yourself though this is probably a good place to start your learning journey: https://en.wikipedia.org/wiki/Denial-of-service_attack#Defense_techniques


text:
Q: Dart Polymer 1.0 - Two-way binding works? Two-way binding works in Dart Polymer 1.0 - RC2?
When I change the field @Property(nofity: true) in the .dart, it does not reflect (change) into  {{}} in the .html.
See the following example.
Whem I click on paper-button, it´s fire clicar, the property text is changed, but   {{text}} does not change!
main_app.html
<dom-module id="main-app">

  <template>
    <paper-input label="Type something..." value="{{text}}"></paper-input>

      Text: {{text}}

    <paper-button on-click="clicar">cliqueme</paper-button>

  </template>
</dom-module>

main_app.dart
@HtmlImport('main_app.html')
library untitled8.lib.main_app;

import 'dart:html';

import 'package:polymer_elements/paper_button.dart';
import 'package:polymer_elements/paper_input.dart';
import 'package:polymer/polymer.dart';
import 'package:web_components/web_components.dart';

@PolymerRegister('main-app')
class MainApp extends PolymerElement {
  @Property(notify: true)
  String text;

  MainApp.created() : super.created();

  @reflectable
  void clicar(e, detail) {
    text = "super teste";
  }
}

A: You need to use the provided methods to updated properties like
 set('text', "super teste");

notify: true is only to notify parent elements (fires an test-changed event)
There are quite a lot such methods in PolymerBase mixin which you get automatically added by extending PolymerElement and which notify Polymer about changes.

*

*notifyPath (currently the same as set)

for collections there are

*

*add

*addAll

*clear

*fillRange

*insert

*insertAll

*removeItem

*removeAt

*removeLast

*removeRange

*removeWhere

*replaceRange

*retainWhere

*setAll

*setRange
there is also a

*

*get
not sure about what to use it for.


text:
Q: Problem with multiple groups while transforming XML using XSLT I had a problem with grouping while transforming xml to xml using xslt version 1.0
@michael.hor257k has kindly provided the solution to fix it. Link below:
Problem transforming XML groups with XSLT
However, I still need some improvements in the resultant output.

*

*I would like to change the tag in output result "" to  omitting the 'namespace' and getting either the tag name in camelCase (with 's' in lower case in this example) or by replacing it with completely a new tag label like 'document' (). Please see that the input still contains stays the same as it is.

*I want to have another super group like  in the output xml. For example if I have two addresses in the input, i would like to keep them under  …….….. . I tried adding another template as  but it resulted only one super group coming up, not both.

This is the sample input

<?xml version="1.0" encoding="UTF-8"?>
<Statement xmlns:xsi="http://www.w.org/2001/XMLSchemainstance">
<field name="statementNumber"> 25 </field>
<field name="Online"> Yes </field>
<field name="iban"> xxxx </field>
<group name="addressFields">
<member name="addressLine1"> flat 2 ted apartments </member>
<member name="addressLine2"> samurai street </member>
<member name="town"> Jaisalmer </member>
<member name="postCode"> 678222 </member>
<member name="country"> Indonesia </member>
</group>
<group name="addressFields">
<member name="addressLine1"> flat 3 Oxford house </member>
<member name="addressLine2"> Baker street </member>
<member name="town"> London </member>
<member name="postCode"> W1U 6BZ </member>
<member name="country"> UK </member>
</group>
<group name="transaction">
<member name="type"> cash </member>
<member name="amount"> 5228 </member>
<member name="txnDate"> 28 oct 2022 </member>
<member name="reference"> ATM withdrawal </member>
</group>
<group name="transaction">
<member name="type"> card </member>
<member name="amount"> 3378 </member>
<member name="txnDate"> 28 nov 2022 </member>
<member name="reference"> Super market purchase </member>
</group>
</Statement>

XSLT code snippet:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/Statement">
    <xsl:copy>
        <xsl:apply-templates select="field"/>
            <xsl:apply-templates select="group[@name!='transaction']"/>
            <transactions>
                <xsl:apply-templates select="group[@name='transaction']"/>
            </transactions>
    </xsl:copy>
    <xsl:copy>
        <xsl:apply-templates select="field"/>
            <xsl:apply-templates select="group[@name!='addressFields']"/>
            <addressFieldsGroup>
                <xsl:apply-templates select="group[@name='addressFields']"/>
            </addressFieldsGroup>
        </grouping>
    </xsl:copy>
</xsl:template>

<xsl:template match="group | field | member">
    <xsl:element name="{@name}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

<xsl:template match="text()">
   <xsl:value-of select="normalize-space()"/>
</xsl:template>

</xsl:stylesheet>

Actual output

    <?xml version="1.0" encoding="UTF-8"?>
    <Statement xmlns:xsi="http://www.w.org/2001/XMLSchemainstance">
       <statementNumber>25</statementNumber>
       <Online>Yes</Online>
       <iban>xxxx</iban>
         <transaction>
            <type>cash</type>
            <amount>5228</amount>
            <txnDate>28 oct 2022</txnDate>
            <reference>ATM withdrawal</reference>
        </transaction>
         <transaction>
            <type>card</type>
            <amount>3378</amount>
            <txnDate>28 nov 2022</txnDate>
            <reference>Super market purchase</reference>
        </transaction>
      <addressFieldsGroup>
      <addressFields>
         <addressLine1>flat 2 ted apartments</addressLine1>
         <addressLine2>samurai street</addressLine2>
         <town>Jaisalmer</town>
         <postCode>678222</postCode>
         <country>Indonesia</country>
     </addressFields>
      <addressFields>
         <addressLine1>flat 3 Oxford house</addressLine1>
         <addressLine2>Baker street</addressLine2>
         <town>London</town>
         <postCode>W1U 6BZ</postCode>
         <country>UK</country>
     </addressFields>
     </addressFieldsGroup>
    </Statement>

If you see above, only one group name is coming up but not the other. I have given below the expected output. Kindly check and advise.

Expected output

    <?xml version="1.0" encoding="UTF-8"?>
    **<statement>**
       <statementNumber>25</statementNumber>
       <Online>Yes</Online>
       <iban>xxxx</iban>
     **  <transactions>**
         <transaction>
            <type>cash</type>
            <amount>5228</amount>
            <txnDate>28 oct 2022</txnDate>
            <reference>ATM withdrawal</reference>
        </transaction>
         <transaction>
            <type>card</type>
            <amount>3378</amount>
            <txnDate>28 nov 2022</txnDate>
            <reference>Super market purchase</reference>
        </transaction>
    **  </transactions>**
      <addressFieldsGroup>
      <addressFields>
         <addressLine1>flat 2 ted apartments</addressLine1>
         <addressLine2>samurai street</addressLine2>
         <town>Jaisalmer</town>
         <postCode>678222</postCode>
         <country>Indonesia</country>
     </addressFields>
      <addressFields>
         <addressLine1>flat 3 Oxford house</addressLine1>
         <addressLine2>Baker street</addressLine2>
         <town>London</town>
         <postCode>W1U 6BZ</postCode>
         <country>UK</country>
     </addressFields>
     </addressFieldsGroup>
    **</statement>**

Thank you!
Explained in detail in the above section

A: Simply remove the repetitious and overriding apply-templates and directly use new root name:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/Statement">
      <statement>
          <xsl:apply-templates select="field"/>
          <transactions>
              <xsl:apply-templates select="group[@name='transaction']"/>
          </transactions>
          <addressFieldsGroup>
              <xsl:apply-templates select="group[@name='addressFields']"/>
          </addressFieldsGroup>
      </statement>
  </xsl:template>

  <xsl:template match="group | field | member">
      <xsl:element name="{@name}">
          <xsl:apply-templates/>
      </xsl:element>
  </xsl:template>

  <xsl:template match="text()">
     <xsl:value-of select="normalize-space()"/>
  </xsl:template>
</xsl:stylesheet>

Online Demo


text:
Q: adding URL to html.grid column !{Html.Grid(Model.Results)
        .Columns(column =>
        {
          column.For(x => x.Title).Named("Article Name");
          column.For(x => x.Sites);
          column.For(x => x.PreviousPath).Named("Previous Path");
          column.For(x => x.CurrentPath).Named("Current Path");
          column.For(x => x.PreviousUrl).Named("Previous Url");
          column.For(x => x.CurrentUrl).Named("Current Url");
          column.For(x => x.LogDate).Named("Date");
        }
)
  .Empty("There are no R301s.")
}

In the above grid I have a CurrentUrl. This URL is pointing to a website. I need to make the Current URL a hyperlink to the same Url.
On the page I have added
use namespace="MvcContrib.UI.Grid.ActionSyntax"

There is an Action syntax to add hyperlink. I think the code will look something like
column.For(x => x.CurrentUrl).Named("Current Url").Action(href)
Need help with the syntax to add hyperlink to the above column.

A: Unless you want to use ActionSyntax, you can create the Html.ActionLink independently assuming you know what values are coming in for your href.
If href is an actual URL (http://www.example.com), standard HTML works with Spark:
column.For(c =>
           string.Format("{1}", x.Grade, "Previous Url"))
                 .Named("Column Header")
                 .DoNotEncode();

If you're building your URL based on a set Action name and Id (such as directing to an edit page):
column.For(c =>
           Html.ActionLink("Previous Url",
                           "Action_Method_Name",
                           new { controller = "DifferentController", //optional
                                 id = c.YourIdColumnIfRequired  //optional
                               })
               .Named("Column Header")
               .DoNotEncode();


text:
Q: Laravel: field already set to nullable: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'affiliate_link' cannot be null I have already read the following links, but it didn't solve my problem
Laravel 5.4 Upgrade -- Integrity constraint violation - Column cannot be null
Laravel 1048 Column cannot be NULL on storing data
https://laravel.io/forum/04-20-2014-sqlstate23000-column-user-id-cannot-be-null
I am using laravel version 5.5.34
My problem is
This is validation in store method of the controller
    $this->validate($request,[
        'title'=>'required',
        'content'=>'required',
        'affiliate_link' => 'nullable|string'
    ]);

As you can see I set the affiliate_link column name to be nullable and if it's available should be string.
But it throws the following error

Illuminate \ Database \ QueryException (23000) SQLSTATE[23000]:
  Integrity constraint violation: 1048 Column 'affiliate_link' cannot be
  null

A: I think the problem is with your migration file. Are you allowing users to post empty data in your migration file?

A: Check if the affiliate_link column is set to allow null. If not you may want to enable it.

A: Just set the affiliate_link column is set to allow null in your database the problem is just because of this try to set it and the error gone hope this will help you.


text:
Q: Admob setAdListener not working I have created one banner ad, with (x) button will destroy adview. while I load ad again in same activity it wont calling adListener method. First time while app starts its working. So First time I can Visible (x) button while Ad appears but when I destroy ad using (x) button it destroy ad but for second time while I load ad, it loads Ad successfully but it is not calling 'adListener' so button is not going to visible.
This is my code:
<FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true">

            <FrameLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="15dp" >

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:orientation="vertical" >

                    <com.google.android.gms.ads.AdView
                        android:id="@+id/adView"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        ads:adSize="MEDIUM_RECTANGLE"
                        ads:adUnitId="@string/banner_home_footer">
                    </com.google.android.gms.ads.AdView>

                </LinearLayout>
            </FrameLayout>

            <LinearLayout
                android:id="@+id/layout_close_banner_ad"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:orientation="vertical"
                android:gravity="center"
                android:layout_gravity="end"
                android:visibility="gone"
                android:background="@drawable/round_view">

                <ImageView
                    android:id="@+id/imageview_close_banner_ad"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:src="@drawable/ic_action_close_dialog" />

            </LinearLayout>
        </FrameLayout>

Class File :
mAdView = (AdView) findViewById(R.id.adView);
        adRequest = new AdRequest.Builder()
                .build();

mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                Log.i("Ads", "onAdClosed");
                super.onAdClosed();
            }

    @Override
    public void onAdFailedToLoad(int i) {
        Log.i("Ads", "onAdFailedToLoad");
        super.onAdFailedToLoad(i);
    }

    @Override
    public void onAdLeftApplication() {
        Log.i("Ads", "onAdLeftApplication");
        super.onAdLeftApplication();
    }

    @Override
    public void onAdOpened() {
        Log.i("Ads", "onAdOpened");
        super.onAdOpened();
        adCloseButton.setVisibility(View.VISIBLE);
    }

    @Override
    public void onAdLoaded() {
        Log.i("Ads", "onAdLoaded");
        super.onAdLoaded();
        adCloseButton.setVisibility(View.VISIBLE);
    }

});

private void showBannerAd() {

    mAdView.loadAd(adRequest);

}

// Destroy Ad while click on close Icon
 adCloseButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mAdView != null){
                        mAdView.destroy();
                    }
                    adCloseButton.setVisibility(View.GONE);
                }
            });

A: From the docs about destroy

Destroy the ad view. This method should be called in the parent Activity's onDestroy() method. No other methods should be called on the ad view after destroy() is called.

Instead of calling destroy set the visibility of adview to View.Invisible or View.GONE. In onAdLoaded of adView make the adView VISIBLE.


text:
Q: Filter by string in django I have 2 models: UserProfile and User_Details and I want to display the details for one user.I think the problem is at the filter and I don't know how to filter after a string,I'm new to django.How can I fix this?
class ShowProfile(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'profile.html'

    def get(self, request, pk, format=None):
        details=User_Details.objects.all().filter(user=request.user.username)
        serializer = ProfileSerializer2(details, many=True)
        pprint.pprint(json.loads(JSONRenderer().render(serializer.data)))
        return Response({'fields ': serializer})

    def post(self, request):
        serializer = CreatePostSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({'fields': serializer })

        user = UserProfile.objects.filter(username=request.user.username).first()
        serializer.save(user=user)
        pprint.pprint(json.loads(JSONRenderer().render(serializer.data)))
        return redirect('mainPage')

Models:
class UserProfile(AbstractUser):
    pass

class User_Details(models.Model):
    user = models.OneToOneField(UserProfile, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=50, blank = True)
    last_name = models.CharField(max_length=50, blank=True)
    gender = models.CharField(max_length=6, blank=True, default='')
    public_info=models.CharField(max_length=100, blank=True, default='')

Template:
{% extends 'base2.html' %}
{% load rest_framework %}
{% block content %}

              Profile
              My Posts

{% for d in fields %}
  {{d.firs_name }}
a

{% endfor %}

{% endblock %}


text:
Q: Define ICommand as async lambda calling async Task, or just async void? Consider the following two ways of setting an ICommand to perform an asynchronous task (in this case, using Xamarin.Forms.Command, but I expect that's not critical):
Scenario 1: setting the command to an async lambda in which you await an async Task method:
// Command definition
ToggleCheckedCommand = new Command(
    execute: async () => { await ToggleCheckedAsync(); },
    canExecute: () => !IsBusy);

// Method that is executed
private async Task ToggleCheckedAsync()
{
    IsBusy = true;
    await DoWork();
    IsBusy = false;
}

Scenario 2: Setting the command to an async void method:
// Command definition
ToggleCheckedCommand = new Command(
    execute: ToggleCheckedAsync,
    canExecute: () => !IsBusy);

// Method that is executed
private async void ToggleCheckedAsync()
{
    IsBusy = true;
    await DoWork();
    IsBusy = false;
}

As long as one is never calling ToggleCheckedAsync directly, are these two scenarios equivalent, or are there any gotchas with one compared to the other?
(I know async void is generally considered a bad practice outside direct event handlers, but ToggleCheckedAsync is logically an event handler, and the async lambda in scenario 1 is also AFAIK effectively async void.)

A:
As long as one is never calling ToggleCheckedAsync directly, are these two scenarios equivalent, or are there any gotchas with one compared to the other?

Either one is fine; they're equivalent approaches. async void is appropriate here because ICommand.Execute is logically an event handler. (And make no mistake: there is an async void in both approaches: the lambda of the first example becomes async void).
However, in my own code, this doesn't hold true:

As long as one is never calling ToggleCheckedAsync directly

In particular, with unit tests. Unit tests can execute your commands directly, and that includes being able to await until they complete, and ICommand doesn't satisfy this need.
So, I find it's useful to expose the async Task methods. Or, if you want to get fancier, develop an IAsyncCommand type with a Task ExecuteAsync method and expose that from the ViewModel. Taking that design to its logical conclusion, you can end up with a full AsyncCommand that hides the async void Execute as an implementation detail.


text:
Q: Why this Linq doesn't work (Error translating Linq expression to URI: Can only specify query options (orderby, where, take, skip) var query = from ch in Client.wcf.context.CashHeading
    where ch.Id_customer == customern//cc.Id
    from cs in Client.wcf.context.Cash
    where cs.Id_cashheading == ch.Id
    from gg in Client.wcf.context.Good
    where gg.Id == cs.Id_good
    select gg.Price.Value;

I'm getting inner error processing it:

Error translating Linq expression to URI:  Can only specify query
  options (orderby, where, take, skip) after last navigation.

I can't understand why, full sources  Here, on GitHub

A: Basically, you have to condense your where clause into a single where clause after all of the navigations (from) have been performed, like so:
var query =
    from ch in Client.wcf.context.CashHeading
    from cs in Client.wcf.context.Cash
    from gg in Client.wcf.context.Good
    where
        ch.Id_customer == customern && //cc.Id
        cs.Id_cashheading == ch.Id &&
        gg.Id == cs.Id_good
    select gg.Price.Value;

Granted, this doesn't seem optimal, as it would seem that it's going to do cross join all of the tables and then perform the filtering, but remember, you're probably dealing with IQueryable<T> interface implementations, meaning that this will more than likely be interpreted and then optimized by whatever handles the translated queries.


text:
Q: struct's string field as function's parameter in C I have a struct
typedef struct HASH_NODE
{
    char*              word;
    struct HASH_NODE*  next;
} HASH_NODE;

and function
void foo(char* destptr, const char* srcptr)
{
    destptr = malloc(strlen(srcptr)+1);
    strcpy(destptr, srcptr);
}

I want to pass structs field .word to foo and I expect that value of my field would be changed after function return, but it doesn't:
int main (void)
{
    HASH_NODE* nodeptr = malloc(sizeof(HASH_NODE));
    nodeptr->next = NULL;
    nodeptr->word = NULL;
    char* word = "cat";
    foo(nodeptr->word, word);
}

What am I doing wrong?

A: You are overwriting the pointer destptr passed to foo() by malloc'ing. Pass a pointer to pointer from main() to foo():
void foo(char** destptr, const char* srcptr)
{
    *destptr = malloc(strlen(srcptr)+1);
    strcpy(*destptr, srcptr);
}

and call as:
foo(&nodeptr->word, word);

A: In the function
void foo(char* destptr, const char* srcptr)
{
    destptr = malloc(strlen(srcptr)+1);
    strcpy(destptr, srcptr);
}

the parameters destptr and srcptr are local to the function foo. They are automatic variable, i.e., have automatic storage allocation. This mean they are allocated on the stack when the function is called and are destroyed when the function returns. Calling foo as
foo(nodeptr->word, word);

simply copies the value of nodeptr->word to destptr and of word to scrptr. Therefore, the variables nodeptr->word and word are not changed. Allocating memory and assigning to desptr in foo function causes memory leak since that memory is not free and handle to it is lost when foo returns.
What you should do is pass the address of nodeptr->word to foo and change the signature of foo accordingly.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct HASH_NODE
{
    char *word;
    struct HASH_NODE *next;
} HASH_NODE;

void foo(char **destptr, const char* srcptr)
{
    *destptr = malloc(strlen(srcptr)+1);
    strcpy(*destptr, srcptr);
}

int main (void)
{
    HASH_NODE *nodeptr = malloc(sizeof *nodeptr);
    if(nodeptr == NULL) {
        printf("not enough memory to allocate\n");
        return 1;
    }
    nodeptr->next = NULL;
    nodeptr->word = NULL;
    const char *word = "cat";
    foo(&nodeptr->word, word);

    // after done with nodeptr
    free(nodeptr->next);
    free(nodeptr);
    //
    return 0;
}


text:
Q: Как достать JSON из словаря Столкнулся с проблемой
У меня есть словарь в котором хранится мой JSON
Он выглядит так
 var dist: [String:Any] = [:]

Так выглядит JSON
{
"statusCode": 200,
"message": "Данные пользователя",
"content": {
    "id": 59,
    "score": 0,
    "level": 1,
    "level_experience": 0,
    "level_up_experience": 24,
    "daily_level_goal": 1,
    "daily_level_completed": 0,
    "daily_tempo": 0,
    "wasted_hours_count": 0,
    "daily_progress": [
        0,
        0,
        0,
        0,
        0,
        0,
        0
    ]
}}

Каким образом мне достать из словаря содержимое этого JSON
Допустим id, level, score

A: вам нужно привести Any к другому типу, в вашем случае это будет опять таки [String:Any] выглядит это так (один из вариантов):
if let json = dict["content"] as? [String: Any] {
    let id = json["id"]
    //и так далее....
    //только учтите значения вы получите типа Any
    //и их нужно будет приводить к нужному типу
} else {
    print("content isn't json")
}

вот тут можно прочитать про преведение типов

A: Так как вы указали, что используете swift 4, я бы рекомендовал сделать через Codable тип, который добавили в swift 4.
1) Объвляем типизированную структу разобора(в идеале, в отдельном файле):
struct UserInfo: Decodable {
    let statusCode: UInt
    var message: String? = nil
    var content: Content? = nil
}

struct Content: Decodable {
    let id: UInt
    let score: UInt
    let level: UInt
    let level_experience: UInt
    let level_up_experience: UInt
    let daily_level_goal: UInt
    let daily_level_completed: UInt
    let daily_tempo: UInt
    let wasted_hours_count: UInt
    let daily_progress: [UInt]
}

2) В нужном месте, где получили json от сервера:
do {
    let userInfo = JSONDecoder().decode(UserInfo.self, from: jsonData)
    print(userInfo.content?.id)
    print(userInfo.content?.level)
    print(userInfo.content?.score)
    print(userInfo.content?.daily_progress)
} catch {
    print("Не верная структура данных")
}

Если вы уверены, что сервер вам отдает поле "content" всегда и там не будет null, можете написать без "? = nil"


text:
Q: Google Maps API - disabled on domain When page loads i get the message as javascript alert:
Google has disabled use of the Maps API for this application. See the Terms of Service for more information: http://www.google.com/intl/en-US_US/help/terms_maps.html.
Everything working fine till today. Google webmasters tool didnt told me anything.
My question is wherer can i find more informations why exacly this page has been banned/blocked. (In terms there are lots of possible reasons)
What to do to unblock this? Who or where to send the request?

A: My web application had this same error occur, and we fixed it by updating our link to the Google Maps API file.
Previously we were using a downloaded version of the Maps API file located at http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE.
When we instead used the direct link, this particular error went away.
Edit: Even if you're directly linking to Google's js file, make sure your application isn't using an older locally cached version.
Not working version:
<script type="text/javascript" src="local_google_maps_api.js">

Working version:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE">

Google likely started invalidating Google API v3 calls using older address versions. The Javascript code files mainly differ in the API IP address call

A: For everyone getting this error / alert, you must:
1.) Ensure that you are linking to the online API, as noted by Steve Feng. Replace your code for accessing the Google API file with this:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE">

2.) Make sure you clear your page's cache - even if you were already accessing the file with the code above(like I was). This may be done quickly if you're working on a Windows platform by pressing [ctrl] + [F5], or by pressing [cmd] + [R] on a Mac(or ['apple'] + [R]). On linux a simple [F5] should force refresh. If this button combination didn't work(or doesn't apply to you), look at this website for more information on clearing your cache.
After you've cleared your cache and made sure your code accesses the API file from the URL posted above, you should not get that message anymore(as far as I have experienced).
AFAIK, this message appears regardless of you actually breaking Google's Terms and Conditions or not. Furthermore, I have found this message may appear when using a Google API that isn't Google Maps. One example of a complaint here (at bottom).
I have no straight evidence to believe this, but I think this message became Google's default(-ish) error message when you did something to upset one of their APIs.

A: I suddenly have this warning in a web app on iPhone Safari only, after everything working fine for months. iPhone Chrome browser works and desktop mac safari and chrome works. Can't see where the terms are being broken
Strange! Clearing my cache and cookies on iPhone has cleared the problem. Map works fine now. Must be some change in the api which is triggering the problem for users who have recently visited

A: Referencing the Google maps script from you local machine causes this issue.
Just reference it back to the remote version and add the ?sensor=false to the end and you should be good to go.


text:
Q: JavaFX 2.2 Modal window dialog *with* FXML I am trying to use the example provided by @jewelsea at this gist and I'm stuck because I'm using FXML.
I have seen both of these posts: How to create a modal window in JavaFX 2.1 and this answer to JavaFX 2 modal window.
Where I'm stuck is in the code by jewelsea, where it says:
final WebView webView = new WebView();
webView.getEngine().load("http://docs.oracle.com/javafx/");
primaryStage.setScene(new Scene(webView));

Whereas, since I'm using FXML, I do this:
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("MyFXML.fxml"));
Scene scene = (Scene)fxmlLoader.load();
myController = fxmlLoader.getController();
primaryStage.setScene(scene);

Can you tell me how to modify my code (the 4 lines above), so it works with jewelsea's example?
Thanks!

A: The replacement code you are using via FXMLLoader rather than the WebView created scene sample code is fine, you don't need to modify it.
Your code will display the main scene for your primary stage based on an fxml document (for my sample I was using a WebView as my main scene, which you don't need, so you don't need any of the WebView related code from the gist).
What you need is some trigger in your controller at the time you want to display a dialog.  As a simple example, you can setup an fxml for your main scene which just includes a button, and then supply an ActionHandler for the button in your controller (just like in the Introduction to FXML document).
Now, instead of just doing a println when the button is pressed as Introduction to FXML has, call the dialog.show() method like the gist did at the time of WebView document load.  What should happen is that the dialog will now be displayed on top of your fxml generated scene.
You will notice that the dialog itself contains a Scene.  If you wanted (and this is optional), you could define the scene contents using fxml.  To do this, at the time of dialog construction, you set up a new fxml and new controller for the dialog contents and load the fxml created scene for the dialog into the dialog's stage.  The code to do this is pretty much identical code to what you used to load the main scene's fxml into the primaryStage.
Try the above and see if it works for you.  If you are still stuck I can probably create an fxml specific example of the gist along the lines of this answer.
Also note that the referenced gist was written a while ago, and there is a now a showAndWait method in JavaFX which facilitates blocking execution of code when making a dialog call and then allowing to process the result of the dialog without using some of the event handler mechanisms from the gist example.  Strategies both with and without showAndWait are perfectly acceptable solutions though.


text:
Q: How do you provide specific answers to question prompts from a shell script? I have a shell script provided by our admin to connect to HPC where I have to provide answers to various prompts every time I connect. Is there a way that I can put my answers in a text file and it provides the answers to the questions based on what question is asked? I tried other answers on SO but here the situation is different because our admin made the questions/options random and sometimes not all questions pop up. Therefor a static input like echo "y n y y y" won't work. Here is the full workflow.
I invoke the script as login.sh then prompt comes up
1) name1  2) name2   2) name3   4) name4
Please select an account:

then I select the number 1 to 4 based on which one I want to connect to. But let's say I always want to connect to name1, and I can simply do that by passing echo "1" | login.sh. However, the tricky part is that these accounts do not appear in the same order each time. Sometimes name1 is on 1, the next time on 4 and so on. It is random. How can I automate it in such a way that I always connect to name1?
Once I pass this first prompt then the next prompt similar to this one comes up
1) instance1
2) instance2
3) instance3
4) random
Please select an instance to connect to:

then again I fill in one numeric value 1 to 4. I always want to connect to random but similar to above, it doesn't always come at position 4. How can I do it?
These first couple of steps are numerical but then comes a bit more complex where it asks us to enter our user id and password.
What is your username?:

here I can either enter my user id or just press enter to continue. I would like to know how to do it both ways. Finally it asks for the password.
Password:
then I enter the password. Trick here is that sometimes it let's me login by only entering the password once, but sometime it asks for the password multiple times.
How can I provide these answers in a simple text file and pass this file to shell script as an argument maybe that it can detect which question is being asked and provide answers based on what question is being asked. I would really appreciate if I can get some guidance on this one.


text:
Q: Default localhost on mac lion moving slowly When developing on my mac the default localhost server runs very slowly compared to the mamp server.
I ran nmap on the both servers and got back a significant difference. Unfortunately, this is out of my realm of knowledge. What does it mean and is there a way I can fix the default localhost to run faster?
****-MBP:~ ****$ nmap localhost

Starting Nmap 5.51 ( http://nmap.org ) at 2012-05-01 14:12 CDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00056s latency).
Not shown: 499 closed ports, 491 filtered ports
PORT      STATE SERVICE
80/tcp    open  http
88/tcp    open  kerberos-sec
548/tcp   open  afp
631/tcp   open  ipp
3389/tcp  open  ms-term-serv
3689/tcp  open  rendezvous
5900/tcp  open  vnc
8888/tcp  open  sun-answerbook
49155/tcp open  unknown
49156/tcp open  unknown

Nmap done: 1 IP address (1 host up) scanned in 2.46 seconds
****-MBP:~ ****$ nmap -p 8888 localhost

Starting Nmap 5.51 ( http://nmap.org ) at 2012-05-01 14:12 CDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00013s latency).
PORT     STATE SERVICE
8888/tcp open  sun-answerbook

Nmap done: 1 IP address (1 host up) scanned in 0.03 seconds

A: curl is installed by default on MacOS.  Try running:
curl --trace trace.log --trace-time -o /dev/null <URL>
against both of your URLs.  (It'll write timing output to 'trace.log', so either rename the file between runs or change the filename on the command line.)
Then examine the log files' timestamps and see if you can find where the delays are occurring.


text:
Q: Cannot focus/type in EditText field in TableRow My Android application so far has been going well apart from I'm using the TableLayout in order to structure some data. However, when I add a EditText object in the row, I can no longer type in it.
<TableLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:descendantFocusability="blocksDescendants">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:gravity="center">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ellipsize="marquee"
                android:singleLine="true"
                android:text="Does the title match?" />

            <CheckBox
                android:id="@+id/checktextview_doestitlematch_confirm_item_specs"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="false"
                android:duplicateParentState="true"
                android:focusable="false"
                android:onClick="toggleTitle" />

            <EditText
                android:id="@+id/editText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="textPersonName"
                android:text="Name" />

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </TableLayout>

I've looked and people mainly have this issue with ListViews. I've tried following some suggestions but hit a brick wall. Thanks.

A: Remove from the Table layout the attribute android:descendantFocusability="blocksDescendants". With that attribute the children can't be focusable


text:
Q: What is the correct way of doing JQuery/AJAX and php, file structure? what way should I structure my files when doing Jquery AJAX requests in PHP.
i.e.

*

*showRecords.htm  - contains jQuery/AJAX that gets data (HTML) from the php file below.

*showRecords.php - contains php that does some processing, likely to get data from DB and echo  some HTML.

or
one file:

*

*showRecords.php - contains the JQuery/AJAX and is the php file and requests data from itself.

also you clever people out there, please note I am a beginner in JQuery
  and AJAX so please forgive me if its a silly question or trivial.

A: Obviously not: one file.
I'd do it this way:

*

*showRecords.php - form processing, db requests

*templates/showSomeHtml.php - displays everything that your users can see

*showRecords.js - jQuery/AJAX that gets data

And if the jQuery/Ajax modifies the HTML, you could also move that (the dynamic HTML) into the templates (read about javascript templates)

A: I think it's up to you. If you have a quick ajax call you'd like to do and you know it won't be used anywhere but there then I see no issue with having everything in one file. On the other hand, you might need to access that processing script in multiple locations on your site. If that's the case, it's not ideal to place it all in one file. I think two files avoids confusion. Keeps everything separate and neat.


text:
Q: RavenDb Data Subscriptions PropertyMatch with Or condition Im new to RavenDb.Im working on RavenDb's data subscriptions. I have a scenario where I want subcription to trigger when a property has a value from a list of values. If that property has any value from a list of permitted values RavenDb should notify my event handler.

For example I have a property named Event and if it has any value from [1,2,3,4,5], I want subscription to trigger.

In SubscriptionCriteria you can specify PropertiesToMatch which is a Dictionary, but it is like AND condition. It requires that document must have all these values.Is there a way to have an OR condition with RavenDb data subscriptions.
Using PropertieNotMatch and excluding all values other than the desired ones is also not feasible for me because values are not coming from a static list.
Any help would be much appreciated.

A: With RavenDB 4.0 you can create a subscription using JavaScript filtering.
See example and read about Subscriptions Complex Conditional in:
https://github.com/ravendb/book/blob/v4.0/Ch05/Ch05.md#complex-conditionals


text:
Q: Scala sort string based on length of the tokens I have the following List
val input = List("Rahul KM","M Ranjan","LK Advani")

I want to sort this list splitted values based on string length.
For example I need the output to be like
op
List("Rahul KM","Ranjan M","Advani LK")

Edit: For Example consider "LK Advani", I need this sorted to "Advani LK" as len(Advani) > len(LK)

A: Simply:
val res = input.sortBy(_.length)

A: I noticed that you're not just sorting by length, but you're also moving around the initials and surnames. How about this:
input.sortBy(_.length).map { name =>
    name.split(" ").sortWith(_.length > _.length).mkString(" ")
}

A: val input = List("Rahul KM","M Ranjan","LK Advani")

var result = input.sortWith( _.length < _.length )

result.foreach( (s:String) => { println(s)} )


text:
Q: Display a List of Tuples in a C# cshtml View I have tried a few ways to get this Tuple list to display in my cshtml view as uploadModel.ErrorsList but have had no luck, this only displays the type of object the Errorslist (Tuple List int, string, string) is, the ErrorMessages (strings) do show the correct values on the screen. Here is my view:
@using Custom.Website.Areas.Custom.Models
@model Custom.Website.Areas.Custom.Models.ExcelUploadModel

Please fix the following errors and reupload:

Your Upload was successful. @Model.UploadedRowCount tickets updated.

Editable fields: Transporter Ticket #,Transporter, Driver, Truck, AFE #, Water Type, Quantity, Operator Job #, Lease.

    <button class="backButton">Back</button>

A: instead of :
$('#uploadErrors').append('
@Model.ErrorsList
');

create a for loop:
@foreach (var tupleErr in Model.ErrorsList){
<text>$('#uploadErrors').append('
@tupleErr.Item1 @tupleErr.Item2 @tupleErr.Item3
');</text>

}

sorry did not validate the syntax; but the idea is that you need to iterate over the list, then have an append jQuery statement for each item in the list. Keep in mind you can access the tuple items by the properties as "Itemx" .


text:
Q: Is there anything RAD comparable to VCL? After years in embedded programming, I have to develop a Windows app. I dug out my old C++ Builder and Delphi. These are great and the latest version costs over $1k, so I won't be going there.
What I particularly like is the VCL (visual component library) which let's me code my own components and share them with others, plus the thousands of existing 3rd party components. I noticed that there is now also a RAD PHP from Borland too.
I realize that MSVC, QT, NetBeans, etc are good enough IDEs for RAD, BUT does anything offer the ease of the Borland products for developing additional components - and does anything else have thousands to choose from?
PC based? Cross-platform is good. Browser based? Free is always good ;-)
I don't particularly care about the programming language.

I went with Lazarus and am pretty happy with it. I can't just recompile my code and expect it to run, but it covers 90% of my existing Delphi code. I'd recommend giving it a whirl before spending $1k for Delphi

A: SHORT
.net, it's the closest you will get

A: If you want develop desktop apps, Delphi is a clear winner: Single executable, no runtimes, few dependencies in the case you have to deploy an app with database access, native code
As already said, Lazarus + FreePascal makes for the "free Delphi" role. I personally didn't have a good experience with it - but I heard that got better since I last tried it.
(I'm talking of lazarus IDE, since FreePascal seems to be a very stable compiler and used by very serious Delphi projects for various purposes - like creating Win64 binaries, for example)
.NET, on the other side, offers some free solutions:

*

*On the multiplatform side, Mono + MonoDevelop

*On MS stack, the Visual Studio Express IDE.
All the choices allow you to visually create hierarchies of forms and change it in design time. Visual Form Inheritance, VFI for short, can save you a lot of time if done well.
Web things, the major players are Java (JSP and the like) and .NET (ASP.NET). Having done some webservice development in dotNet(1.1), I loved it for the simplicity. Seems Java boys have a lot more work to make things work (that was said from a Java enthusiast friend of mine) with SOAP Webservices.

A: The Visual Studio Express Editions are pretty good if you don't want to spend any money on an IDE.  I started programming in C++ Builder and also liked the VCL a lot.  I dabbled in Java a bit but found C# to be much closer to the C++ Builder/VCL experience.
http://www.microsoft.com/express/
You can always try these out and if you really like the environment the upgrades aren't too expensive to the full versions.  I think the only major feature missing from express editions are plugins.

A: Try Lazarus, Lazarus is a cross platform visual IDE  for Pascal and Object Pascal developers. It is developed for and supported by the Free Pascal compiler.  is available for several Linux distributions, FreeBSD, Microsoft Windows (win32/64/CE) and Mac OS X (including IPhone/IPad). The language syntax has excellent compatibility with  Delphi (classes, rtti, exceptions, ansistrings, widestrings, interfaces).
for additional info check theses links

*

*free pascal

*Components and Code examples

*Lazarus Components

A: If you are interested in PHP, the next version 6.9 of the NetBeans IDE will include support for the Zend Framework. Milestone 1 of NetBeans 6.9 is already available here (24 MB size).
A blog entry with screenshots can be found here: Zend Framework support.

A: For the Java platform, Apache Click is a web based solution.

Highlights:

*

*Very easy to learn

*Component and Page Oriented design

*Event base programming model

*Stateless and stateful page support

*Exceptional performance

*Automatic form rendering and client/server side validation

*Supports Velocity, JSP or FreeMarker page rendering

*Supports Java 1.5 and up

Click examples are available online at http://www.avoka.com/click-examples/home.htm.
There are a number of extension projects that provides extra features and components.
Click applications can also run "in the cloud" on Google App Engine. This means you can develop and test them on a local app engine server and then deploy them to GAE which is free within the basic quota (up to several millions of requests per month).

A: Eclipse is also a great IDE, and there's a good number of libraries which can integrate into it, so Eclipse + free 3rd party components >= VCL.

A: There are quite a few options available.  You can download the express versions of Visual Studio for free and they are quite good.  Not as many features as the full paid versions but very close (however the C++ version DOES NOT support MFC/ATL only C++/Win32).  This gives you great exposure to the .net framework if you wish to learn it.
I haven't used the free Delphi tools so I can't say what they're like.
You could also give Qt or WxWidgets a try as well. Both are great products but I think Qt is more mature and has a better component library.  However both of them come with runtime components that have to be distributed with your app.


text:
Q: Android getting data from facebook json {Response:  responseCode: 200, graphObject: {"id":"108303252910226","first_name":"Chris","last_name":"Jack","email":"adaptech123@gmail.com","gender":"male","birthday":"08\/08\/1984","hometown":{"id":"106377336067638","name":"Bangalore, India"}}, error: null}

I'm getting this response from facebook.
how to get the first name
I have tired
 try {
                                String res = response+"";
                                JSONObject j = new JSONObject(res);
                                String graphResponse = j.optString("graphObject");

                                JSONObject j2 = new JSONObject(graphResponse);

                                String first_name = j2.getString("first_name");

                                Log.i("firstname", ""+first_name);
                            }
                            catch (JSONException e)
                            {
                                e.printStackTrace();
                            }

A: inside your GraphRequest method
GraphRequest request = GraphRequest.newMeRequest(
                                loginResult.getAccessToken(),
                                new GraphRequest.GraphJSONObjectCallback() {
                                    @Override
    public void onCompleted(JSONObject object,GraphResponse response) {
         object.getString("first_name")
    }
});

A: It's multidimensional array so you first spilt that array.
String res="["+"{responseCode: 200, graphObject: {"id":"108303252910226","first_name":"Chris","last_name":"Jack","email":"adaptech123@gmail.com","gender":"male","birthday":"08\/08\/1984","hometown":{"id":"106377336067638","name":"Bangalore, India"}}, error: null}"+"]";
            JSONObject c;
            JSONArray data=null;
            try {
                data = new JSONArray(res);
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
      try {
         if(data != null) {
               for (int i = 0; i < data.length(); i++) {
                  c = data.getJSONObject(i);
                  String lat=c.getString("responseCode");
                   JSONArray dd=      c.getJSONArray("graphObject")
                      }

then json encode with dd string.


text:
Q: Consuming Spring Hateoas Pageable I have a Rest-Service using HAteoas, what worked before without pageing. Now I am producing pageable Json. I did it with out-of-the box features from Spring-Hateoas. But now I am stucking consuming it and I guess it is really not well documented, if it is.
My JSON looks like follows:
{
"_embedded": {
"vertragResourceList": [
  {
    "identifier": 728,
    "auszubildender": "Rumm",
    "beruf": "Landwirt/in",
    "betrieb": "Mitterbauer Johann",
    "betriebsNummer": "e12d0949-67ae-4134-9dc2-fb67758b6b16",
    "zustaendigeStelle": "Irgendwo",
    "beginn": 529887600000,
    "status": "RECENT",
    "fachrichtung": null,
    "schwerpunkt": "Grünland oder Ackergras",
    "ende": 623113200000,
    "_links": {
      "self": {
        "href": "http://localhost:8080/bbsng-app-rest/vertrag/728"
      }
    }
  },
  {
    "identifier": 803,
    "auszubildender": "Gossen",
    "beruf": "Landwirt/in",
    "betrieb": "Beer Johann",
    "betriebsNummer": "d5a20cb9-7273-4b75-85bd-f8e7d6a843c4",
    "zustaendigeStelle": "Woanders",
    "beginn": 278118000000,
    "status": "RECENT",
    "fachrichtung": null,
    "schwerpunkt": "Ackerfutterbau",
    "ende": 339116400000,
    "_links": {
      "self": {
        "href": "http://localhost:8080/bbsng-app-rest/vertrag/803"
      }
    }
  }
]
},
"page": {
"size": 2,
"totalElements": 1000,
"totalPages": 500,
"number": 5
}
}

====
But now my list is "_embedded", so how can I consume it in most convenient way. I would prefer out-of-the-box soltions by Spring-Hateoas or similar.
My code before worked like follows (Json was not wrapped in _embedded/vertragResourceList before!!!).
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public VertragsListe findeAlleVertraege(final Integer firstDataSet, final Integer lastDataSet, final VertragDTFilter vertragsFilter,
        final VertragDTSorting vertragSorting) {
    final VertragsListe vertragsListe = new VertragsListe();
    final String url = LinkUtils.findeVertrag(firstDataSet, lastDataSet, vertragsFilter, vertragSorting);
    final ResponseEntity<List> entity = template.getForEntity(url, List.class);

    if (OK.equals(entity.getStatusCode())) {
        final List<LinkedHashMap> body = entity.getBody();
        for (final LinkedHashMap map : body) {
            vertragsListe.add(getPopulatedVertrag(vertragsListe, map));
        }
    }

    return vertragsListe;
}

Stacktrace:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@e89d61c; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@e89d61c; line: 1, column: 1]

=====
EDIT:
Corresponding Resourceclass looks like this (Serverside and Clientside!!!):
public class VertragPagedResources extends PagedResources<VertragResource> {

    @SuppressWarnings("unchecked")
    public VertragPagedResources(final Collection<VertragResource> content, final PageMetadata metadata) {
        super(content, metadata, CollectionUtils.EMPTY_COLLECTION);
    }

    public VertragPagedResources() {
        super();
    }

}

On Clientside I changed now followed:
@Autowired private RestTemplate template;

@Override
public VertragPagedResources findeAlleVertraege(final Integer firstDataSet, final Integer lastDataSet, final VertragDTFilter vertragsFilter,
        final VertragDTSorting vertragSorting) {
    final String url = LinkUtils.findeVertrag(firstDataSet, lastDataSet, vertragsFilter, vertragSorting);
    final ResponseEntity<VertragPagedResources> entity = template.getForEntity(url, VertragPagedResources.class);

    if (OK.equals(entity.getStatusCode())) {
        return entity.getBody();
    }

    return new VertragPagedResources();
}

Now I don't get any exceptions, but content is empty. The only thing what is filled correctly are the information from pageable (numberOfReturned Datasets, pageSize and so on). The content is empty List!!!
When debugging and I try out the given URL in browser, then JSON looks like above mentioned.
<200 OK,PagedResource { content: [], metadata: Metadata { number: 1, total pages: 100, total elements: 1000, size: 10 }, links: [] },{Server=[Apache-Coyote/1.1], X-Application-Context=[application:custom:8080], totalNumber=[1000], Content-Type=[application/json;charset=UTF-8], Transfer-Encoding=[chunked], Date=[Wed, 28 Jan 2015 16:58:16 GMT]}>

VertragResource (Client & Server):
public class VertragResource extends IdentifierResourceSupport {

  @NotNull private String auszubildender;
  @NotNull private String beruf;
  @NotNull private String betrieb;
  @NotNull private String betriebsNummer;
  @NotNull private String zustaendigeStelle;
  @NotNull private Calendar beginn;
  @NotNull private String status;

  private String fachrichtung;
  private String schwerpunkt;
  private Calendar ende;

  // GETTER & SETTER ....

Controller Server-Side:
@RequestMapping(method = GET, produces = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<VertragPagedResources> showAll( /*  PARAMS  */ ) {

    // FILTER ...
    final VertragFilter filter = new VertragFilter();
    // FILL FILTER

    // SORTING ...
    final VertragSorting sorting = new VertragSorting(/* BLA */)

    // COMPUTE ...
    final VertragResourceAssembler assembler = new VertragResourceAssembler();
    final List<Vertrag> alleVertrage = service.findeAlleVertraege(/* BLA */);
    final List<VertragResource> resources = assembler.toResources(alleVertrage);

    //

    final long totalElements = service.zaehleAlleVertraege(filter);
    final long size = Math.min(displayLength, totalElements);
    final long totalPages = totalElements / size;
    final PageMetadata pageMetadata = new PageMetadata(displayLength, displayStart, totalElements, totalPages);
    final VertragPagedResources pagedResources = new VertragPagedResources(resources, pageMetadata);
    return new HttpEntity<VertragPagedResources>(pagedResources, headerTotalNumberOfData());
}

====
IdentifierResourceSupport :
public class IdentifierResourceSupport extends ResourceSupport {
    private Long identifier;

    public Long getIdentifier() {
        return identifier;
    }

    public void setIdentifier(Long identifier) {
       this.identifier = identifier;
    }
}

=====
EDIT 2:
What I did now, I switched Spring-Boot from 1.2.1 back to 1.1.10. Now I get an exception when trying the same, it seems that Spring-Boot 1.2.1 hides the exception:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized field "_embedded" (class at.compax.bbsng.client.mvc.client.resource.VertragPagedResources), not marked as ignorable (3 known properties: "links", "content", "page"])
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@62532c56; line: 1, column: 15] (through reference chain: at.compax.bbsng.client.mvc.client.resource.VertragPagedResources["_embedded"]); nested exception is com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "_embedded" (class at.compax.bbsng.client.mvc.client.resource.VertragPagedResources), not marked as ignorable (3 known properties: "links", "content", "page"])
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@62532c56; line: 1, column: 15] (through reference chain: at.compax.bbsng.client.mvc.client.resource.VertragPagedResources["_embedded"])

A: Okay,
I got the solution now.
First of all, there is a BUG in Spring Boot 1.2.1. like mentioned in the question EDIT2. Spring-Boot 1.1.10 throws exception, because it cannot map the content in _embedded. Thats why my content stayed empty. Spring Boot 1.2.1 just leave it emptry without any hint as exception. Downgrading to 1.1.10 gave me the hint.
So what were the consequence to change:
Controller on Serverside:
@RequestMapping(method = GET, produces = "application/hal+json")
public HttpEntity<VertragPagedResources> showAll( /* PARAMS */  ) {

    // LIKE CODE IN QUESTION ...

    return new HttpEntity<VertragPagedResources>(pagedResources);
}

====
RestTemplate Config:
Then you need to configure your Resttemplate to handle HAL-Format.
@Bean
public RestTemplate restTemplate() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Jackson2HalModule());

    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json"));
    converter.setObjectMapper(mapper);

    return new RestTemplate(Collections.<HttpMessageConverter<?>> singletonList(converter));
}

The Client-Code stays same as first Edit in Question!


text:
Q: how to get index of closets match elements in list I have two lists that are related to one another. An original list and a downsampled list. The original list contains all of my reference data and the downsampled list contains a small sample of the original data. They look like this:
original list:
original = [
 0.0,
 0.033,
 0.066,
 0.1,
 0.133,
 0.166,
 0.199,
 0.233,
 0.266,
 0.299,
 0.333,
 0.366,
 0.399,
 0.433,
 0.466,
 0.499,
 0.533,
 0.566,
 0.599,
 0.633,
 0.666,
 0.699,
 0.733,
 0.766,
 0.799,
 0.833,
 0.866,
 0.899,
 0.933,
 0.966,
 0.999,
 1.033,
 1.066,
 1.099,
 1.133,
 1.166,
 1.199,
 1.232,
 1.266,
 1.299,
 1.332,
 1.366,
 1.399,
 1.432,
 1.466,
 1.499,
 1.532,
 1.566,
 1.599,
 1.632,
 1.666,
 1.699,
 1.732,
 1.766,
 1.799,
 1.832,
 1.866,
 1.899,
 1.932,
 1.966,
 1.999,
 2.032,
 2.066,
 2.099,
 2.132,
 2.166,
 2.199,
 2.232,
 2.266,
 2.299,
 2.332,
 2.366,
 2.399,
 2.432,
 2.466,
 2.499,
 2.532,
 2.566,
 2.599,
 2.632,
 2.666,
 2.699
]

and the downsampled list:
downsampled = [
0.633078,
1.632956,
2.632756
]

How do I get the indices of the elements in original that are exactly or the closet match to the items in downsampled?

A: With numpy's help, using abs and argmin:
import numpy as np
def dist(d):
    return abs(d - np.array(original))
[np.argmin(dist(d)) for d in downsampled]

output:
[19, 49, 79]

A: As an alternative solution, I suggest an approach using only built-in pandas methods.
You just have to create dataframes from the lists
df_original = pd.DataFrame(original, columns=['original_value']).reset_index().rename(columns={'index': 'original_index'})
df_downsampled = pd.DataFrame(downsampled, columns=['downsampled_value']).reset_index().rename(columns={'index': 'downsampled_index'})

Then you just perform a left join from original into downsampled with pandas merge_asof
result = pd.merge_asof(df_downsampled, df_original, left_on=['downsampled_value'], right_on=['original_value'])
result['original_index'].to_list()

[19, 49, 79]

I like this approach because you end up with the complete merged dataframe that you can use to look at the selected values directly and perform other operations.


text:
Q: Como pegar uma data com JavaScript e inserir num form input hidden? Preciso que o javascript preencha automaticamente em um <input type="hidden" /> com a data atual, e outro com 15 dias após a data atual.
Será usado para data de emissão de um boleto e o outro para a data de vencimento do boleto, e preciso que o formato seja aaaammdd.
<input name="dataEmissao" type="hidden" />
<script>
   ????????????????
</script>

e
<input name="dataVencimentoTit" type="hidden" />
<script>
    ????????????????
</script>

Obs: não pode ser PHP, pois estou usando este código dentro de um code
  block do theme, no WordPress. Lá dentro não funciona código PHP, só
  JavaScript.

A: Como fazer setar uma data num input e outra, quinze dias depois noutro?
Os passos que precisas seguir são:

*

*criar um objeto data com o dia de inicio

*criar um novo objeto data com mais 1296e6 ms que o outro (porque o JavaScript trabalha em milisegundos)

*ter uma função para formatar a string de saída, neste caso YYYYMMDD

*ir ao DOM "buscar" os elementos e setar o seu .value
Na prática:
function pad(s) {
    return (s < 10) ? '0' + s : s;
}

function formatarData(d) {
    return [d.getFullYear(), d.getMonth() - 1, d.getDate()].map(pad).join('');
}

var emissao = document.querySelector('input[name="dataEmissao"]');
var vencimento = document.querySelector('input[name="dataVencimentoTit"]');

var hoje = new Date();
var quinzeDias = new Date(hoje.getTime() + 1296e6);
emissao.value = formatarData(hoje);
vencimento.value = formatarData(quinzeDias);

Exemplo: https://jsfiddle.net/3zymmpxb/1


text:
Q: Extract text from an aria-label selenium webdriver (python) Right now I'm working on a program that takes user input of questions and answers, separates them into separate lists of q's and a's, then automatically answers the question given either the question or answer. Since the place where the 'bot' is being used is online, I'm using the Selenium web driver, which is causing me some problems when trying to read an aria-label. I don't know what I'm doing wrong, as I'm not advanced at all with selenium, HTML, or CSS. I'm trying to find the aria-label value for each container without knowing what it is
An example of the HTML I'm trying to get the text value of:

to cloak; to conceal the truth; to offer lame excuses

Snippet of my code:
def driver():
    driver = webdriver.Chrome()
    driver.get(link)
    startMatch = driver.find_element_by_xpath("/html/body/div[5]/div/div/div/div[2]/button").click()

    #find text in matches
    container = driver.find_elements_by_class_name('MatchModeQuestionGridTile-content')
    containerFile = open("QuizletTerms.txt", "w+")

    for _ in list(container):
        arialabel = driver.find_elements_by_css_selector("div[aria-label='']")
        containerFile.write("\n")
        containerFile.write(str(arialabel))
        print(arialabel)

    containerFile.close()
    print("done")
    sleep(5)

Output:

[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]

A: The texts e.g. to cloak; to conceal the truth; to offer lame excuses is present in child
 as well in it's parent
. So extract it you need to induce WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

*

*Using CSS_SELECTOR and get_attribute():
print([my_elem.get_attribute("aria-label") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.MatchModeQuestionGridTile-content>div[aria-label]")))])

*Using XPATH and get_attribute():
print([my_elem.get_attribute("aria-label") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='MatchModeQuestionGridTile-content']/div[@aria-label]")))])

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: Xposed - Can't hook static method I try to hook Settings.System.putInt method which is static. One of the calls for this method is done in setAirplaneModeOn method of com.android.settings.AirplaneModeEnabler class. It is placed in Settings app of android. Also, putInt method is used in com.android.systemui.
However, following code doesn't hook putInt method. It doesn't give any exception, but it also doesn't dump any log message with content "In android.provider.Settings.System" which means beforeHookedMethod is not called or it couldn't be hooked. Loaded app logs are printed. Any help is greatly appreciated.
@Override
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
    if (!( lpparam.packageName.equals("com.android.systemui") || lpparam.packageName.equals("com.android.settings"))) {
        return;
    }
    XposedBridge.log("Loaded app: " + lpparam.packageName);
    final Class<?> mClass = XposedHelpers.findClass("android.provider.Settings$System", lpparam.classLoader);
    findAndHookMethod(mClass, "putInt", ContentResolver.class, String.class, "int",  new XC_MethodHook() {
        @Override
        protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
            XposedBridge.log("In android.provider.Settings.System");
        }
    });
}

Xposed-Framework version : 54
Android version: 4.2.2

A: Since Jelly Bean MR1 (4.2) the method setAirplaneModeOn use putInt in Settings.Global instead Settings.System as you can see here.
Your code should be modified like this:
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
    if (!(lpparam.packageName.equals("com.android.systemui") || lpparam.packageName.equals("com.android.settings"))) {
        return;
    }
    XposedBridge.log("Loaded app: " + lpparam.packageName);
    final Class<?> mClass = XposedHelpers.findClass("android.provider.Settings$Global", lpparam.classLoader);
    findAndHookMethod(mClass, "putInt", ContentResolver.class, String.class, int.class, new XC_MethodHook() {
        @Override
        protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
            XposedBridge.log("In android.provider.Settings.Global");
        }
    });
}

I tested the updated code with KitKat 4.4.4 and it works correctly.


text:
Q: How do I run a slow running batch Asynchronously, specifically a SVN post-commit? I have a slow running batch file that compiles a log of changes and then emails a user. I would like it not to cause the user's commits to perform slowly in TortoiseSVN.
@ECHO OFF
SET REPOS=%1
SET REV=%2
SET DIR=%REPOS%/hooks
SET PATH=%PATH%;%DIR%;C:\Utils
SET WORKING_COPY=C:\path\to\local\copy\
SET SITENAME=MySiteName
SET SMTP_SERVER=11.11.11.11
SET EMAIL_TO=my@email.email
SET EMAIL_FROM=my@email.email
SET SUBJECT=SVN Update - %SITENAME% - rev %REV% - %REPOS%

svn cleanup %WORKING_COPY%
svn update %WORKING_COPY%

ECHO The following changes were made to the code: > %DIR%/email.txt
ECHO. >> %DIR%/email.txt

svn log %WORKING_COPY% -v -r "%REV%" >> %DIR%/email.txt

svn diff %WORKING_COPY% -c "%REV%" --no-diff-deleted >> %DIR%/email.txt

sendEmail -s %SMTP_SERVER% -t %EMAIL_TO% -f %EMAIL_FROM% -u "%SUBJECT%" -o message-file=%DIR%/email.txt

I realised that this was running slowly, so I moved it to another file "email-changes.bat" and created a simple batch to call this batch asynchronously.
@ECHO OFF
#START %1\hooks\email-changes.bat %1 %2
echo 'fired' > %1\hooks\test.log

If I comment out the "START" line it runs and finishes instantly. If I remove the comment it takes forever to complete. I thought that should allow the post-commit to return to SVN quickly.
Is there any way I can get the code to not hang in Subversion, but still complete the emailing task in the background?

A: Try starting the real hook script in a separate process:
@ECHO OFF
cmd.exe /c START %1\hooks\email-changes.bat %1 %2
echo 'fired' > %1\hooks\test.log

if that doesn't work, find a tool that can start another bat file in a separate process/thread.


text:
Q: File numbers do not match after copying I have about 3GB of files/folders (47k files, 15k folders) on a server and am trying to copy it to another in the same domain via LAN. Every time I finish making a copy, the number of files being reported on the server being copied to is more than what exists in the original server.
I used Windows copy (using mouse) the first two times. I then used robocopy (first with the /E parameter and then with /E /PURGE). I have 47,619 files/15,335 folders on the original server. I have 47,640 files/15,335 folders on the copied server. The two times I ran robocopy with the said parameters did not change the number of files.
Does anyone what could be going wrong?
Other details:

*

*Both servers are Win Server SP1 Standard Ed.

*The server where the files are being copied to has 638 MB free in C: but I am copying everything to D: which has enough space.

*I am running the command sitting on the server where the files are being copied to.

A: Copying with the mouse means that you probably used Windows Explorer to copy all those files.  I've experienced many problems with this with large numbers of files that are stored within many directories where Windows Explorer copies files to the wrong directories.
This means that Windows Explorer probably copied some files to the wrong places, and now you have duplicates at the destination -- robocopy would just be ignoring those that it isn't overwriting, and that's how you'd end up with these duplicates.
To find the duplicates, use the following DOS command to output the directory structure to some text files (these operations will take quite a bit of time, so you can start them both in separate DOS windows then go have a coffee):

*

*DIR /s /a /b [source-path] | SORT > file-listing-source.txt

*DIR /s /a /b [target-path] | SORT > file-listing-target.txt

Then, edit those files with a search-and-replace to remove the leading portions of the paths that don't match.  After that, compare the files with the following DOS command (this operation may take a while too, but shouldn't be as long as the first two because the sorting has already been done; go have another coffee but order a "small" size this time):

*

*FC /a /l /n file-listing-source.txt file-listing-target.txt > file-listing-differences.txt

Then view the contents of "file-listing.txt" to see what's different.
(In total, only three new .txt file will be created.)


text:
Q: Importing Android Project can't click finish I am trying to move a project from one computer to another and having issues.  I have tried.
File > New > Project ... > Android Project from Existing code
and
File > Import > Android > Existing Android Code Into Workspace.
Both look like they get me to the same place.  I browse to the project location check the option to copy in existing workspace.  When a click finish nothing happens.  The dialog stays open and the project is to imported or opened.
Ryan

A: Simple export method I tend to follow:

*

*Save everything

*Close Eclipse (And wait to completely close)

*Then goto workspace folder

*Select the project you're working on

*Either simply copy to new location or compress to zip

*Then using new system, either file open project by folder or zip

To open compressed project or copied folder:

*

*File ---> Import

*General ---> Existing Projects into Workspace

*Browse either root directory or archive file
Screenshots below:

A: Maybe there is already a project in your workspace with same name. Check your workspace and rename that project.


text:
Q: How do I run the Linux command, "netstat" from a Java program? I have a client-server project written in Java in which they connect through sockets. I cannot figure out how to run "netstat" from the server side of my Java code.

A: Unfortunately there is no netstat equivalent available directly in java.
You could use the process API to spawn a new process and check the output.
I will use an example from the following q/a: https://stackoverflow.com/a/5711150/1688441
I have changed it to call netstat. After spawning the process you will also have to read the output and parse it.
Runtime rt = Runtime.getRuntime();
String[] commands = {"netstat", ""};
Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new
     InputStreamReader(proc.getInputStream()));

BufferedReader stdError = new BufferedReader(new
     InputStreamReader(proc.getErrorStream()));

// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}

Source: https://stackoverflow.com/a/5711150/1688441


text:
Q: Avatar image upload without page upload I want to add an avatar image upload feature to my project, and I was wondering if there exists any AJAX/jQuery solution for uploading an image without needing to refresh the page after uploading (the image uploads automatically).

A: I have used http://www.uploadify.com/ in several projects and it works great.

A: Apparently this can do it, haven't tried it yet.
http://www.plupload.com/

A: You could use an iframe as target, to avoid full page reload:
<form method="post" action="your_action" enctype="multipart/form-data" target="myIframe">
   <input type="file" name="image" />
   <input type="submit" value="Upload image" />
</form>

   //Post response will load here

A: trying update panel with a trigger DOES NOT WORK !!
DOESNT NOT WORK:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true"                                                           UpdateMode="Conditional" >
  <ContentTemplate>
     <asp:Repeater ID="rpUploadedImages" runat="server">
       <ItemTemplate>
        <img src='../Images/<%# DataBinder.Eval(Container.DataItem, "ImagePath")%>'/>

       </ItemTemplate>
     </asp:Repeater>
   </ContentTemplate>
   <Triggers>
       <asp:AsyncPostBackTrigger ControlID="btnupload" EventName="click" />
   </Triggers>
 </asp:UpdatePanel>

<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:Button ID="btnupload" runat="server" Text="Upload" onclick="btnupload_Click" />

DO WORK:
so you have to go with placing the whole FileUpload tag in a separate page, and call it in iframe in your main page, and of course keep the "Upload" button in the iframe; so by click on the upload button the iframe alone will refresh without refreshing the whole page.
(well tested)


text:
Q: How to find words with REGEX using Elixir Given this string "NEWNEWNEW1" I need to remove all the NEW from the string so that after I'm done replacing it, it would look like this "1". So If I got this string "NEWNEW1" I would also return this "1". So how can I use regex to pull out any instance of NEW?

A: I don't think it is necessary to use Regex for this particular case. This should do :
iex> String.replace("NEWNEWNEW1", "NEW", "")
"1"

A: Regex.replace ~r/(NEW)*, "NEWNEWNEW1", ""


text:
Q: Get stargazer to print number of observations in multinomial logistic regression is there a way to print the number of observations for the multinomial logistic regression model in a stargazer table? This sample code illustrates the problem.
Thank you.
var1<-sample(c('A', 'B', 'C'), size=1000, replace=T)
var2<-rnorm(n=1000)
var3<-rnorm(n=1000)
df<-data.frame(var1, var2, var3)
library(nnet)
mod1<-multinom(var1~var2+var3, data=df)
library(stargazer)
stargazer(mod1, nobs=T, type="text")

A: Stargazer is really nice package however sometimes you have to do some tweaks "by-hand". If you want to have number of observation in you output this is how to go about it:
stargazer(mod1,
          type="text",
          add.lines = list(c("n", nrow(df), nrow(df))))

if you want to create a table in latex you can use:
stargazer(mod1,
          type="latex",
          add.lines = list(c("\\textit{$n$}", nrow(df), nrow(df))))

This approach is so that once you render it in latex "n" will be in mathematical font.
==============================================
                      Dependent variable:
                  ----------------------------
                        B              C
                       (1)            (2)
----------------------------------------------
var2                  0.0002        -0.055
                     (0.080)        (0.079)

var3                  -0.088         0.012
                     (0.078)        (0.077)

Constant              -0.029         0.030
                     (0.078)        (0.077)

----------------------------------------------
n                      1000          1000
Akaike Inf. Crit.   2,206.078      2,206.078
==============================================
Note:              *p<0.1; **p<0.05; ***p<0.01

Hopefully, this is what you have been asking for.

A: Would texreg work for you instead?
library(texreg)
screenreg(list(mod1))
# ====================================
#                 B          C
# ------------------------------------
# (Intercept)         0.01      -0.03
#                    (0.08)     (0.08)
# var2               -0.06       0.01
#                    (0.08)     (0.08)
# var3                0.04       0.10
#                    (0.08)     (0.08)
# ------------------------------------
# AIC              2206.34    2206.34
# BIC              2235.79    2235.79
# Log Likelihood  -1097.17   -1097.17
# Deviance         2194.34    2194.34
# Num. obs.        1000       1000
# ====================================
# *** p < 0.001, ** p < 0.01, * p < 0.05

I may be wrong but I'm not sure this can be easily done with nnet and stargazer. You could make your model mimic that of different output. See here for that type of approach.


text:
Q: What is the difference between the full name and the abbreviation of a time zone I have multiple times in my database that look like this:
String summerTime = "2022-07-21T10:00:00Z";
String winterTime = "2022-11-21T10:00:00Z";

In another hand, I want to get the time part of these dates based on a custom timezone, the timezones that I have, look like this:
GMT-03:00
GMT-02:00
GMT-01:00
GMT+02:00
GMT+01:00
....

When I try to extract the time part using this code:
ZoneId tz = ZoneId.of("GMT+01:00");

ZonedDateTime date1 = ZonedDateTime.parse(summerTime).withZoneSameInstant(tz.toZoneId());
ZonedDateTime date2 = ZonedDateTime.parse(winterTime).withZoneSameInstant(tz.toZoneId());

I get:
11:00
11:00

But if you notice well, the time is the same even on summer or winter dates.
I expect to get:
12:00  // <----- correct
11:00  // <----- correct

I found a solution for my issue, which is using the full name of the time zone, instead of the abbreviation:
ZoneId tz = ZoneId.of("Europe/Paris");

This gives me the correct response:
12:00
11:00

but I can't use this because I should use only the abbreviation.
My question:

*

*Why do the two formats give different results?

*How can get the full name from the abbreviation so I can get the correct output?

A:
Why do the two formats gives different result?

Because your first form is a "fixed offset" time zone, effectively. "GMT+01:00" is always on UTC+1, for the whole of time. It doesn't actually map to any specific area of the world, it's just "always UTC+1".

How can get the full name from the abbreviation so I can get the correct output?

You can't. Even if you know the UTC offset at a particular instant in time, there may be multiple time zones that have that UTC offset at that instant, but have different UTC offsets from each other at different times.
For example, currently both Europe/London and Africa/Abidjan are on UTC+0... but in June 2022 (for example) Africa/Abidjan was still be UTC+0, and Europe/London was UTC+1.

I can't use this because I should use only the abbreviation.

That's a fundamental problem, and you should push back on the requirement. It's like saying "I really need the user's full name, but I only have their initials." It's an infeasible requirement.


text:
Q: simple regex for street address I know there are a dozen questions at least on this. I am trying to have a simple validation of input for street address using Regex whereby I check for at least two spaces in the input entry. The reason? for the most part us addresses are at least 3 parts, street number, street name, type (lane, drive, ave , st ,etc)
I want to alert the user if the entry doesn't match at least that, if it has more than three spaces, meaning it has more names in the address, that's fine but the minimum not being met necessitates an alert. My latest effort is below, and is not working.
  var addregex = new RegExp("^\d{1,6}\040([A-Z]{1}[a-z]{1,}\040[A-Z]{1}[a-z]{1,})$|^\d{1,6}\040([A-Z]{1}[a-z]{1,}\040[A-Z]{1}[a-z]{1,}\040[A-Z]{1}[a-z]{1,})$|^\d{1,6}\040([A-Z]{1}[a-z]{1,}\040[A-Z]{1}[a-z]{1,}\040[A-Z]{1}[a-z]{1,}\040[A-Z]{1}[a-z]{1,})$");

            if (addregex.test($(this).val())) {
                alert('is valid');
                address.addClass('isvalid');
                address.css("border", "1px solid lightgray");
            } else {
                address.css("border", "2px solid red");
                alert("Are you sure this is a valid street address?");
                address.focus();
            }

A: A simple test is all you need:    /^\s*\S+(?:\s+\S+){2}/

A: \w+(\s\w+){2,}
Description:

*

*\w+ => Alphanumeric, one or more repititions

*\s => Whitespace

*(\s\w+) => A numbered capture group [\s\w+]

*{2,} => at least 2 repititions

A: I could not get the other guys to work for some reason but this one validates all street addresses I have ever come up with...
var value = '12136 Test This Road';
var streetAddRegEx = new RegExp('/\d{1,}(\s{1}\w{1,})(\s{1}?\w{1,})+)/g');
console.log(streetAddRegEx.test(value));

Basically I made it so it was any set of words more then one proceeding a set of numbers...

A: You've got some viable suggestion here. I would however like to offer you a regex that I think does what you asked for:
\d+\s+\w+\s+\w+

or, if it's a warning only, you could even add testing of "types" you indicated, like:
\d+\s+\w+\s+(?:st(?:\.|reet)?|ave(?:\.|nue)?|lane|dr(?:\.|ive)?)

allowing for abbreviated version with or without full stop. (Add road, court, etc. at will)
Check it out at regex101.
Hope this helps,
Regards
EDIT: Remember to add flag for case insensitive. ;)

A: Improved version based on ClasG's answer.
/\d+(\s+\w+){1,}\s+(?:st(?:\.|reet)?|dr(?:\.|ive)?|pl(?:\.|ace)?|ave(?:\.|nue)?|rd|road|lane|drive|way|court|plaza|square|run|parkway|point|pike|square|driveway|trace|park|terrace|blvd)/

A: ^(?!\s*$)^((?!([p|P][-. ]?[o|O].?[- ]?|post office )[b|B]([ox|OX]))(?!(\`|\~|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\+|\=|\[|\{|\]|\}|\||\\|\'|\<|\,|\.|\>|\?|\"|\;|\:)).)*$