问:
What is "Super Loop" in Embedded C programming language?
What is Super Loop in Embedded C programming language?

答:
Super loop is an infinite loop which is suitable only in embedded c programming because there you have to run your code for very very long time and wants explicitly terminate when the behavior is change for your robot or whatever.
Superloop be like

```<code>while(1){

// Your code

// exit condition

}

for(;;) {

}
</code>```

Body:
Super loop is an infinite loop which is suitable only in embedded c programming because there you have to run your code for very very long time and wants explicitly terminate when the behavior is change for your robot or whatever.
Superloop be like

while(1){

// Your code

// exit condition

}

for(;;) {

}


来源: stackexchange

问:
How to call the angular function on ng-click of a href
a href tag

```<code><a href="#" ng-click="getUserSkills($event);" data-id="{{iUserInfoID}}" class="accordion-toggle" title="Skills" data-toggle="modal" data-target="#skillModal">Skills</a>
</code>```

Angular Controller

```<code>    $scope.getUserSkills=  function (e) {
    e.preventDefault();
    $scope.UserInfoId = $(this).data('id');
    alert($scope.UserInfoId)

};
</code>```

答:
You can just remove the href="#" from the link.

```<code><a ng-click="getUserSkills($event);">My Link</a>
</code>```

But I would suggest you use just a span or something similar instead. There is no reason why you should try to suppress a default functionality of a when you can use any other HTML tag.

ContentLicense: CC BY-SA 3.0

Body:
a href tag

Skills

Angular Controller

    $scope.getUserSkills=  function (e) {
    e.preventDefault();
    $scope.UserInfoId = $(this).data('id');
    alert($scope.UserInfoId)

};

Body:
You can just remove the href="#" from the link.

<a ng-click="getUserSkills($event);">My Link</a>

But I would suggest you use just a span or something similar instead. There is no reason why you should try to suppress a default functionality of a when you can use any other HTML tag.


问:
Regex named capture group with multiple values
I seem to be having a tough regex week.  Anyone that can save me from throwing my laptop out the window gets a virtual beer.  I have some data in the form of:

```<code>... f=something group="First Group,Group2" foo=val ...
</code>```

where the number of groups can vary.  I need to capture each group entry to a named capture.  Based on a previous post, The difference here is that I don't have a constant to key off of within the values (i.e. ID-1-1, ID-2-2 allows me to say ID-\d+-\d+ whereas these values could be pretty much anything). I've been trying a ton of stuff, but I tend to get matches that are far too greedy, or I (often) get these 2 values:

```<code>First Group
First Group,Group2
</code>```

What I need is:

```<code>First Group
Group2
...
</code>```

I'm currently trying regex such as this where I'm trying to anchor to the group=" portion, and not exceed the ending ":

```<code>(?:(?:group=\")|(?:\"))(?<group>(?:(.+)+?)
</code>```

Hopefully someone can make my day a lot better...

答:
Here's the PHP solution. Once again, regex doesn't like capturing the multiple values so we need to break it in to two searches. One extracts the group value, the next extracts each value from the group

```<code>$test = 'f=something group="First Group,Group2" foo=val';
$re = '/(?:group=)?\x22(?<group>(?:[^\x2C]+\x2C*)+)\x22/';
$_ = null;
if (preg_match($re,$test,$_))
  echo "Group Contents: ".$_['group']."\r\n";

$__ = null;
$re = '/(?:^|\x2C)(?<value>(?:[^\x2C]+)+)/';
if (preg_match_All($re,$_['group'],$__))
  echo "Group Values: ".print_r($__['value'],true);
</code>```

Should be pretty easy to port in to another language, just extract the regexes out and manage them the way you normally would.

ContentLicense: CC BY-SA 2.5

Body:
I seem to be having a tough regex week.  Anyone that can save me from throwing my laptop out the window gets a virtual beer.  I have some data in the form of:

... f=something group="First Group,Group2" foo=val ...

where the number of groups can vary.  I need to capture each group entry to a named capture.  Based on a previous post, The difference here is that I don't have a constant to key off of within the values (i.e. ID-1-1, ID-2-2 allows me to say ID-\d+-\d+ whereas these values could be pretty much anything). I've been trying a ton of stuff, but I tend to get matches that are far too greedy, or I (often) get these 2 values:

First Group
First Group,Group2

What I need is:

First Group
Group2
...

I'm currently trying regex such as this where I'm trying to anchor to the group=" portion, and not exceed the ending ":

(?:(?:group=\")|(?:\"))(?<group>(?:(.+)+?)

Hopefully someone can make my day a lot better...

Body:
Here's the PHP solution. Once again, regex doesn't like capturing the multiple values so we need to break it in to two searches. One extracts the group value, the next extracts each value from the group

$test = 'f=something group="First Group,Group2" foo=val';
$re = '/(?:group=)?\x22(?<group>(?:[^\x2C]+\x2C*)+)\x22/';
$_ = null;
if (preg_match($re,$test,$_))
  echo "Group Contents: ".$_['group']."\r\n";

$__ = null;
$re = '/(?:^|\x2C)(?<value>(?:[^\x2C]+)+)/';
if (preg_match_All($re,$_['group'],$__))
  echo "Group Values: ".print_r($__['value'],true);

Should be pretty easy to port in to another language, just extract the regexes out and manage them the way you normally would.


问:
How can I match multiple hits between 2 delimiters?
Hi, my fellow RegEx'ers ;)

I'm trying to match multiple Texts between every two quotes
Here's my text:

```<code>...random code
someArray[] =         ["Come and",
                       "get me,",
                       "or fail",
                       "trying!",
                       "Yours truly"]
random code...
</code>```

So far, I managed to get the correct matches with two patterns, executed after each other:

```<code>(?s)someArray\[\].*?=.*?\[(.*?)\]
</code>```

this extracts the text between the two brackets and on the result, I use this one:

```<code>"(.*?)"
</code>```

This is working just fine, but I'd love to get the Texts in one regex.

Any help is highly appreciated!

答:
Consider using \G. With its help, you may match "(.*?)" preceded by either someArray[] = [ or previous match of "(.*?)" (well, strictly speaking previous match of entire regex). Then just grab first capture groups from all matches:

```<code>(?:(?s).*someArray\[\].*?=.*?\[|\G[^"\]]+)"(.*?)"
</code>```

Demo: https://regex101.com/r/eBQWdU/3

How you grab the first capture groups from depends on the language you're using regex in. For example in PHP you may do something like this:

```<code>preg_match_all('/(?:(?s).*someArray\[\].*?=.*?\[|\G[^"\]]+)"(.*?)"/', $input, $matches);
$array_items = $matches[1];
</code>```

Demo: https://ideone.com/mZgU1x

Body:
Hi, my fellow RegEx'ers ;)

I'm trying to match multiple Texts between every two quotes
Here's my text:

...random code
someArray[] =         ["Come and",
                       "get me,",
                       "or fail",
                       "trying!",
                       "Yours truly"]
random code...

So far, I managed to get the correct matches with two patterns, executed after each other:

(?s)someArray\[\].*?=.*?\[(.*?)\]

this extracts the text between the two brackets and on the result, I use this one:

"(.*?)"

This is working just fine, but I'd love to get the Texts in one regex.

Any help is highly appreciated!

Body:
Consider using \G. With its help, you may match "(.*?)" preceded by either someArray[] = [ or previous match of "(.*?)" (well, strictly speaking previous match of entire regex). Then just grab first capture groups from all matches:

(?:(?s).*someArray\[\].*?=.*?\[|\G[^"\]]+)"(.*?)"

Demo: https://regex101.com/r/eBQWdU/3

How you grab the first capture groups from depends on the language you're using regex in. For example in PHP you may do something like this:

preg_match_all('/(?:(?s).*someArray\[\].*?=.*?\[|\G[^"\]]+)"(.*?)"/', $input, $matches);
$array_items = $matches[1];

Demo: https://ideone.com/mZgU1x


问:
PHP only sending the first word in my sentense?
I am developing an APi where its suppossed to send a text message to a number ...this should be the message "Your registration for mobile Number has been received. Thank you for staying connected" but the text massage that is sending is only the first word "Your"

here is my code

```<code>    $message ="Your registration for mobile no has been received. Thank you for staying with MbongoCash";

sendTextMessage("0719401837",$message);

function sendTextMessage($phoneNumber,$data)
{

    $url = "http://121.241.242.114/bulksms/bulksms?username=josy-mbongocash&password=Jofar14&type=0&dlr=1&destination=$phoneNumber&source=MbongoCash&message='$data''";
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}
</code>```

Here is the image.
This is the Image screenshot

答:
The spaces in the message break the URL. Using urlencode should solve this:

```<code>$data = urlencode($data);
</code>```

Body:
I am developing an APi where its suppossed to send a text message to a number ...this should be the message "Your registration for mobile Number has been received. Thank you for staying connected" but the text massage that is sending is only the first word "Your"

here is my code

    $message ="Your registration for mobile no has been received. Thank you for staying with MbongoCash";

sendTextMessage("0719401837",$message);

function sendTextMessage($phoneNumber,$data)
{

    $url = "http://121.241.242.114/bulksms/bulksms?username=josy-mbongocash&password=Jofar14&type=0&dlr=1&destination=$phoneNumber&source=MbongoCash&message='$data''";
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

Here is the image.
This is the Image screenshot

Body:
The spaces in the message break the URL. Using urlencode should solve this:

$data = urlencode($data);


问:
How to make GCM Encrypt with authentication tag for Android
I want to make a function encrypt data by GCM mode with authentication tag for Android.
This is my source code:

```<code>public static byte[] GCMEncrypt(String hexKey, String hexIV, byte[] aad) throws Exception {
        byte[] aKey = hexStringToByteArray(hexKey);
        byte[] aIV = hexStringToByteArray(hexIV);
        Key key = new SecretKeySpec(aKey, "AES");
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(16 * Byte.SIZE, aIV));
        cipher.updateAAD(aad);
        byte[] encrypted = cipher.doFinal(aKey);
        return encrypted;
    }
</code>```

How to insert authentication tag into this code?

答:
You already have included the authentication tag. Java (unfortunately - see below) includes the authentication tag in the ciphertext. That means that it is generated during that last call to doFinal.

You can easily check this by viewing the size of the ciphertext. It should be the same size as the plaintext (in this case aKey) plus 128 bits, the default and sensible size of the authentication tag.

This is also why AEADBadTagException is derived from BadPaddingException : during decryption the verification takes place implicitly. So older code would still be compatible with GCM mode.

As I indicated earlier I think including the authentication tag in the ciphertext is a major design mistake for an API:

it doesn't allow the user to place the authentication tag elsewhere - at least without array (size) manipulation;

it removes the online nature of GCM where decryption of plaintext is instantaneous (for each call to update) as the authentication tag needs to be buffered;

it makes the code larger, less efficient and requires spurious buffering if the location of the authentication tag is known in advance (i.e. if the protocol specifies the tag location or the size of the ciphertext directly);

In my opinion that doesn't weigh up to the advantages of retrofitting the Cipher class without adding methods and maintaining compatibility. It would have been better if the designer had just added methods for retrieving and verifying the authentication tag separately.

Because it is currently raining I have created an example:

```<code>public static void main(String... args) throws Exception {
    int tagSize = 96;

    Cipher gcm = Cipher.getInstance("AES/GCM/NoPadding");

    SecretKey aesKey = new SecretKeySpec(new byte[16], "AES");

    GCMParameterSpec gcmSpec = new GCMParameterSpec(tagSize, new byte[gcm.getBlockSize()]);

    gcm.init(Cipher.ENCRYPT_MODE, aesKey, gcmSpec);

    byte[] pt = "Maarten Bodewes creates code".getBytes(StandardCharsets.UTF_8);
    System.out.println(pt.length);
    byte[] ctAndTag = new byte[gcm.getOutputSize(pt.length)];

    System.out.println(ctAndTag.length);

    int off = 0;
    off += gcm.update(pt, 0, pt.length, ctAndTag, off);
    // prints 16 (for the Oracle crypto provider)
    // meaning it is not online, buffering even during encryption
    System.out.println(off);
    off += gcm.doFinal(new byte[0], 0, 0, ctAndTag, off);
    // prints 40 for the Oracle crypto provider, meaning it doesn't *just*
    // output the tag during doFinal !
    System.out.println(off);

    int ctSize = ctAndTag.length - tagSize / Byte.SIZE;
    System.out.println(ctSize);

    byte[] ct = Arrays.copyOfRange(ctAndTag, 0, ctSize);
    byte[] tag = Arrays.copyOfRange(ctAndTag, ctSize, ctAndTag.length);

    System.out.println(Hex.toHexString(ct));
    System.out.println(Hex.toHexString(tag));
}
</code>```

Notes:

it doesn't make sense to encrypt a key with itself, I hope that was just for demo purposes

GCM quickly loses security for smaller authentication tags, changing the size is not recommended, unless your protocol is explicitly designed for it.

Body:
I want to make a function encrypt data by GCM mode with authentication tag for Android.
This is my source code:

public static byte[] GCMEncrypt(String hexKey, String hexIV, byte[] aad) throws Exception {
        byte[] aKey = hexStringToByteArray(hexKey);
        byte[] aIV = hexStringToByteArray(hexIV);
        Key key = new SecretKeySpec(aKey, "AES");
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(16 * Byte.SIZE, aIV));
        cipher.updateAAD(aad);
        byte[] encrypted = cipher.doFinal(aKey);
        return encrypted;
    }

How to insert authentication tag into this code?

Body:
You already have included the authentication tag. Java (unfortunately - see below) includes the authentication tag in the ciphertext. That means that it is generated during that last call to doFinal.

You can easily check this by viewing the size of the ciphertext. It should be the same size as the plaintext (in this case aKey) plus 128 bits, the default and sensible size of the authentication tag.

This is also why AEADBadTagException is derived from BadPaddingException : during decryption the verification takes place implicitly. So older code would still be compatible with GCM mode.

As I indicated earlier I think including the authentication tag in the ciphertext is a major design mistake for an API:

it doesn't allow the user to place the authentication tag elsewhere - at least without array (size) manipulation;

it removes the online nature of GCM where decryption of plaintext is instantaneous (for each call to update) as the authentication tag needs to be buffered;

it makes the code larger, less efficient and requires spurious buffering if the location of the authentication tag is known in advance (i.e. if the protocol specifies the tag location or the size of the ciphertext directly);

In my opinion that doesn't weigh up to the advantages of retrofitting the Cipher class without adding methods and maintaining compatibility. It would have been better if the designer had just added methods for retrieving and verifying the authentication tag separately.

Because it is currently raining I have created an example:

public static void main(String... args) throws Exception {
    int tagSize = 96;

    Cipher gcm = Cipher.getInstance("AES/GCM/NoPadding");

    SecretKey aesKey = new SecretKeySpec(new byte[16], "AES");

    GCMParameterSpec gcmSpec = new GCMParameterSpec(tagSize, new byte[gcm.getBlockSize()]);

    gcm.init(Cipher.ENCRYPT_MODE, aesKey, gcmSpec);

    byte[] pt = "Maarten Bodewes creates code".getBytes(StandardCharsets.UTF_8);
    System.out.println(pt.length);
    byte[] ctAndTag = new byte[gcm.getOutputSize(pt.length)];

    System.out.println(ctAndTag.length);

    int off = 0;
    off += gcm.update(pt, 0, pt.length, ctAndTag, off);
    // prints 16 (for the Oracle crypto provider)
    // meaning it is not online, buffering even during encryption
    System.out.println(off);
    off += gcm.doFinal(new byte[0], 0, 0, ctAndTag, off);
    // prints 40 for the Oracle crypto provider, meaning it doesn't *just*
    // output the tag during doFinal !
    System.out.println(off);

    int ctSize = ctAndTag.length - tagSize / Byte.SIZE;
    System.out.println(ctSize);

    byte[] ct = Arrays.copyOfRange(ctAndTag, 0, ctSize);
    byte[] tag = Arrays.copyOfRange(ctAndTag, ctSize, ctAndTag.length);

    System.out.println(Hex.toHexString(ct));
    System.out.println(Hex.toHexString(tag));
}

Notes:

it doesn't make sense to encrypt a key with itself, I hope that was just for demo purposes

GCM quickly loses security for smaller authentication tags, changing the size is not recommended, unless your protocol is explicitly designed for it.


问:
How to get all the single number from [number -(to) number] with comma-seperated in a column in sql server
column of data in sqlserver like
    numbers
    1000-1050, 1054, 1090-1230, 1245

```<code>numbers
-------
1000-1050, 1054, 1090-1230, 1245
</code>```

how to get the style like below:

```<code>numbers
-------
1000
1001
1002
1003
1004
...
1050
1054
1090
1091
1092
...
1245
</code>```

答:
First split the comma seperated values, then get the values using a recursive common table expression.

```<code>Declare @values nvarchar(max) = '1000-1050, 1054, 1090-1230, 1245'

;with ranges_cte as
(
    select cast(case pos when 0 then  ResultValue else left(ResultValue,pos-1) end as int) first, cast(case pos when 0 then  ResultValue else substring(ResultValue,pos+1,len(ResultValue)-pos) end as int) Last
    from (
    select ResultValue, charINDEx('-',ResultValue) pos
    from dbo.SplitString(@values,',')) x
)
, values_rte as
(
select first,last,first as active
from ranges_cte
union all
select first,last,active +1 as active
from values_rte
where active< last
)

select *
from values_rte
OPTION (MAXRECURSION 0)
</code>```

Function to split the values:

```<code>Create FUNCTION [dbo].[SplitString] (@StringArray NVARCHAR(MAX), @Delimiter NVARCHAR(10))
RETURNS @ResultedValues table
(
nr int,
ResultValue nvarchar(max)
)
AS
--select * from dbo.splitstring ('123,456,789',',')
BEGIN
  declare @string nvarchar(max)
  declare @nr int = 1
  set @string = @StringArray
  WHILE (CHARINDEX(@Delimiter,@String)>0)
   BEGIN
    INSERT INTO @ResultedValues (nr,ResultValue) VALUES (@nr,LTRIM(RTRIM(SUBSTRING(@String,1,CHARINDEX(@Delimiter,@String)-1))))
    SET @String = SUBSTRING(@String,   CHARINDEX(@Delimiter,@String)+LEN(@Delimiter),LEN(@String))
    set @nr = @nr +1
   END
INSERT INTO @ResultedValues (nr,ResultValue ) VALUES ( @nr, LTRIM(RTRIM(@String)))
RETURN
END
</code>```

Body:
column of data in sqlserver like
    numbers
    1000-1050, 1054, 1090-1230, 1245

numbers
-------
1000-1050, 1054, 1090-1230, 1245

how to get the style like below:

numbers
-------
1000
1001
1002
1003
1004
...
1050
1054
1090
1091
1092
...
1245

Body:
First split the comma seperated values, then get the values using a recursive common table expression.

Declare @values nvarchar(max) = '1000-1050, 1054, 1090-1230, 1245'

;with ranges_cte as
(
    select cast(case pos when 0 then  ResultValue else left(ResultValue,pos-1) end as int) first, cast(case pos when 0 then  ResultValue else substring(ResultValue,pos+1,len(ResultValue)-pos) end as int) Last
    from (
    select ResultValue, charINDEx('-',ResultValue) pos
    from dbo.SplitString(@values,',')) x
)
, values_rte as
(
select first,last,first as active
from ranges_cte
union all
select first,last,active +1 as active
from values_rte
where active< last
)

select *
from values_rte
OPTION (MAXRECURSION 0)

Function to split the values:

Create FUNCTION [dbo].[SplitString] (@StringArray NVARCHAR(MAX), @Delimiter NVARCHAR(10))
RETURNS @ResultedValues table
(
nr int,
ResultValue nvarchar(max)
)
AS
--select * from dbo.splitstring ('123,456,789',',')
BEGIN
  declare @string nvarchar(max)
  declare @nr int = 1
  set @string = @StringArray
  WHILE (CHARINDEX(@Delimiter,@String)>0)
   BEGIN
    INSERT INTO @ResultedValues (nr,ResultValue) VALUES (@nr,LTRIM(RTRIM(SUBSTRING(@String,1,CHARINDEX(@Delimiter,@String)-1))))
    SET @String = SUBSTRING(@String,   CHARINDEX(@Delimiter,@String)+LEN(@Delimiter),LEN(@String))
    set @nr = @nr +1
   END
INSERT INTO @ResultedValues (nr,ResultValue ) VALUES ( @nr, LTRIM(RTRIM(@String)))
RETURN
END


问:
Web.config rule for rewriting url is always redirected from https to http
I have a issue with the web.config and forcing SSLs. I have a rule for rewriting url, because Nette PHP site is hosted.

```<code><rule name="Rewrite Admin" stopProcessing="true">
                  <match url="^admin/(.*)" ignoreCase="true"/>
                  <conditions logicalGrouping="MatchAll">
                      <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                      <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                  </conditions>
                  <action type="Rewrite" url="/admin/index.php" />
               </rule>
</code>```

In case I use https in url, the request is always redirected to http. (https://example.com/admin -> example.com/admin). When I use rule for SSL force below for all requests then error occur (Too many redirects). (have a 2 rules in web.config)

```<code><rule name="Redirect to https">
        <match url="(.*)"/>
        <conditions>
          <add input="{HTTPS}" pattern="Off"/>
          <add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
            <add input="{REQUEST_URI}" pattern="^/(node)" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(cbre)" negate="true" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"/>
      </rule>
</code>```

How to force ssl for action type "rewrite"?

Thanks for help

答:
I took your rule config but cannot reproduce the issue. So, to redirect HTTP traffic to HTTPS, I'd recommend you install a site extension called Redirect HTTP to HTTPS via Kudu.

Open the browser and visit:

```<code>https://<your-app-name>.scm.azurewebsites.net/SiteExtensions/#gallery
</code>```

In search box enter "redirect", then click Search button.

Select Redirect HTTP to HTTPS and click ADD button.

Click Install button when the dialog opens.

To make it available by clicking Restart Site button.

Body:
I have a issue with the web.config and forcing SSLs. I have a rule for rewriting url, because Nette PHP site is hosted.

<rule name="Rewrite Admin" stopProcessing="true">
                  <match url="^admin/(.*)" ignoreCase="true"/>
                  <conditions logicalGrouping="MatchAll">
                      <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                      <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                  </conditions>
                  <action type="Rewrite" url="/admin/index.php" />
               </rule>

In case I use https in url, the request is always redirected to http. (https://example.com/admin -> example.com/admin). When I use rule for SSL force below for all requests then error occur (Too many redirects). (have a 2 rules in web.config)

<rule name="Redirect to https">
        <match url="(.*)"/>
        <conditions>
          <add input="{HTTPS}" pattern="Off"/>
          <add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
            <add input="{REQUEST_URI}" pattern="^/(node)" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(cbre)" negate="true" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"/>
      </rule>

How to force ssl for action type "rewrite"?

Thanks for help

Body:
I took your rule config but cannot reproduce the issue. So, to redirect HTTP traffic to HTTPS, I'd recommend you install a site extension called Redirect HTTP to HTTPS via Kudu.

Open the browser and visit:

https://<your-app-name>.scm.azurewebsites.net/SiteExtensions/#gallery

In search box enter "redirect", then click Search button.

Select Redirect HTTP to HTTPS and click ADD button.

Click Install button when the dialog opens.

To make it available by clicking Restart Site button.


问:
What to do with separate short url domain? Redirect to primary domain? .htaccess?
I'm using a drupal module that has an api to create short url's. It is configurable to use any domain for the short url's. When testing, I used my site's primary domain in creating short url's, and the links that are created work perfectly.

However, when I attempt using a separate short domain, the links are not being routed properly to the primary domain. I really hoped it would be as easy as just setting up a redirect from the short.url --> primarydomain.com, but that gives a 404 when a short.url is clicked.

If I don't use a redirect (in effect, doing nothing to short.url), I get a 500 error when clicking short.url/8d3j

It's clear to me that the code (drupal module) works perfectly, it's just that the maintainer does not believe in documenting code and there is absolutely no clue as to how to configure the separate domain. Anyone been in a similar situation? Does someone know of a couple lines of code to add to .htaccess that will magically solve my problems?

答:
If you're just looking for something to send all the requests to your short domain to your long domain, you might try:

```<code><IfModule mod_rewrite.c>
  RewriteCond %{HTTP_HOST} !^longdomain\.com$ [NC]
  RewriteRule ^(.*)$ http://longdomain.com/$1 [L,R=301]
</IfModule>
</code>```

That's saying: if the host doesn't match my long domain, please ask the client to redirect to the requested path on my long domain.

Body:
If you're just looking for something to send all the requests to your short domain to your long domain, you might try:

<IfModule mod_rewrite.c>
  RewriteCond %{HTTP_HOST} !^longdomain\.com$ [NC]
  RewriteRule ^(.*)$ http://longdomain.com/$1 [L,R=301]
</IfModule>

That's saying: if the host doesn't match my long domain, please ask the client to redirect to the requested path on my long domain.


问:
Can't get libcurl to link.(Dev-C++)
This is a source of tremendous anxiety. I can't seem to get it to do anything. I am thinking about just trashing this whole project. Why isn't the linker working?

I have been sitting and look at so many different links, but I don't understand how to resolve it. I know that I have the library installed correctly, but, I can't seem to get it to link. I have the libcurl.dll in System32 file. Yet, I still do not know what to do. I am going mad trying to get it to work. I don't have any files in the Project Options>Directories>Library Directories, Project Options>Directories>Include Directories, or Project Options>Directories>Resource Directories. In the Project Options>Parameters>Linker:

```<code>"../Program Files (x86)/Dev-Cpp/MinGW64/lib/libcurl.a"
</code>```

So, I don't know what else to do. I have been sitting here for about week trying to figure it out on my own. I probably should have asked for help sooner x.x Maybe I am missing files for the libcurl, but I doubt it because I downloaded the whole file. I don't know if it could be my firewall, Norton, blocking it. How would I allow permissions if it is? I have no clue what the problem is. Can someone shed some light on this. I have literally looked at every solution anyone has to offer on here

My MakeFile:

```<code># Project: Project1
# Makefile created by Dev-C++ 5.11

CPP      = g++.exe
CC       = gcc.exe
WINDRES  = windres.exe
OBJ      = Project.o
LINKOBJ  = Project.o
LIBS     = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc "../Program Files (x86)/Dev-Cpp/MinGW64/lib/libcurl.a"
INCS     = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include"
CXXINCS  = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++"
BIN      = Project1.exe
CXXFLAGS = $(CXXINCS)
CFLAGS   = $(INCS)
RM       = rm.exe -f

.PHONY: all all-before all-after clean clean-custom

all: all-before $(BIN) all-after

clean: clean-custom
    ${RM} $(OBJ) $(BIN)

$(BIN): $(OBJ)
    $(CPP) $(LINKOBJ) -o $(BIN) $(LIBS)

Project.o: Project.cpp
    $(CPP) -c Project.cpp -o Project.o $(CXXFLAGS)
</code>```

The Source Code:

```<code>#include <curl/curl.h>
#include <iostream>

int main( void )
{
    CURL *curl;
    CURLcode res;

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://google.com");
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    return 0;
}
</code>```

The errors that keep popping up:

```<code>g++.exe Project.o -o Project1.exe -L"C:/Program Files (x86)/Dev-
Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-
mingw32/lib" -static-libgcc "../Program Files (x86)/Dev-
Cpp/MinGW64/lib/libcurl.a"
Project.o:Project.cpp:(.text+0x16): undefined reference to `__imp_curl_easy_init'
Project.o:Project.cpp:(.text+0x41): undefined reference to `__imp_curl_easy_setopt'
Project.o:Project.cpp:(.text+0x5c): undefined reference to `__imp_curl_easy_setopt'
Project.o:Project.cpp:(.text+0x6c): undefined reference to `__imp_curl_easy_perform'
Project.o:Project.cpp:(.text+0x83): undefined reference to `__imp_curl_easy_strerror'
Project.o:Project.cpp:(.text+0xb5): undefined reference to `__imp_curl_easy_cleanup'
collect2.exe: error: ld returned 1 exit status
C:\Projects\Makefile.win:25: recipe for target 'Project1.exe' failed
mingw32-make.exe: *** [Project1.exe] Error 1
</code>```

答:
That may work better as

```<code>-L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -lcurl
</code>```

The -L argument adds a directory to the library search path, and the -l argument specifies which library to look for.

Title: Can't get libcurl to link.(Dev-C++)

Body:
This is a source of tremendous anxiety. I can't seem to get it to do anything. I am thinking about just trashing this whole project. Why isn't the linker working?

I have been sitting and look at so many different links, but I don't understand how to resolve it. I know that I have the library installed correctly, but, I can't seem to get it to link. I have the libcurl.dll in System32 file. Yet, I still do not know what to do. I am going mad trying to get it to work. I don't have any files in the Project Options>Directories>Library Directories, Project Options>Directories>Include Directories, or Project Options>Directories>Resource Directories. In the Project Options>Parameters>Linker:

"../Program Files (x86)/Dev-Cpp/MinGW64/lib/libcurl.a"

So, I don't know what else to do. I have been sitting here for about week trying to figure it out on my own. I probably should have asked for help sooner x.x Maybe I am missing files for the libcurl, but I doubt it because I downloaded the whole file. I don't know if it could be my firewall, Norton, blocking it. How would I allow permissions if it is? I have no clue what the problem is. Can someone shed some light on this. I have literally looked at every solution anyone has to offer on here

My MakeFile:

# Project: Project1
# Makefile created by Dev-C++ 5.11

CPP      = g++.exe
CC       = gcc.exe
WINDRES  = windres.exe
OBJ      = Project.o
LINKOBJ  = Project.o
LIBS     = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc "../Program Files (x86)/Dev-Cpp/MinGW64/lib/libcurl.a"
INCS     = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include"
CXXINCS  = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++"
BIN      = Project1.exe
CXXFLAGS = $(CXXINCS)
CFLAGS   = $(INCS)
RM       = rm.exe -f

.PHONY: all all-before all-after clean clean-custom

all: all-before $(BIN) all-after

clean: clean-custom
    ${RM} $(OBJ) $(BIN)

$(BIN): $(OBJ)
    $(CPP) $(LINKOBJ) -o $(BIN) $(LIBS)

Project.o: Project.cpp
    $(CPP) -c Project.cpp -o Project.o $(CXXFLAGS)

The Source Code:

#include <curl/curl.h>
#include <iostream>

int main( void )
{
    CURL *curl;
    CURLcode res;

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://google.com");
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    return 0;
}

The errors that keep popping up:

g++.exe Project.o -o Project1.exe -L"C:/Program Files (x86)/Dev-
Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-
mingw32/lib" -static-libgcc "../Program Files (x86)/Dev-
Cpp/MinGW64/lib/libcurl.a"
Project.o:Project.cpp:(.text+0x16): undefined reference to `__imp_curl_easy_init'
Project.o:Project.cpp:(.text+0x41): undefined reference to `__imp_curl_easy_setopt'
Project.o:Project.cpp:(.text+0x5c): undefined reference to `__imp_curl_easy_setopt'
Project.o:Project.cpp:(.text+0x6c): undefined reference to `__imp_curl_easy_perform'
Project.o:Project.cpp:(.text+0x83): undefined reference to `__imp_curl_easy_strerror'
Project.o:Project.cpp:(.text+0xb5): undefined reference to `__imp_curl_easy_cleanup'
collect2.exe: error: ld returned 1 exit status
C:\Projects\Makefile.win:25: recipe for target 'Project1.exe' failed
mingw32-make.exe: *** [Project1.exe] Error 1

Body:
That may work better as

-L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -lcurl

The -L argument adds a directory to the library search path, and the -l argument specifies which library to look for.


问:
cant open image in android studio (file not found)
I'm using android studio and I have some pics located here: ..\app\src\main\res\pics

I have this method to open images in the adapter java class

```<code>private Drawable drawImage(String iconString) {
    Log.i(TAG , "icon string = " + iconString) ;
    AssetManager assetManager=ctx.getAssets();
    InputStream inputStream;

    try {
        inputStream=assetManager.open("pics/"+iconString+".png");
        Log.i(TAG , "icon string try = " + iconString) ;
        Drawable drawable=Drawable.createFromStream(inputStream, null);
        return  drawable ;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return  null;

}
</code>```

I did invoke the method
but when I build and run it I get the following error:

```<code>java.io.FileNotFoundException: pics/ic_payments.png
06-08 10:10:44.577 8002-8002/ ... W/System.err:
at android.content.res.AssetManager.openAsset(Native Method)
</code>```

What did I miss here?

答:
First create asset folder like this.

Second create folder pics in asset and copy all into that folder files.

Body:
I'm using android studio and I have some pics located here: ..\app\src\main\res\pics

I have this method to open images in the adapter java class

private Drawable drawImage(String iconString) {
    Log.i(TAG , "icon string = " + iconString) ;
    AssetManager assetManager=ctx.getAssets();
    InputStream inputStream;

    try {
        inputStream=assetManager.open("pics/"+iconString+".png");
        Log.i(TAG , "icon string try = " + iconString) ;
        Drawable drawable=Drawable.createFromStream(inputStream, null);
        return  drawable ;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return  null;

}

I did invoke the method
but when I build and run it I get the following error:

java.io.FileNotFoundException: pics/ic_payments.png
06-08 10:10:44.577 8002-8002/ ... W/System.err:
at android.content.res.AssetManager.openAsset(Native Method)

What did I miss here?


问:
Use of cut command in unix
Suppose I have string as follwing:

Rajat;Harshit Srivastava;Mayank 123;5

Now i want result as following using cut command
Rajat
Harshit Srivastava
Mayank 123
5
I have tried but cut is not working on string containing spaces.

答:
Try this</p>

```<code>echo "Rajat;Harshit Srivastava;Mayank 123;5" | sed 's/;/ /g'
</code>```

Title: Use of cut command in unix

Body:
Try this

echo "Rajat;Harshit Srivastava;Mayank 123;5" | sed 's/;/ /g'


问:
Eclipse - pointer to function parameters hints
Showing parameters hint of a function is very practical thing and good way to save time.
Is there a way how Eclipse display parameters hits for a pointer to function.

```<code>struct {
    void (*bar)(p1, p2, p3...);
} foo;
foo.bar("Ctrl+Space")
</code>```

report the following error

```<code>java.lang.ClassCastException: org.eclipse.cdt.internal.core.index.composite.c.CompositeCField cannot be cast to [Lorg.eclipse.cdt.core.dom.ast.IBinding;
</code>```

答:
The ClassCastException is being fixed in bug 517954 which Jonah kindly filed.

However, the ClassCastException is not the reason for having no parameter hints. Showing parameter hints based on a function pointer's type is just something that hasn't been implemented in CDT. Bug 517978 is now on file for that.

Body:
Showing parameters hint of a function is very practical thing and good way to save time.
Is there a way how Eclipse display parameters hits for a pointer to function.

struct {
    void (*bar)(p1, p2, p3...);
} foo;
foo.bar("Ctrl+Space")

report the following error

java.lang.ClassCastException: org.eclipse.cdt.internal.core.index.composite.c.CompositeCField cannot be cast to [Lorg.eclipse.cdt.core.dom.ast.IBinding;


问:
Cx_Freeze build is not including python libraries in zip file
I'm in trouble with cx_Freeze 5.0
I'm working on:
Windows 10 LTSB x64
Python 3.4.4 x86
PyQt5
PyWin32 x86

I never had any issue with this process until I reinstall my Windows10 installation... it was working great and now I can't figured it out why it's happening ...

When I Freeze my python app (python setup.py build) script is copying the whole python libraries outside the python34.zip.
The only thing I got inside python34.zip is *.pyc files (only this.. but a lot)

I don't know why it doesnt include python libraries now and didnt find any options/config, it has to include this automatically ...

If someone can help with this.. :)

Note: nothing has changed in my setup.py, simple setup.py file, copied from standard example just including one asset folder (this one is correctly copied.. no issues)

Thanks !

cx_Freeze build output

答:
I encountered the same problem (if it is indeed a problem) after upgrading to cx_Freeze 5.x. I believe it's mentioned in the changelog here: https://cx-freeze.readthedocs.io/en/latest/releasenotes.html

Added support for storing packages in the file system instead of in
  the zip file. There are a number of packages that assume that they are
  found in the file system and if found in a zip file instead produce
  strange errors. The default is now to store packages in the file
  system but a method is available to place packages in the zip file if
  they are known to behave properly when placed there. (Issue #73)

(emphasis mine)
That "method" is apparently described in https://cx-freeze.readthedocs.io/en/latest/distutils.html#build-exe, specifically the zip_include_packages and zip_exclude_packages options.

I ended up putting the following as a keyword argument to my setup() call, which solved it for me:

```<code>options = {"build_exe": {"include_msvcr": True, "include_files": dataFiles, "packages": ["lxml", "idna"], "zip_include_packages": "*", "zip_exclude_packages": ""}},
</code>```

Body:
I encountered the same problem (if it is indeed a problem) after upgrading to cx_Freeze 5.x. I believe it's mentioned in the changelog here: https://cx-freeze.readthedocs.io/en/latest/releasenotes.html

Added support for storing packages in the file system instead of in
  the zip file. There are a number of packages that assume that they are
  found in the file system and if found in a zip file instead produce
  strange errors. The default is now to store packages in the file
  system but a method is available to place packages in the zip file if
  they are known to behave properly when placed there. (Issue #73)

(emphasis mine)
That "method" is apparently described in https://cx-freeze.readthedocs.io/en/latest/distutils.html#build-exe, specifically the zip_include_packages and zip_exclude_packages options.

I ended up putting the following as a keyword argument to my setup() call, which solved it for me:

options = {"build_exe": {"include_msvcr": True, "include_files": dataFiles, "packages": ["lxml", "idna"], "zip_include_packages": "*", "zip_exclude_packages": ""}},


问:
Drupal - Set 'user/%/edit/uprofile' to default tab on 'user/%/edit'
I'm using the content profile module. When a user is on their view profile page and press edit, they expect the profile edit page to show, not account settings as it is now. The path to content profile edit page is 'user/%/edit/uprofile'. Does anyone know how to set the 'user/%/edit/uprofile' to default tab for 'user/%/edit'?</p>

答:
There is a module on drupal.org.
Works with profile fields.
See Profile Tools.</p>


问:
Not able to generate aggregate csv file in Jmeter
In my application i am not able to create the aggregate file in my test? Below is the error iam facing, Any plugin i need to add?

ERROR: java.lang.NoSuchMethodError: org.apache.jorphan.util.JOrphanUtils.closeQuietly(Ljava/io/Closeable;)V

* Problem's technical details go below *

Home directory was detected as: /prod/products/Performance_Testing/apache-jmeter-2.11/lib/ext
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.jorphan.util.JOrphanUtils.closeQuietly(Ljava/io/Closeable;)V
        at org.apache.jmeter.util.JMeterUtils.loadJMeterProperties(JMeterUtils.java:198)
        at kg.apc.jmeter.PluginsCMDWorker.initializeProperties(PluginsCMDWorker.java:95)
        at kg.apc.jmeter.PluginsCMDWorker.prepareJMeterEnv(PluginsCMDWorker.java:85)
        at kg.apc.jmeter.PluginsCMDWorker.(PluginsCMDWorker.java:55)
        at kg.apc.cmdtools.ReporterTool.processParams(ReporterTool.java:66)
        at kg.apc.cmdtools.PluginsCMD.processParams(PluginsCMD.java:63)
        at kg.apc.cmdtools.PluginsCMD.processParams(PluginsCMD.java:23)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)

        at kg.apc.cmd.UniversalRunner.main(UniversalRunner.java:174)

/prod/products/Performance_Testing/Application/Batch/../Results/1496905397Filters_ByPerson_PeopleSideA_1/Report/1496905686911/aggregate_00.csv (No such file or directory)
IOException: processing requests

答:
I think this is due to JMeter Plugins and JMeter version mismatch

Upgrade to JMeter 3.2  (or whatever version will be the latest by that time), you can get it from JMeter Downloads page

Install JMeter Plugins Manager

Install plugins you require via the JMeter Plugins Manager

If the problem still persists report the problem via JMeter Plugins Support Forum


问:
Trouble for newbie with header code
I'm a newbie to code and pretty well illiterate. I have inserted some code into my customized header file only to realize it was the wrong place.

I since received this error message when i try to get onto my website

Parse error: syntax error, unexpected '$', expecting variable (T_VARIABLE) in /home2/seth1/public_html/wp-content/themes/TESSERACT/inc/custom-header.php on line 151

After seeing this i downloaded filezilla and removed the code I had previously  inserted. This code wasn't on or near line 151 where the error was.

The website is sethslawnandgarden
and here is a link to my code pastebin.com/s7ePRE6Q

答:
This error says than your js code incude before jquery library.
try add parameter array('jquery') in
wp_enqueue_script( 'theme-js', get_template_directory_uri() . '/js/main.js', array('jquery') ); or in file (or in  tags) transfer all code to  </p>

```<code>jQuery.noConflict();
(function( $ ) {
//your code
})(jQuery);
</code>```

Title: Trouble for newbie with header code

Body:
This error says than your js code incude before jquery library.
try add parameter array('jquery') in
wp_enqueue_script( 'theme-js', get_template_directory_uri() . '/js/main.js', array('jquery') ); or in file (or in  tags) transfer all code to

jQuery.noConflict();
(function( $ ) {
//your code
})(jQuery);


问:
Class that returns json, python
I have a python class that should return a json, it looks something like this:

```<code>class ScanThis():
    def__init__(self, test):
        data={}
        if test>5:
            data["amount"] = test
            self.json_data = json.dumps(data)
        else:
            data["fail"] = test
            self.json_data = json.dumps(data)

    def __str__(self):
        return self.json_data
</code>```

and I'm trying to call it like so:

```<code>output= json.loads(ScanThis(8))
print(output["command"])
</code>```

But I get this error:

```<code>TypeError: the JSON object must be str, bytes or bytearray, not 'ScanThis'
</code>```

I believe my earlier clas returns an object of type ScanThis() rather than a JSon like I wanted. I just wanted to now how I'd fix this
Thank you

PS: I apologise if this code is rough or invalid, it's not the actual code, just something similar I made up

Update: Again, this isn't the real code, it's just a small basic fragment of the actual code. There's a good reason I'm using a class, and a json is used cause data transfer over the internet is involved

答:
I don't think you are wanting to use a class there at all.
Instead, try using a function that returns a string. For example:

```<code>def scan_this(test):
    data={}
    if test>5:
        data["amount"] = test
        json_data = json.dumps(data)
    else:
        data["fail"] = test
        json_data = json.dumps(data)

    return json_data

output = json.loads(scan_this(8))
</code>```

However!! Now you are just doing extra work for nothing? Why do you need to serialize a python dictionary as a json formatted string, and then load it back into a python dictionary straight away? While you are working with data in python, it's best to keep it as native data types, and only using the json module to either load from a string/file you already have, or serialize to a string/file for storage or transfer (eg sending over the internet).

Title: Class that returns json, python

Body:
I have a python class that should return a json, it looks something like this:

class ScanThis():
    def__init__(self, test):
        data={}
        if test>5:
            data["amount"] = test
            self.json_data = json.dumps(data)
        else:
            data["fail"] = test
            self.json_data = json.dumps(data)

    def __str__(self):
        return self.json_data

and I'm trying to call it like so:

output= json.loads(ScanThis(8))
print(output["command"])

But I get this error:

TypeError: the JSON object must be str, bytes or bytearray, not 'ScanThis'

I believe my earlier clas returns an object of type ScanThis() rather than a JSon like I wanted. I just wanted to now how I'd fix this
Thank you

PS: I apologise if this code is rough or invalid, it's not the actual code, just something similar I made up

Update: Again, this isn't the real code, it's just a small basic fragment of the actual code. There's a good reason I'm using a class, and a json is used cause data transfer over the internet is involved

Body:
I don't think you are wanting to use a class there at all.
Instead, try using a function that returns a string. For example:

def scan_this(test):
    data={}
    if test>5:
        data["amount"] = test
        json_data = json.dumps(data)
    else:
        data["fail"] = test
        json_data = json.dumps(data)

    return json_data

output = json.loads(scan_this(8))

However!! Now you are just doing extra work for nothing? Why do you need to serialize a python dictionary as a json formatted string, and then load it back into a python dictionary straight away? While you are working with data in python, it's best to keep it as native data types, and only using the json module to either load from a string/file you already have, or serialize to a string/file for storage or transfer (eg sending over the internet).


问:
Spring Boot application without the hibernate-validator dependency
I am trying to get spring-boot (spring-boot-starter-web:1.3.5.RELEASE and  spring-boot-starter-validation:1.3.5.RELEASE) working without the hibernate-validator dependency. These are the options I have:

Option 1: Use default OptionalValidatorFactoryBean.

Option 2: Find some other JSR 303 implementation - org.apache.bval:bval-jsr303 or anything else.

I tried option 1, and dependency injection ignores this setup and looks for hibernate-validator and fails:

```<code>@Bean
public org.springframework.validation.Validator validator() {
    return new OptionalValidatorFactoryBean();
}
</code>```

With option 2, I dropped the jar on class-path and dependency injection does not pick the implementation.

It'd be nice to have a working validator flow other than hibernate-validator or, at least provide a dummy validation like option 1.

答:
Adding maven dependencies:

```<code><!-- Bean Validation -->
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>

<dependency>
    <groupId>org.apache.bval</groupId>
    <artifactId>bval-jsr</artifactId>
    <version>1.1.2</version>
</dependency>
</code>```

In action, Spring Boot output:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target MyProperties(prop1=null, ...) failed:

    Property: prop1
    Value: null
    Reason: must not be null

Action:

Update your application's configuration
</code>```

Body:
I am trying to get spring-boot (spring-boot-starter-web:1.3.5.RELEASE and  spring-boot-starter-validation:1.3.5.RELEASE) working without the hibernate-validator dependency. These are the options I have:

Option 1: Use default OptionalValidatorFactoryBean.

Option 2: Find some other JSR 303 implementation - org.apache.bval:bval-jsr303 or anything else.

I tried option 1, and dependency injection ignores this setup and looks for hibernate-validator and fails:

@Bean
public org.springframework.validation.Validator validator() {
    return new OptionalValidatorFactoryBean();
}

With option 2, I dropped the jar on class-path and dependency injection does not pick the implementation.

It'd be nice to have a working validator flow other than hibernate-validator or, at least provide a dummy validation like option 1.

Body:
Adding maven dependencies:

<!-- Bean Validation -->
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>

<dependency>
    <groupId>org.apache.bval</groupId>
    <artifactId>bval-jsr</artifactId>
    <version>1.1.2</version>
</dependency>

In action, Spring Boot output:

***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target MyProperties(prop1=null, ...) failed:

    Property: prop1
    Value: null
    Reason: must not be null

Action:

Update your application's configuration


问:
undefined method `action' for ArticlesController(Table doesn't exist):Class - Ruby on Rails error
I got an error notification but I dont know where to search.
See attachement.

Where's the file with the included error?
I did the following instruction:
http://guides.rubyonrails.org/getting_started.html

Here's my code:

```<code>class ArticlesController < ActiveRecord::Base
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    redirect_to articles_path
  end

  private #description
    def article_params #description
      params.require(:article).permit(:title, :text)
    end #here's the end
end
</code>```

答:
why the controller inherits ActiveRecord?

try changing ArticlesController < ActiveRecord::Base to ArticlesController < ApplicationController

Body:
I got an error notification but I dont know where to search.
See attachement.

Where's the file with the included error?
I did the following instruction:
http://guides.rubyonrails.org/getting_started.html

Here's my code:

class ArticlesController < ActiveRecord::Base
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    redirect_to articles_path
  end

  private #description
    def article_params #description
      params.require(:article).permit(:title, :text)
    end #here's the end
end


问:
Spacing between columns in a table
I have a big problem with the spacing of columns in a table.
Here's what I'd like to get, spacing only between :

Not working with margin, padding  or border:

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td></td>
<td></td>
<td></td>
<td></td></code>```

Not working with border-spacing:

And if use first-child and last-child, same problem as previous image.

Solution I found, but really dirty:

.spacer {
  width: 15px;
  height: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td></td>
<div id="spacer"></div>
<td></td>
<div id="spacer"></div>
<td></td>
<div id="spacer"></div>
<td></td></code>```

答:
1) You must use Standard structure for table when you want work with css on it.

change :

```<code><td></td>
<td></td>
<td></td>
<td></td>
</code>```

To:

```<code><table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</code>```

2) If want space between TDs add border-spacing:30px 0px; to table.

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
  background-color: orange;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}

table {
    border-spacing:30px 0px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
   <tr>
 <td>TD1</td>
 <td>TD2</td>
 <td>TD3</td>
 <td>TD4</td>
   </tr>
</table></code>```

Title: Spacing between columns in a table

Body:
I have a big problem with the spacing of columns in a table.
Here's what I'd like to get, spacing only between :

Not working with margin, padding  or border:

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}

Not working with border-spacing:

And if use first-child and last-child, same problem as previous image.

Solution I found, but really dirty:

.spacer {
  width: 15px;
  height: 15px;
}

Body:
1) You must use Standard structure for table when you want work with css on it.

change :

<td></td>
<td></td>
<td></td>
<td></td>

To:

<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>

2) If want space between TDs add border-spacing:30px 0px; to table.

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
  background-color: orange;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}

table {
    border-spacing:30px 0px;
  }

<table>
   <tr>
 <td>TD1</td>
 <td>TD2</td>
 <td>TD3</td>
 <td>TD4</td>
   </tr>
</table>


问:
C++ How to determine if function has capability for being inlined and actually was?
I have a question about inline functions in C++. I know that similar questions have appeared many times on this. I hope that mine is a little bit different.

I know that when you specify some function to be inline it is just a "suggestion" to the compiler. So in case:

```<code>inline int func1()
{
    return 2;
}
</code>```

Some code later

```<code>cout << func1() << endl; // replaced by cout << 2 << endl;
</code>```

So there is no mystery there, but what about cases like this:

```<code>inline int func1()
{
    return 2;
}

inline int func2()
{
    return func1() * 2;
}

inline int func3()
{
    return func2() * func1() * 2;
}
</code>```

And so on...

Which of these functions have a chance to become inlined, is it benefitial and how to check what compiler actually did?

答:
Think of inline as only a hint to the compiler, a bit like register was in old versions of C++ and C standards. Caveat, register is being obsoleted (in C++17).

Which of these functions have a chance to become inlined, is it benefitial

Trust your compiler on making sane inlining decisions. To enable some particular occurrence of a call, the compiler needs to know the body of the called function. You should not care if the compiler is inlining or not (in theory).

In practice, with the GCC compiler:

inlining is not always improving the performance (e.g. because of CPU cache issues, TLB, branch predictor, etc etc....)

inlining decisions depends a lot on optimization options. It probably is more likely to happen with -O3 than with -O1; there are many guru options (like -finline-limit= and others) to tune it.

notice that individual calls get inlined or not. It is quite possible that some call occurrence like foo(x) at  line 123 is inlined, but another call occurrence (to the same function foo) like foo(y) at some other place like line 456 is not inlined.

when debugging, you may want to disable inlining (because that makes the debugging more convenient). This is possible with the  -fno-inline GCC optimization flag (which I often use with -g, which asks for debugging information).

the always_inline function attribute "forces" inlining, and the noinline prevents it.

if you compile and link with link time optimization (LTO) such as -flto -O2 (or -flto -O3), e.g. with CXX=g++ -flto -O2 in your Makefile, inlining  can happen between several translation units (e.g. C++ source files). However LTO is at least doubling the compilation time (and often, worse) and consumes memory during compilation (so better have a lot of RAM then), and often improve performance by only a few percents (with weird exceptions to this rule of thumb).

you might optimize a function differently, e.g. with #pragma GCC optimize ("-O3") or with function attribute optimize

Look also into profile-guided optimizations with instrumentation options like -fprofile-generate and latter optimizations with -fprofile-use with other optimization flags.

If you are curious about what calls are inlined (and sometimes, some won't be) look into the generated assembler (e.g. use g++ -O2 -S -fverbose-asm and look in the .s assembler file), or use some internal dump options.

The observable behavior of your code (except performance) should not depend upon inlining decisions made by your compiler. In other words, don't expect inlining to happen (or not). If your code behave differently with or without some optimization it is likely to be buggy. So read about undefined behavior.

See also MILEPOST GCC project (using machine learning techniques for optimization purposes).

Body:
I have a question about inline functions in C++. I know that similar questions have appeared many times on this. I hope that mine is a little bit different.

I know that when you specify some function to be inline it is just a "suggestion" to the compiler. So in case:

inline int func1()
{
    return 2;
}

Some code later

cout << func1() << endl; // replaced by cout << 2 << endl;

So there is no mystery there, but what about cases like this:

inline int func1()
{
    return 2;
}

inline int func2()
{
    return func1() * 2;
}

inline int func3()
{
    return func2() * func1() * 2;
}

And so on...

Which of these functions have a chance to become inlined, is it benefitial and how to check what compiler actually did?


问:
how to create borders with bootstrap 3 border class
I use the class border-* of bootstrap, but can't see the borders.
 1. What am I missing ?
 2. Where do I change the thikness of the border ?
 3. Why there is a silght gap, the white spot between the cells in the outcoume result of the following code ?
 4. I used the class rounded-0 and it still seams to be exists, why ?

Thanks un advance for any help.

div {
height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!-- Jquery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- BootStrap -->
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <!-------------------------------------------------------------------------->
    <div class="container-fluid row">
      <h1 class = 'page-header'>
      Why the borders are not visible ?
      </h1>
      <h5>And why the radius box is still rounded if the class is rounded-0 ?</h5>
      <div class='btn btn-primary rounded-0 col-xs-4'></div>
      <div class='btn btn-primary rounded-0 col-xs-4 border-top-0'></div>
      <div class='btn btn-primary rounded-0 col-xs-4 '></div>
      <div class='btn btn-primary rounded-0 col-xs-4 border-left-0'></div>
      <div class='btn btn-primary rounded-0 col-xs-4 '></div>
      <div class='btn btn-primary rounded-0 col-xs-4  border-right-0'></div>
      <div class='btn btn-primary rounded-0 col-xs-4'></div>
      <div class='btn btn-primary rounded-0 col-xs-4 border-bottom-0'></div>
      <div class='btn btn-primary rounded-0 col-xs-4'></div>
     </div></code>```

答:
I just looked in file Bootstrap.css for 'border-top-0', 'border-right-0' ...
Those classes are not given in Bootstrap although it is written in Bootstrap docu.
But maybe you could create those classes by yourself.

for example:

```<code>.border-top-0{
    border-style: solid;
    border-top: none;
}
</code>```

and to set the border width: border-width: 1px;

Body:
I use the class border-* of bootstrap, but can't see the borders.
 1. What am I missing ?
 2. Where do I change the thikness of the border ?
 3. Why there is a silght gap, the white spot between the cells in the outcoume result of the following code ?
 4. I used the class rounded-0 and it still seams to be exists, why ?

Thanks un advance for any help.

div {
height: 50px;
}

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

      Why the borders are not visible ?

And why the radius box is still rounded if the class is rounded-0 ?

Body:
I just looked in file Bootstrap.css for 'border-top-0', 'border-right-0' ...
Those classes are not given in Bootstrap although it is written in Bootstrap docu.
But maybe you could create those classes by yourself.

for example:

.border-top-0{
    border-style: solid;
    border-top: none;
}

and to set the border width: border-width: 1px;


问:
Asp.net server interface with a hardware device?
I've currently developing a web application in asp.net and a smsgateway moderm connected to my server (currently my laptop). is there a way for the asp.net to interface with the moderm that is connected to the server? so i'll be able to send/receive message in a web interface </p>

答: The server-side code can interact with the system just like you can with other applications, as long as the application has the proper permissions to do so.  </p>


问:
C++ "terminating with uncaught exception of type std::out_of_range: vector" error in a merge sort algorithm
I have a c++ code which should use merge sort algorithm to sort a file containing 800,000+ words each on a new line.

What I did ?

To start off, I tried implementing the following merge sort algorithm and tried testing it on a small piece of input. I cannot figure out where I am getting index out of bounds error with the vector. If anyone could help me with this, I would really appreciate

```<code>#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

vector<string> merge(const vector<string>& first,
                     const vector<string>& second) {
    // Write your code to merge vectors first and
    // second onto result.

    vector<string> output;
    int i = 0;
    int j = 0 ;
    int size_first = sizeof(first);
    int size_second = sizeof(second);

    while(i < size_first || j < size_second){
        if (i < size_first && j < size_second){
            if (first.at(i) < second.at(j)){
                output.push_back(first.at(i));
                i++;
            }
            else{
                output.push_back(second.at(i));
                j++;
            }
        }
        else if (i < size_first){
            output.push_back(first.at(i));
            i++;
        }
        else{
            output.push_back(second.at(j));
            j++;
        }

    }
    return output;
}

void mergeSort(vector<string>& words) {
    if (words.size() <= 1)
    {
        return;
    }
    int n = words.size();
    int middle = n/2;

    vector<string> first_half(middle);
    for (int i = 0; i < middle; ++i) {
        first_half[i] = words[i];
    }

    vector<string> second_half(n - middle);
    for (int i = middle; i < n; ++i) {
        second_half[i - middle] = words[i];
    }

    words = merge(first_half, second_half);
}

void sort(vector<string>& words) {

    // Invoke mergeSort  here.
    mergeSort(words);
}

int main(){

    vector<string> names;
    names.push_back("Smith");
    names.push_back("Abinash");
    names.push_back("Ciara");
    names.push_back("Reeta");

    sort(names);

    return 0;

}
</code>```

答:
std::vector has a size() member function that returns the number of  elements in vector. sizeof(first) returns size in bytes of object representation of the type std::vector<string>, and that's not what you need.

```<code> int size_first = sizeof(first);
 int size_second = sizeof(second);
</code>```

Should be replaced with

```<code> int size_first = first.size();
 int size_second = second.size();
</code>```

You have a typo in:

```<code>else {
    output.push_back(second.at(i));
    j++;
}
</code>```

Should be

```<code>    ...
    output.push_back(second.at(j))
</code>```

And another one. You forgot about the main thing - calling mergeSort for the parts before calling merge. Should be:

```<code>mergeSort(first_half);
mergeSort(second_half);
words = merge(first_half, second_half);
</code>```

Body:
I have a c++ code which should use merge sort algorithm to sort a file containing 800,000+ words each on a new line.

What I did ?

To start off, I tried implementing the following merge sort algorithm and tried testing it on a small piece of input. I cannot figure out where I am getting index out of bounds error with the vector. If anyone could help me with this, I would really appreciate

#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

vector<string> merge(const vector<string>& first,
                     const vector<string>& second) {
    // Write your code to merge vectors first and
    // second onto result.

    vector<string> output;
    int i = 0;
    int j = 0 ;
    int size_first = sizeof(first);
    int size_second = sizeof(second);

    while(i < size_first || j < size_second){
        if (i < size_first && j < size_second){
            if (first.at(i) < second.at(j)){
                output.push_back(first.at(i));
                i++;
            }
            else{
                output.push_back(second.at(i));
                j++;
            }
        }
        else if (i < size_first){
            output.push_back(first.at(i));
            i++;
        }
        else{
            output.push_back(second.at(j));
            j++;
        }

    }
    return output;
}

void mergeSort(vector<string>& words) {
    if (words.size() <= 1)
    {
        return;
    }
    int n = words.size();
    int middle = n/2;

    vector<string> first_half(middle);
    for (int i = 0; i < middle; ++i) {
        first_half[i] = words[i];
    }

    vector<string> second_half(n - middle);
    for (int i = middle; i < n; ++i) {
        second_half[i - middle] = words[i];
    }

    words = merge(first_half, second_half);
}

void sort(vector<string>& words) {

    // Invoke mergeSort  here.
    mergeSort(words);
}

int main(){

    vector<string> names;
    names.push_back("Smith");
    names.push_back("Abinash");
    names.push_back("Ciara");
    names.push_back("Reeta");

    sort(names);

    return 0;

}

Body:
std::vector has a size() member function that returns the number of  elements in vector. sizeof(first) returns size in bytes of object representation of the type std::vector<string>, and that's not what you need.

 int size_first = sizeof(first);
 int size_second = sizeof(second);

Should be replaced with

 int size_first = first.size();
 int size_second = second.size();

You have a typo in:

else {
    output.push_back(second.at(i));
    j++;
}

Should be

    ...
    output.push_back(second.at(j))

And another one. You forgot about the main thing - calling mergeSort for the parts before calling merge. Should be:

mergeSort(first_half);
mergeSort(second_half);
words = merge(first_half, second_half);


问:
iOS - How to change app language in storyboard strings without programmatically?
I am developing an app in which an user can change language at any time. I have done this in a demo app. It is working fine. But there is an issue with it, that is for localisation app I have to do following 2 tasks.

Step 1: I have to create IB outlet for every object (i.e in every class ==> buttons, labels, textFields, TextViews).

Step 2 : I have to set language for every objects for example : [myButton setTitle:[Language get:@"Language Test" alter:nil] forState:UIControlStateNormal];
 OR  myLabel.text=LocalizedString(@"Forgot Passoword");

I have a project which has many screens, around 60 screens (in storyboard). Unfortunately in this project there is no IB outlet for all objects. Strings are set in via storyboard. Now I have to make support this app in another language  also (current language english )name Arabic language.

Conclusion : If I do above 2 steps (create IB outlet for every objects
  , then write code in .m file for every object). It will take very much
  time. Is there any other better options please ? I want do not want
  create IB outlet and coding in .m file. Any suggestion will be great!!

What I have done till now :

Follow these tuttorials :

(1).  How to force NSLocalizedString to use a specific language

and sample projects :

(1). https://github.com/tonisalae/TSLanguageManager

(2). https://github.com/object2dot0/Advance-Localization-in-ios-apps

My code :

example calls:

[Language setLanguage:@"it"];

OR

```<code>[Language setLanguage:@"de"];

+(void)initialize {
        NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
        NSArray* languages = [defs objectForKey:@"AppleLanguages"];
        NSString *current = [languages objectAtIndex:0];
        [self setLanguage:current];

    }

        +(void)setLanguage:(NSString *)l {
        NSLog(@"\n\n\t ***** Hint Lang. selected by user: %@   ****\n\n", l);
        NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ];
        bundle = [NSBundle bundleWithPath:path];
    }

        +(NSString *)get:(NSString *)key alter:(NSString *)alternate {
        return [bundle localizedStringForKey:key value:alternate table:nil];
    }
</code>```

答: You can achieve this using User Defined Runtime Attribute. Follow this link for detail.</p>

Body:
I am developing an app in which an user can change language at any time. I have done this in a demo app. It is working fine. But there is an issue with it, that is for localisation app I have to do following 2 tasks.

Step 1: I have to create IB outlet for every object (i.e in every class ==> buttons, labels, textFields, TextViews).

Step 2 : I have to set language for every objects for example : [myButton setTitle:[Language get:@"Language Test" alter:nil] forState:UIControlStateNormal];
 OR  myLabel.text=LocalizedString(@"Forgot Passoword");

I have a project which has many screens, around 60 screens (in storyboard). Unfortunately in this project there is no IB outlet for all objects. Strings are set in via storyboard. Now I have to make support this app in another language  also (current language english )name Arabic language.

Conclusion : If I do above 2 steps (create IB outlet for every objects
  , then write code in .m file for every object). It will take very much
  time. Is there any other better options please ? I want do not want
  create IB outlet and coding in .m file. Any suggestion will be great!!

What I have done till now :

Follow these tuttorials :

(1).  How to force NSLocalizedString to use a specific language

and sample projects :

(1). https://github.com/tonisalae/TSLanguageManager

(2). https://github.com/object2dot0/Advance-Localization-in-ios-apps

My code :

example calls:

[Language setLanguage:@"it"];

OR

[Language setLanguage:@"de"];

+(void)initialize {
        NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
        NSArray* languages = [defs objectForKey:@"AppleLanguages"];
        NSString *current = [languages objectAtIndex:0];
        [self setLanguage:current];

    }

        +(void)setLanguage:(NSString *)l {
        NSLog(@"\n\n\t ***** Hint Lang. selected by user: %@   ****\n\n", l);
        NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ];
        bundle = [NSBundle bundleWithPath:path];
    }

        +(NSString *)get:(NSString *)key alter:(NSString *)alternate {
        return [bundle localizedStringForKey:key value:alternate table:nil];
    }


问:
Twitter Search API - Is it possible to return tweets that aren't truncated?
I am searching for tweets using the Twitter search API, however when a tweet has a line break or two, or is simply too long, the tweet is truncated and ends with '...' (often, but not always followed by a t.co link).

Is it possible to return a tweet's full text from the search API?

答:
Recently Twitter changed how it displays tweets and how they're represented in the API - see https://dev.twitter.com/overview/api/upcoming-changes-to-tweets

You need to add ?tweet_mode=extended to the end of your query.  That will get you back the data you want.


问:
Print character by character of a string
The below code  prints characters till 20th, I want the code to print an error if the string size is more than 20.</p>

```<code>    #include<stdio.h>
    #include<string.h>
    int main()
   {
    int i = 0, l = 0;
    char s[20];
    fgets(s, 30, stdin);
    l = strlen(s);
    if (l < 20)
    {
     for (i = 0; i < l; i++)
    {
     printf("%c\n", s[i]);
    }
    }
    else
    printf("Length of the String exceeds the limit.");
    }
</code>```

答:
Your code contains undefined behaviour if someone enters more that 19 characters. This is because char s[20] reserves 20 characters (including string termination character '\0'). So reading in more than 20 characters using fgets(s,30,stdin) may lead to almost anything, including entering the "wrong" path in the remainder of the program.

Try char s[30] and test your code again.

Body:
The below code  prints characters till 20th, I want the code to print an error if the string size is more than 20.

    #include<stdio.h>
    #include<string.h>
    int main()
   {
    int i = 0, l = 0;
    char s[20];
    fgets(s, 30, stdin);
    l = strlen(s);
    if (l < 20)
    {
     for (i = 0; i < l; i++)
    {
     printf("%c\n", s[i]);
    }
    }
    else
    printf("Length of the String exceeds the limit.");
    }


问:
Submitting multiple form row into table using sql loop
i have collected multiple rows from a student table. and its listing them just fine.

```<code><?php

                    $sql = "SELECT * FROM `students` WHERE `class`='$class' && `academicyear`='$academicyear'";

                    $result = mysqli_query($conn, $sql);
                    if (mysqli_num_rows($result) > 0) {
                        // output data of each row
                        while($row = mysqli_fetch_assoc($result)) {

                    ?>
                                    <tr>
                                      <td><?php echo @++$n ; ?> </td>
                                      <td><?php echo $row["studentid"]?> <input type="text" name="studentid" value="<?php echo $row["studentid"]?>" style="visibility: hidden; width: 10px;"></td>
                                      <td><?php echo $row["fname"]?> &nbsp <?php echo $row["sname"]?> <input type="text" name="name" value="<?php echo $row["fname"]?>  <?php echo $row["sname"]?>" style="visibility: hidden; width: 10px;"></td>
                                      <td style="display: none; width: 10px;"><input type="text" name="class"  value=" <?php echo $class; ?>"> </td>
                                      <td style="display: none; width: 10px;"><input type="text" name="academicyear"  value=" <?php echo $academicyear; ?>"></td>
                                      <td style="display: none; width: 10px;"><input type="text" name="rowcount"  value=" <?php echo $rowcount; ?>"> </td>
                                    </tr>
                           <?php

                        }
                    } else {
                        echo "";
                    }
                    mysqli_close($conn);
                    ?>
</code>```

my difficulty is how to submit this multiple rows into another table called classlist

```<code><?php
// Receiving variables
@$pfw_ip= $_SERVER['REMOTE_ADDR'];
@$example1_length = addslashes($_POST['example1_length']);
@$studentid = addslashes($_POST['studentid']);
@$name = addslashes($_POST['name']);
@$class = addslashes($_POST['class']);
@$academicyear = addslashes($_POST['academicyear']);
@$rowcount = addslashes($_POST['rowcount']);

// Validation
//saving record to MySQL database

@$pfw_host = "localhost";
@$pfw_user = "root";
@$pfw_pw = "";
@$pfw_db = "myschool";
$pfw_link = mysql_connect($pfw_host, $pfw_user, $pfw_pw);
if (!$pfw_link) {
 die('Could not connect: ' . mysql_error());
}
 $pfw_db_selected = mysql_select_db($pfw_db, $pfw_link);
 if (!$pfw_db_selected) {
 die ('Can not use $pfw_db : ' . mysql_error());
 }

 $i=0;
 while ($i<= $rowcount) {
 @$pfw_strQuery = "INSERT INTO `classlist`(`studentid`,`name`,`class`,`academicyear`) VALUES (\"$studentid\",\"$name\",\"$class\",\"$academicyear\")" ;

 $rowcount = $rowcount - 1;
 }

 //insert new record
 $pfw_result = mysql_query($pfw_strQuery);
 if (!$pfw_result) {
 die('Invalid query: ' . mysql_error());
 }

 mysql_close($pfw_link);

 header('location:classlist.php');

?>
</code>```

i only get the last row data submitted into the classlist table then an error appear -- invalid query, duplicate query.

please help.

答:
You must use single quotes to wrap strings in SQL</p>

```<code> @$pfw_strQuery = "INSERT INTO `classlist`(`studentid`,`name`,`class`,`academicyear`) VALUES ('$studentid','$name','$class','$academicyear')" ;
</code>```

Body:
i have collected multiple rows from a student table. and its listing them just fine.

<?php

                    $sql = "SELECT * FROM `students` WHERE `class`='$class' && `academicyear`='$academicyear'";

                    $result = mysqli_query($conn, $sql);
                    if (mysqli_num_rows($result) > 0) {
                        // output data of each row
                        while($row = mysqli_fetch_assoc($result)) {

                    ?>

                                      <?php echo @++$n ; ?>
                                      <?php echo $row["studentid"]?> <input type="text" name="studentid" value="<?php echo $row["studentid"]?>" style="visibility: hidden; width: 10px;">
                                      <?php echo $row["fname"]?> &nbsp <?php echo $row["sname"]?> <input type="text" name="name" value="<?php echo $row["fname"]?>  <?php echo $row["sname"]?>" style="visibility: hidden; width: 10px;">
                                      <input type="text" name="class"  value=" <?php echo $class; ?>">
                                      <input type="text" name="academicyear"  value=" <?php echo $academicyear; ?>">
                                      <input type="text" name="rowcount"  value=" <?php echo $rowcount; ?>">

                           <?php

                        }
                    } else {
                        echo "";
                    }
                    mysqli_close($conn);
                    ?>

my difficulty is how to submit this multiple rows into another table called classlist

<?php
// Receiving variables
@$pfw_ip= $_SERVER['REMOTE_ADDR'];
@$example1_length = addslashes($_POST['example1_length']);
@$studentid = addslashes($_POST['studentid']);
@$name = addslashes($_POST['name']);
@$class = addslashes($_POST['class']);
@$academicyear = addslashes($_POST['academicyear']);
@$rowcount = addslashes($_POST['rowcount']);

// Validation
//saving record to MySQL database

@$pfw_host = "localhost";
@$pfw_user = "root";
@$pfw_pw = "";
@$pfw_db = "myschool";
$pfw_link = mysql_connect($pfw_host, $pfw_user, $pfw_pw);
if (!$pfw_link) {
 die('Could not connect: ' . mysql_error());
}
 $pfw_db_selected = mysql_select_db($pfw_db, $pfw_link);
 if (!$pfw_db_selected) {
 die ('Can not use $pfw_db : ' . mysql_error());
 }

 $i=0;
 while ($i<= $rowcount) {
 @$pfw_strQuery = "INSERT INTO `classlist`(`studentid`,`name`,`class`,`academicyear`) VALUES (\"$studentid\",\"$name\",\"$class\",\"$academicyear\")" ;

 $rowcount = $rowcount - 1;
 }

 //insert new record
 $pfw_result = mysql_query($pfw_strQuery);
 if (!$pfw_result) {
 die('Invalid query: ' . mysql_error());
 }

 mysql_close($pfw_link);

 header('location:classlist.php');

?>

i only get the last row data submitted into the classlist table then an error appear -- invalid query, duplicate query.

please help.

Body:
You must use single quotes to wrap strings in SQL

 @$pfw_strQuery = "INSERT INTO `classlist`(`studentid`,`name`,`class`,`academicyear`) VALUES ('$studentid','$name','$class','$academicyear')" ;


问:
Is there a driver for SQLite in Java?
I did some research on their site, and after some Google-ing, it looks like there are only drivers for C & C++. Is there an open driver that I can use with SQLLite, or is there a way I can use it with JDBC?

UPDATE

I'm doing development on Linux, but I would like to keep my options open. Native libraries would work, but wouldn't give the cross-platform freedom that I'm used to with Java.

答:
SQLite is a native library - therefore a platform independent solution is not that simple. The SQLiteJDBC project uses a internally complex but working system for accessing SQLite database platform independent (on most platform with a good speed). As the name implies it can be used via JDBC (see code sample on the main page).

If you only need one specific platform you can also use the SQLite Java wrapper. For windows there are pre-compiled binaries; sources are also available.

Title: Is there a driver for SQLite in Java?


问:
How Disable Auto-focus of a webcam using opencv
I am trying to calibrate two cameras but my problem is the auto-focus. Im using the webcam logitech c920. Anyone knows a way to disable the auto-focus feature??  Im using C++ and opencv 2.4.9 in osx system.  </p>

答:
You can try this.

```<code>cap = cv2.VideoCapture(1) // Generate camera object
cap.set(cv2.CAP_PROP_AUTOFOCUS, 0) // turn the autofocus off
</code>```

You can find more information on how to set some properties at these links.

The VideoCapture class

http://docs.opencv.org/3.2.0/d8/dfe/classcv_1_1VideoCapture.html

The VideoCapture properties

http://docs.opencv.org/3.2.0/d4/d15/group__videoio__flags__base.html#ga023786be1ee68a9105bf2e48c700294d

Body:
You can try this.

cap = cv2.VideoCapture(1) // Generate camera object
cap.set(cv2.CAP_PROP_AUTOFOCUS, 0) // turn the autofocus off

You can find more information on how to set some properties at these links.

The VideoCapture class

http://docs.opencv.org/3.2.0/d8/dfe/classcv_1_1VideoCapture.html

The VideoCapture properties

http://docs.opencv.org/3.2.0/d4/d15/group__videoio__flags__base.html#ga023786be1ee68a9105bf2e48c700294d


问:
non-numeric argument to binary operator in ggplot
This is driving me crazy... Sorry if it is trivial. I Searched but did not find help. First of all a reproducible example

```<code>df = data.frame(idx = c(1,2,3,4,5), label=c(0,0,1,1,0),
 filter = c(1,1,0,1,1), values = c(0.1, 0.3, 1.2, 1.7, 2.4))

ggplot (df, aes(x = df$idx, y = df$values, size = as.factor(df$label*filter),
color = as.factor(df$label*filter)))+geom_point()+
scale_colour_manual(name = "Duplicates (J/N)", labels = c("Nein", "Ja"),
values = c("red", "blue")) + scale_size_manual(name = "Duplicates (J/N)",
labels = c("Nein", "Ja"), values = c("red", "blue"))
</code>```

When I run this example I get the error

```<code>Error in coords$size * .pt : non-numeric argument to binary Operator
</code>```

Now usually in ggplot you get this error when you got too many + or not enough +. But it does not seem to be the case here. At least is not evident to me.

This is working (without the scale_size_manual)

```<code>ggplot (df, aes(x = df$idx, y = df$values, size = as.factor(df$label*filter),
            color = as.factor(df$label*filter)))+geom_point()+
    scale_colour_manual(name = "Duplicates (J/N)", labels = c("Nein", "Ja"),
                  values = c("red", "blue"))
</code>```

Anyone spot the mistake??

Thanks in advance for the help!

答: It's because the values you are passing to scale_size_manual c("red", "blue") are characters and not numeric values. scale_size requires numeric values. </p>

Body:
This is driving me crazy... Sorry if it is trivial. I Searched but did not find help. First of all a reproducible example

df = data.frame(idx = c(1,2,3,4,5), label=c(0,0,1,1,0),
 filter = c(1,1,0,1,1), values = c(0.1, 0.3, 1.2, 1.7, 2.4))

ggplot (df, aes(x = df$idx, y = df$values, size = as.factor(df$label*filter),
color = as.factor(df$label*filter)))+geom_point()+
scale_colour_manual(name = "Duplicates (J/N)", labels = c("Nein", "Ja"),
values = c("red", "blue")) + scale_size_manual(name = "Duplicates (J/N)",
labels = c("Nein", "Ja"), values = c("red", "blue"))

When I run this example I get the error

Error in coords$size * .pt : non-numeric argument to binary Operator

Now usually in ggplot you get this error when you got too many + or not enough +. But it does not seem to be the case here. At least is not evident to me.

This is working (without the scale_size_manual)

ggplot (df, aes(x = df$idx, y = df$values, size = as.factor(df$label*filter),
            color = as.factor(df$label*filter)))+geom_point()+
    scale_colour_manual(name = "Duplicates (J/N)", labels = c("Nein", "Ja"),
                  values = c("red", "blue"))

Anyone spot the mistake??

Thanks in advance for the help!


问:
How do I auto restart a .sh script every few hours? (Ubuntu 16)
Hi I have a fiveM server running from a run.sh file however I am unsure on how to make the run.sh close and start again every few hours (aka the fiveM server restarts). Anyone know how I would do that?</p>

答:
You should schedule your .sh script using the contrab

https://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800