What's abaut this one:
List<int> tmpList = intArry.ToList();
tmpList.Add(anyInt);
intArry = tmpList.ToArray();
You can try this FLAG_ACTIVITY_REORDER_TO_FRONT
(the document describes exactly what you want to)
The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.
If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.
Conceptually, the simplest regular expressions are literal characters. The pattern N
matches the character 'N'.
Regular expressions next to each other match sequences. For example, the pattern Nick
matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.
If you've ever used grep
on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re
in grep
refers to regular expressions.)
Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick
. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c]
matches either 'a' or 'b' or 'c'.
The pattern .
is special: rather than matching a literal dot only, it matches any character†. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...]
.
Think of character classes as menus: pick just one.
Using .
can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]
. Digits are a frequent match target, so you could instead use the shortcut \d
. Others are \s
(whitespace) and \w
(word characters: alphanumerics or underscore).
The uppercased variants are their complements, so \S
matches any non-whitespace character, for example.
From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c
matches 'abc' or 'ac' because the ?
quantifier makes the subpattern it modifies optional. Other quantifiers are
*
(zero or more times)+
(one or more times){n}
(exactly n times){n,}
(at least n times){n,m}
(at least n times but no more than m times)Putting some of these blocks together, the pattern [Nn]*ick
matches all of
The first match demonstrates an important lesson: *
always succeeds! Any pattern can match zero times.
A few other useful examples:
[0-9]+
(and its equivalent \d+
) matches any non-negative integer\d{4}-\d{2}-\d{2}
matches dates formatted like 2019-01-01A quantifier modifies the pattern to its immediate left. You might expect 0abc+0
to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c
. This means 0abc+0
matches '0abc0', '0abcc0', '0abccc0', and so on.
To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0
. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr
.
Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick
. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |
, e.g., (Nick|nick)
.
For another example, you could equivalently write [a-c]
as a|b|c
, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.
Although some characters match themselves, others have special meanings. The pattern \d+
doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+
. A backslash removes the special meaning from the following character.
Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.
For example, say the input is
"Hello," she said, "How are you?"
You might expect ".+"
to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.
To switch from greedy to what you might think of as cautious, add an extra ?
to the quantifier. Now you understand how \((.+?)\)
, the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.
If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.
(As to your confusion, I don't know of any regular-expression dialect where ((.+?))
would do the same thing. I suspect something got lost in transmission somewhere along the way.)
Use the special pattern ^
to match only at the beginning of your input and $
to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.
Say you want to match comments of the form
-- This is a comment --
you'd write ^--\s+(.+)\s+--$
.
Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.
†: The statement above that .
matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n"
, but in practice you rarely expect a pattern such as .+
to cross a newline boundary. Perl regexes have a /s
switch and Java Pattern.DOTALL
, for example, to make .
match any character at all. For languages that don't have such a feature, you can use something like [\s\S]
to match "any whitespace or any non-whitespace", in other words anything.
git reset is what you want, but I'm going to add a couple extra things you might find useful that the other answers didn't mention.
git reset --hard HEAD
resets your changes back to the last commit that your local repo has tracked. If you made a commit, did not push it to GitHub, and want to throw that away too, see @absiddiqueLive's answer.
git clean -df
will discard any new files or directories that you may have added, in case you want to throw those away. If you haven't added any, you don't have to run this.
git pull
(or if you are using git shell with the GitHub client) git sync
will get the new changes from GitHub.
Edit from way in the future:
I updated my git shell the other week and noticed that the git sync
command is no longer defined by default. For the record, typing git sync
was equivalent to git pull && git push
in bash. I find it still helpful so it is in my bashrc.
There are two main differences from double:
The reason you should use BigDecimal for monetary calculations is not that it can represent any number, but that it can represent all numbers that can be represented in decimal notion and that include virtually all numbers in the monetary world (you never transfer 1/3 $ to someone).
As MadScientist pointed out, you can export individual variables with:
export MY_VAR = foo # Available for all targets
Or export variables for a specific target (target-specific variables):
my-target: export MY_VAR_1 = foo
my-target: export MY_VAR_2 = bar
my-target: export MY_VAR_3 = baz
my-target: dependency_1 dependency_2
echo do something
You can also specify the .EXPORT_ALL_VARIABLES
target to—you guessed it!—EXPORT ALL THE THINGS!!!:
.EXPORT_ALL_VARIABLES:
MY_VAR_1 = foo
MY_VAR_2 = bar
MY_VAR_3 = baz
test:
@echo $$MY_VAR_1 $$MY_VAR_2 $$MY_VAR_3
You can try this VBA program
Option Explicit
Sub CopyWorksheetsFomTemplate()
Dim NewName As String
Dim nm As Name
Dim ws As Worksheet
If MsgBox("Copy specific sheets to a new workbook" & vbCr & _
"New sheets will be pasted as values, named ranges removed" _
, vbYesNo, "NewCopy") = vbNo Then Exit Sub
With Application
.ScreenUpdating = False
' Copy specific sheets
' *SET THE SHEET NAMES TO COPY BELOW*
' Array("Sheet Name", "Another sheet name", "And Another"))
' Sheet names go inside quotes, seperated by commas
On Error GoTo ErrCatcher
Sheets(Array("Sheet1", "Sheet2")).Copy
On Error GoTo 0
' Paste sheets as values
' Remove External Links, Hperlinks and hard-code formulas
' Make sure A1 is selected on all sheets
For Each ws In ActiveWorkbook.Worksheets
ws.Cells.Copy
ws.[A1].PasteSpecial Paste:=xlValues
ws.Cells.Hyperlinks.Delete
Application.CutCopyMode = False
Cells(1, 1).Select
ws.Activate
Next ws
Cells(1, 1).Select
' Remove named ranges
For Each nm In ActiveWorkbook.Names
nm.Delete
Next nm
' Input box to name new file
NewName = InputBox("Please Specify the name of your new workbook", "New Copy")
' Save it with the NewName and in the same directory as original
ActiveWorkbook.SaveCopyAs ThisWorkbook.Path & "\" & NewName & ".xls"
ActiveWorkbook.Close SaveChanges:=False
.ScreenUpdating = True
End With
Exit Sub
ErrCatcher:
MsgBox "Specified sheets do not exist within this workbook"
End Sub
I was having the same issue by using an IF statement to return an unwanted value to "", and the chart would do as you described.
However, when I used #N/A
instead of ""
(important, note that it's without the quotation marks as in #N/A
and not "#N/A"
), the chart ignored the invalid data. I even tried putting in an invalid FALSE
statement and it worked the same, the only difference was #NAME?
returned as the error in the cell instead of #N/A
. I will use a made up IF statement to show you what I mean:
=IF(A1>A2,A3,"")
---> Returned "" into cell when statement is FALSE and plotted on chart
(this is unwanted as you described)
=IF(A1>A2,A3,"#N/A")
---> Returned #N/A as text when statement is FALSE and plotted on chart
(this is also unwanted as you described)
=IF(A1>A2,A3,#N/A)
---> Returned #N/A as Error when statement is FALSE and does not plot on chart (Ideal)
=IF(A1>A2,A3,a)
---> Returned #NAME? as Error when statement is FALSE and does not plot on chart
(Ideal, and this is because any letter without quotations is not a valid statement)
If you want to use this in VBA:
For i = 1 To X
UserForm1.Controls("Label" & i).Caption = MySheet.Cells(i + 1, i).Value
Next
If you want to switch to a specific database on startup, try
/Applications/Postgres.app/Contents/Versions/9.5/bin/psql vigneshdb;
By default, Postgres runs on the port 5432. If it runs on another, make sure to pass the port in the command line.
/Applications/Postgres.app/Contents/Versions/9.5/bin/psql -p2345 vigneshdb;
By a simple alias, we can make it handy.
Create an alias in your .bashrc
or .bash_profile
function psql()
{
db=vigneshdb
if [ "$1" != ""]; then
db=$1
fi
/Applications/Postgres.app/Contents/Versions/9.5/bin/psql -p5432 $1
}
Run psql
in command line, it will switch to default database; psql anotherdb
, it will switch to the db with the name in argument, on startup.
I had the same issue and could fix it with the solution from dougwilson: from Apr 5, 2017, Github.
index.js
to index.pug
'/'
route: res.render('index.pug')
- instead of res.render('index')
DEBUG=express:view
Now it works like a charm.In my case it was the missing .pub
extension of a key. I pasted it from clipboard and saved as mykey
. The following command returned described error:
ssh-copy-id -i mykey localhost
After renaming it with mv mykey mykey.pub
, works correctly.
ssh-copy-id -i mykey.pub localhost
You can also run the follow command to reset the query cache.
RESET QUERY CACHE
This should work for all PHP versions. It determines the PHP version, then checks to see if the session is started based on the PHP version. Then if the session is not started it starts it.
function start_session() {
if(version_compare(phpversion(), "5.4.0") != -1){
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
} else {
if(session_id() == '') {
session_start();
}
}
}
If you are on Windows using SMTP, you can use error_get_last()
when mail()
returns false. Keep in mind this does not work with PHP's native mail() function.
$success = mail('[email protected]', 'My Subject', $message);
if (!$success) {
$errorMessage = error_get_last()['message'];
}
With print_r(error_get_last())
, you get something like this:
[type] => 2
[message] => mail(): Failed to connect to mailserver at "x.x.x.x" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
[file] => C:\www\X\X.php
[line] => 2
You can have an onclick event in the svg itself, I do this all the time in my work. make a rect over the space of your svg, (so define it last, remember svg uses the painters model)
rect.btn {
stroke:#fff;
fill:#fff;
fill-opacity:0;
stroke-opacity:0;
}
then as an attribute to the rect add the onclick (this can be done with js or jquery as well).
<div>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g>
<circle ... //your img svg
<rect class="btn" x="0" y="0" width="10" height="10" onclick="alert('click!')" />
</g>
</svg>
</div>
this will work in most modern browsers, http://caniuse.com/svg ...though if you need cross compatability, you can implement Google Chrome Frame. http://www.google.com/chromeframe
When using MVC, try using ViewBag. The best way to take input from textbox and displaying in View.
You could use the Array.IndexOf method:
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
// the array contains the string and the pos variable
// will have its position in the array
}
Sometimes we need to get the date from a string. One example with grouping:
record = '1518-09-06 00:57 some-alphanumeric-charecter'
pattern_date_time = ([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}) .+
match = re.match(pattern_date_time, record)
if match is not None:
group = match.group()
date = group[0]
print(date) // outputs 1518-09-06 00:57
For people working on PyCharm, and for forcing CPU, you can add the following line in the Run/Debug configuration, under Environment variables:
<OTHER_ENVIRONMENT_VARIABLES>;CUDA_VISIBLE_DEVICES=-1
Try this:
UPDATE data_table t, (SELECT DISTINCT ID, NAME, VALUE
FROM data_table
WHERE VALUE IS NOT NULL AND VALUE != '') t1
SET t.VALUE = t1.VALUE
WHERE t.ID = t1.ID
AND t.NAME = t1.NAME
Set the following registry value:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion!EnableLog] (DWORD) to 1
To disable, set to 0 or delete the value.
[edit ]:Save the following text to a file, e.g FusionEnableLog.reg, in Windows Registry Editor Format:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion]
"EnableLog"=dword:00000001
Then run the file from windows explorer and ignore the warning about possible damage.
Just in case you just need to show a picture in response to a camera request, there is image-to-camera.
Just download, build, install, copy an image of your choice to the device, and you can select it via the app, which is an alternative to the built-in camera.
I am providing the modern answer. The Timestamp
class was always poorly designed, a real hack on top of the already poorly designed Date
class. Both those classes are now long outdated. Don’t use them.
When the question was asked, you would need a Timestamp
for sending a point in time to the SQL database. Since JDBC 4.2 that is no longer the case. Assuming your database needs a timestamp with time zone
(recommended for true timestamps), pass it an OffsetDateTime
.
Before we can do that we need to overcome a real trouble with your sample string, Mon May 27 11:46:15 IST 2013
: the time zone abbreviation. IST
may mean Irish Summer Time, Israel Standard Time or India Standard Time (I have even read that Java may parse it into Atlantic/Reykjavik time zone — Icelandic Standard Time?) To control the interpretation we pass our preferred time zone to the formatter that we are using for parsing.
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("EEE MMM dd HH:mm:ss ")
.appendZoneText(TextStyle.SHORT, Set.of(ZoneId.of("Asia/Kolkata")))
.appendPattern(" yyyy")
.toFormatter(Locale.ROOT);
String dateString = "Mon May 27 11:46:15 IST 2013";
OffsetDateTime dateTime = formatter.parse(dateString, Instant::from)
.atOffset(ZoneOffset.UTC);
System.out.println(dateTime);
This snippet prints:
2013-05-27T06:16:15Z
This is the UTC equivalent of your string (assuming IST was for India Standard Time). Pass the OffsetDateTime
to your database using one of the PreparedStatement.setObject
methods (not setTimestamp
).
How can I convert this into timestamp and calculate in seconds the difference between the same and current time?
Calculating the difference in seconds goes very naturally with java.time:
long differenceInSeconds = ChronoUnit.SECONDS
.between(dateTime, OffsetDateTime.now(ZoneOffset.UTC));
System.out.println(differenceInSeconds);
When running just now I got:
202213260
Link: Oracle tutorial: Date Time explaining how to use java.time.
To elaborate on @serine's answer and illustrate working with non-trivial multi-valued condition: I had a need to show a "dim-out" overlay on an item for the boolean condition NOT a AND (b OR NOT c)
.
For background, this is a "Multiple Choice" question. If the user picks a wrong answer it becomes disabled (dimmed out and cannot be selected again). An automated agent has the ability to focus on any particular choice to give an explanation (border highlighted). When the agent focuses on an item, it should not be dimmed out even if it is disabled. All items that are not in focused are marked de-focused, and should be dimmed out.
The logic for dimming is thus:
NOT IsFocused AND (IsDefocused OR NOT Enabled)
To implement this logic, I made a generic IMultiValueConverter
named (awkwardly) to match my logic
// 'P' represents a parenthesis
// ! a && ( b || ! c )
class NOT_a_AND_P_b_OR_NOT_c_P : IMultiValueConverter
{
// redacted [...] for brevity
public object Convert(object[] values, ...)
{
bool a = System.Convert.ToBoolean(values[0]);
bool b = System.Convert.ToBoolean(values[1]);
bool c = System.Convert.ToBoolean(values[2]);
return !a && (b || !c);
}
...
}
In the XAML I use this in a MultiDataTrigger
in a <Style><Style.Triggers>
resource
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<!-- when the equation is TRUE ... -->
<Condition Value="True">
<Condition.Binding>
<MultiBinding Converter="{StaticResource NOT_a_AND_P_b_OR_NOT_c_P}">
<!-- NOT IsFocus AND ( IsDefocused OR NOT Enabled ) -->
<Binding Path="IsFocus"/>
<Binding Path="IsDefocused" />
<Binding Path="Enabled" />
</MultiBinding>
</Condition.Binding>
</Condition>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<!-- ... show the 'dim-out' overlay -->
<Setter Property="Visibility" Value="Visible" />
</MultiDataTrigger.Setters>
</MultiDataTrigger>
And for completeness sake, my converter is defined in a ResourceDictionary
<ResourceDictionary xmlns:conv="clr-namespace:My.Converters" ...>
<conv:NOT_a_AND_P_b_OR_NOT_c_P x:Key="NOT_a_AND_P_b_OR_NOT_c_P" />
</ResourceDictionary>
there is another simple way to select particular elements in css too...
#s1, #s2, #s3 {
// set css attributes here
}
if you only have a few elements to choose from, and dont want to bother with classes, this will work easily too.
you can use lst.pop()
or del lst[-1]
pop()
removes and returns the item, in case you don't want have a return use del
As per the Newtonsoft Documentation you can also deserialize to an anonymous object like this:
var definition = new { Name = "" };
string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
Console.WriteLine(customer1.Name);
// James
Since Python 3.5 you can use math.isclose()
function for testing approximate equality:
>>> import math
>>> math.isclose(0.1 + 0.2, 0.3)
True
>>> 0.1 + 0.2 == 0.3
False
To perform case-insensitive operations, supply re.IGNORECASE
>>> import re
>>> test = 'UPPER TEXT, lower text, Mixed Text'
>>> re.findall('text', test, flags=re.IGNORECASE)
['TEXT', 'text', 'Text']
and if we want to replace text matching the case...
>>> def matchcase(word):
def replace(m):
text = m.group()
if text.isupper():
return word.upper()
elif text.islower():
return word.lower()
elif text[0].isupper():
return word.capitalize()
else:
return word
return replace
>>> re.sub('text', matchcase('word'), test, flags=re.IGNORECASE)
'UPPER WORD, lower word, Mixed Word'
This question is old, but I wanted to add my two-cents. I read the question as " I want to run a query to my [my]SQL database and store the returned data as Pandas data structure [DataFrame]."
From the code it looks like you mean mysql database and assume you mean pandas DataFrame.
import MySQLdb as mdb
import pandas.io.sql as sql
from pandas import *
conn = mdb.connect('<server>','<user>','<pass>','<db>');
df = sql.read_frame('<query>', conn)
For example,
conn = mdb.connect('localhost','myname','mypass','testdb');
df = sql.read_frame('select * from testTable', conn)
This will import all rows of testTable into a DataFrame.
You're using smart quotes. That is, instead of standard quotation marks ("
), you are using curly quotes (”
). This happens automatically with Microsoft Word and other word processors to make things look prettier, but it also mangles HTML. Make sure to code in a plain text editor, like Notepad or Notepad2.
<html>
<head>
<title>HTML in 10 Simple Steps or Less</title>
<meta http-equiv="refresh" content="5"> <!-- See the difference? -->
</head>
<body>
</body>
</html>
Just my 2 cents regarding the divs option.
Famous/Infamous and SamsaraJS (and possibly others) use absolutely positioned non-nested divs (with non-trivial HTML/CSS content), combined with matrix2d/matrix3d for positioning and 2D/3D transformations, and achieve a stable 60FPS on moderate mobile hardware, so I'd argue against divs being a slow option.
There are plenty of screen recordings on Youtube and elsewhere, of high-performance 2D/3D stuff running in the browser with everything being an DOM element which you can Inspect Element on, at 60FPS (mixed with WebGL for certain effects, but not for the main part of the rendering).
None of the solutions above worked for me because I was using Formik and I needed to mark the field "touched" along with changing the field value. Following code worked for me.
const emailField = orderPageWrapper.find('input[name="email"]')
emailField.simulate('focus')
emailField.simulate('change', { target: { value: '[email protected]', name: 'email' } })
emailField.simulate('blur')
You could use:
echo date('F Y', strtotime('20130814'));
which should do the trick.
Edit: You have a date which is in a string format. To be able to format it nicelt, you first need to change it into a date itself - which is where strtotime comes in. It is a fantastic feature that converts almost any plausible expression of a date into a date itself. Then we can actually use the date() function to format the output into what you want.
Other answers show how to globally configure client certificates. However if you want to programmatically define the client key for one particular connection, rather than globally define it across every application running on your JVM, then you can configure your own SSLContext like so:
String keyPassphrase = "";
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream("cert-key-pair.pfx"), keyPassphrase.toCharArray());
SSLContext sslContext = SSLContexts.custom()
.loadKeyMaterial(keyStore, null)
.build();
HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
HttpResponse response = httpClient.execute(new HttpGet("https://example.com"));
I'm somewhat partial to Jersey. We use 1.10 in all our projects and haven't run into an issue we couldn't solve with it.
Some reasons why I like it:
In truth, HTTPClient and Jersey are very similar in implementation and API. There is also an extension for Jersey that allows it to support HTTPClient.
Some code samples with Jersey 1.x: https://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with
http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/
HTTPClient with Jersey Client: https://blogs.oracle.com/PavelBucek/entry/jersey_client_apache_http_client
Reduce the memory size to Xmx512m and it works.
Some thing like this should also work
import numpy as np
def proper_round(a):
'''
given any real number 'a' returns an integer closest to 'a'
'''
a_ceil = np.ceil(a)
a_floor = np.floor(a)
if np.abs(a_ceil - a) < np.abs(a_floor - a):
return int(a_ceil)
else:
return int(a_floor)
You can try ng-file-upload angularjs plugin (instead of ng-upload).
It's fairly easy to setup and deal with angularjs specifics. It also supports progress, cancel, drag and drop and is cross browser.
html
<!-- Note: MUST BE PLACED BEFORE angular.js-->
<script src="ng-file-upload-shim.min.js"></script>
<script src="angular.min.js"></script>
<script src="ng-file-upload.min.js"></script>
<div ng-controller="MyCtrl">
<input type="file" ngf-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: 'server/upload/url', //upload.php script, node.js route, or servlet url
data: {myObj: $scope.myModelObj},
file: file,
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).then(function(response) {
var data = response.data;
// file is uploaded successfully
console.log(data);
});
}
};
}];
select min(DEPARTMENT.DeptName) as deptname
from DEPARTMENT
inner join employee on
DEPARTMENT.DeptId = employee.DeptId
where Salary > 1000
group by (EmpId) having count(EmpId) > =2
if you have numbers in list, you can use map
to apply str
to each element:
print ', '.join(map(str, LIST))
^ map
is C code so it's faster than str(i) for i in LIST
Place the following after the setContentView() method.
final EditText edit = (EditText) findViewById(R.id.Your_Edit_ID);
String emailString = (String) edit.getText().toString();
Log.d("email",emailString);
Thanks everyone for the answers. Another quick solution will be to use jQuery.param method with traditional parameter set to true to convert JSON object to string:
$.post("/your/url", $.param(yourJsonObject,true));
You can use the following attributes for webkit, which reach into the shadow DOM:
::-webkit-scrollbar { /* 1 */ }
::-webkit-scrollbar-button { /* 2 */ }
::-webkit-scrollbar-track { /* 3 */ }
::-webkit-scrollbar-track-piece { /* 4 */ }
::-webkit-scrollbar-thumb { /* 5 */ }
::-webkit-scrollbar-corner { /* 6 */ }
::-webkit-resizer { /* 7 */ }
Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.
http://jsfiddle.net/hmartiro/Xck2A/1/
Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.
Many of the mentioned examples (e.g. git diff 15dc8^!
, or git diff 15dc8^..15dc8
) don't work if you are using zsh and have extendedglob
option set. You can fix it by one of the following three ways:
unsetopt extendedglob
(and/or remove it from .zshrc)
setopt NO_NOMATCH
(and/or set it in .zshrc)
escape the caret and bang every time with a backslash, e.g. git diff 15dc8\^\!
The @CustID means it's a parameter that you will supply a value for later in your code. This is the best way of protecting against SQL injection. Create your query using parameters, rather than concatenating strings and variables. The database engine puts the parameter value into where the placeholder is, and there is zero chance for SQL injection.
Just make sure build with correct web.xml configuration.I have update web.xml with tomcat configuration and it worked for me. Sample :-
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"_x000D_
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"_x000D_
id="WebApp_ID" version="2.5">_x000D_
<display-name>simulator</display-name>_x000D_
<description>simulator app</description>_x000D_
_x000D_
_x000D_
<!-- File upload -->_x000D_
<welcome-file-list>_x000D_
<welcome-file>index.html</welcome-file>_x000D_
</welcome-file-list>_x000D_
<!-- excel simulation -->_x000D_
<display-name>simulator</display-name>_x000D_
<description>simulator app</description>_x000D_
<!-- File upload -->_x000D_
<welcome-file-list>_x000D_
<welcome-file>InsertPage.html</welcome-file>_x000D_
</welcome-file-list>_x000D_
<servlet>_x000D_
<servlet-name>FileUploadServlet</servlet-name>_x000D_
<servlet-class>clari5.excel.FileUploadServlet</servlet-class>_x000D_
<load-on-startup>1</load-on-startup>_x000D_
</servlet>_x000D_
<servlet-mapping>_x000D_
<servlet-name>FileUploadServlet</servlet-name>_x000D_
<url-pattern>/excelSimulator/FileUploadServlet</url-pattern>_x000D_
</servlet-mapping>_x000D_
_x000D_
_x000D_
_x000D_
</web-app>
_x000D_
The Node.js package is available in the LTS release and the current release. It’s your choice to select which version you want to install on the system as per your requirements.
Use Current Release: At the last update of this tutorial, Node.js 13 is the current Node.js release available.
sudo apt-get install curl
curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash -
Use LTS Release: At the last update of this tutorial, Node.js 12.x is the LTS release available.
sudo apt-get install curl
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
You can successfully add Node.js PPA to the Ubuntu system. Now execute the below command to install Node.js on and Ubuntu using apt-get. This will also install NPM with Node.js. This command also installs many other dependent packages on your system.
sudo apt-get install nodejs
After installing Node.js, verify and check the installed version. You can find more details about the current version on the Node.js official website.
node -v
v13.0.1
Also, check the npm version:
npm -v
6.12.0
Go to firebase console => cloud firestore database and add rule allowing users to read and write.
=> allow read, write
From the Mongo docs:
The
$not
operator only affects other operators and cannot check fields and documents independently. So, use the$not
operator for logical disjunctions and the$ne
operator to test the contents of fields directly.
Since you are testing the field directly $ne
is the right operator to use here.
Edit:
A situation where you would like to use $not
is:
db.inventory.find( { price: { $not: { $gt: 1.99 } } } )
That would select all documents where:
You can use the following flags --single-branch
&& --depth
to download the specific branch and to limit the amount of history which will be downloaded.
You will clone the repo from a certain point in time and only for the given branch
git clone -b <branch> --single-branch <url> --depth <number of commits>
--[no-]single-branch
Clone only the history leading to the tip of a single branch, either specified by the
--branch
option or the primary branch remote’sHEAD
points at.Further fetches into the resulting repository will only update the
remote-tracking
branch for the branch this option was used for the initial cloning. If the HEAD at the remote did not point at any branch when--single-branch
clone was made, no remote-tracking branch is created.
--depth
Create a shallow clone with a history truncated to the specified number of commits
I try lots of ways and finally try this:
def db_persist(func):
def persist(*args, **kwargs):
func(*args, **kwargs)
try:
session.commit()
logger.info("success calling db func: " + func.__name__)
return True
except SQLAlchemyError as e:
logger.error(e.args)
session.rollback()
return False
return persist
and :
@db_persist
def insert_or_update(table_object):
return session.merge(table_object)
To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:
Open Source:
Paid:
** - means I didn't try those so I can't really recommend it but other users suggested it..
For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);
If you want it to download and install from your own server then use the following code
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
startActivity(intent);
As was mentioned "".join(set(foo)) and collections.OrderedDict will do. A added foo = foo.lower() in case the string has upper and lower case characters and you need to remove ALL duplicates no matter if they're upper or lower characters.
from collections import OrderedDict
foo = "EugeneEhGhsnaWW"
foo = foo.lower()
print "".join(OrderedDict.fromkeys(foo))
prints eugnhsaw
If you don't want to deal with security and want to make it as exposed (aka "convenient") as possible for short term, and|or don't have ssh/telnet or key generation on all your hosts, you can can hack a one-liner together with netcat. Write a command to your target computer's port over the network and it will run it. Then you can block access to that port to a few "trusted" users or wrap it in a script that only allows certain commands to run. And use a low privilege user.
mkfifo /tmp/netfifo; nc -lk 4201 0</tmp/netfifo | bash -e &>/tmp/netfifo
This one liner reads whatever string you send into that port and pipes it into bash to be executed. stderr & stdout are dumped back into netfifo and sent back to the connecting host via nc.
To run a command remotely:
echo "ls" | nc HOST 4201
$('div').attr('class', function(i, c){
return c.replace(/(^|\s)color-\S+/g, '');
});
This page explains it pretty well.
As a numeric
the allowable range that can be stored in that field is -10^38 +1
to 10^38 - 1
.
The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.
The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.
So the range that can be stored in this particular field is -(10^18 - 1)
to (10^18 - 1)
Or -999999999999999999
to 999999999999999999
Integers only
For those like @sha1 wondering why the OP's code doesn't work -
OP's logic for deleting player at server side is in the handler for DelPlayer
event,
and the code that emits this event (DelPlayer
) is in inside disconnected
event callback of client.
The server side code that emits this disconnected
event is inside the disconnect
event callback which is fired when the socket loses connection. Since the socket already lost connection, disconnected
event doesn't reach the client.
Accepted solution executes the logic on disconnect
event at server side, which is fired when the socket disconnects, hence works.
Have you tried gdb -w with cygwin gdb. It is supossed to have a windows interface which works fairly well.
The only problem I found is that on my present machine it didn't run that way until after I installed ddd. I suspect that it requires tcltk which was installed when I installed ddd.
I am a pragmatist, so I will try to look at this in terms of costs and benefits.
Note that for any disadvantage I give, I recognize that they are solvable. That's why I don't look at anything as black and white, but rather, costs and benefits.
Advantages
Disadvantages
Again, I recognize that every one of these problems is solvable, at some cost. But there comes a point where you are spending all your time solving problems which you could have just avoided in the first place. It comes back to the benefits and how important they are to you.
On some mobiles like mine (MIUI Redmi 3) you can just add specific Application on list where application doesnt stop when you terminate applactions in Task Manager (It will stop but it will start again)
Just go to Settings>PermissionsAutostart
As others have mentioned, comments are referenced with a #
and are documented here. However, unlike some languages, the #
must be at the beginning of the line. If they occur part way through the line, they are interpreted as an argument and may result in unexpected behavior.
# This is a comment
COPY test_dir target_dir # This is not a comment, it is an argument to COPY
RUN echo hello world # This is an argument to RUN but the shell may ignore it
It should also be noted that parser directives have recently been added to the Dockerfile which have the same syntax as a comment. They need to appear at the top of the file, before any other comments or commands. Originally, this directive was added for changing the escape character to support Windows:
# escape=`
FROM microsoft/nanoserver
COPY testfile.txt c:\
RUN dir c:\
The first line, while it appears to be a comment, is a parser directive to change the escape character to a backtick so that the COPY
and RUN
commands can use the backslash in the path. A parser directive is also used with BuildKit to change the frontend parser with a syntax
line. See the experimental syntax for more details on how this is being used in practice.
With a multi-line command, the commented lines are ignored, but you need to comment out every line individually:
$ cat Dockerfile
FROM busybox:latest
RUN echo first command \
# && echo second command disabled \
&& echo third command
$ docker build .
Sending build context to Docker daemon 23.04kB
Step 1/2 : FROM busybox:latest
---> 59788edf1f3e
Step 2/2 : RUN echo first command && echo third command
---> Running in b1177e7b563d
first command
third command
Removing intermediate container b1177e7b563d
---> 5442cfe321ac
Successfully built 5442cfe321ac
In SQL, a comparison between a null
value and any other value (including another null
) using a comparison operator (eg =
, !=
, <
, etc) will result in a null
, which is considered as false
for the purposes of a where clause (strictly speaking, it's "not true", rather than "false", but the effect is the same).
The reasoning is that a null
means "unknown", so the result of any comparison to a null
is also "unknown". So you'll get no hit on rows by coding where my_column = null
.
SQL provides the special syntax for testing if a column is null
, via is null
and is not null
, which is a special condition to test for a null
(or not a null
).
Here's some SQL showing a variety of conditions and and their effect as per above.
create table t (x int, y int);
insert into t values (null, null), (null, 1), (1, 1);
select 'x = null' as test , x, y from t where x = null
union all
select 'x != null', x, y from t where x != null
union all
select 'not (x = null)', x, y from t where not (x = null)
union all
select 'x = y', x, y from t where x = y
union all
select 'not (x = y)', x, y from t where not (x = y);
returns only 1 row (as expected):
TEST X Y
x = y 1 1
See this running on SQLFiddle
I would do it like this:
SELECT top(100)* into #tmpFerdeen
FROM Customers
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerEurope
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAsia
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAmericas
int main()
{
char buff[1024] = {0};
FILE* cvt;
int status;
/* Launch converter and open a pipe through which the parent will write to it */
cvt = popen("converter", "w");
if (!cvt)
{
printf("couldn't open a pipe; quitting\n");
exit(1)
}
printf("enter Fahrenheit degrees: " );
fgets(buff, sizeof (buff), stdin); /*read user's input */
/* Send expression to converter for evaluation */
fprintf(cvt, "%s\n", buff);
fflush(cvt);
/* Close pipe to converter and wait for it to exit */
status=pclose(cvt);
/* Check the exit status of pclose() */
if (!WIFEXITED(status))
printf("error on closing the pipe\n");
return 0;
}
The important steps in this program are:
popen()
call which establishes the association between a child process and a pipe in the parent.fprintf()
call that uses the pipe as an ordinary file to write to the child process's stdin or read from its stdout.pclose()
call that closes the pipe and causes the child process to terminate.Just as others said, you can perform a case sensitive search. Or just change the collation format of a specified column as me. For the User/Password columns in my database I change them to collation through the following command:
ALTER TABLE `UserAuthentication` CHANGE `Password` `Password` VARCHAR(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL;
run "export TEMPDIR=/someDir" where some dir is a valid directory other than /tmp. Run this on prompt before running your python command. In my case it is "pip install rasa[spacy]" which was earlier failing.
The export command allows you to temporarily use the specified dir as temp dir.
They serve different purposes. clear()
clears an instance of the class, removeAll()
removes all the given objects and returns the state of the operation.
Check your apache error log. I had this error "[error] (OS 5)Access is denied. : could not open transfer log file C:/wamp/logs/access.log. Unable to open logs" Then I rename my "access.log" to other name, you can delete if you don't need/never see your access log. Then restart your apache service. This happen because the file size too big. I think if you trying to open this file using notepad, it will not open, I tried to open that before. Hope it help.
stdout
is the standard output stream in UNIX. See http://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#Standard-Streams.
When running in a terminal, you will see data written to stdout
in the terminal and you can redirect it as you choose.
There are two options. Ayman's approach is the most simple, but I would add one extra note to it. You should really cache jQuery selections, there is no reason to call $("#input-field-id")
twice:
var input = $( "#input-field-id" );
input.val( input.val() + "more text" );
The other option, .val()
can also take a function as an argument. This has the advantange of easily working on multiple inputs:
$( "input" ).val( function( index, val ) {
return val + "more text";
});
since PHP 5.4 you can use http_response_code()
for get and set header status code.
here an example:
<?php
// Get the current response code and set a new one
var_dump(http_response_code(404));
// Get the new response code
var_dump(http_response_code());
?>
here is the document of this function in php.net:
With LINQ, you could use the SkipWhile
/ TakeWhile
methods, like this:
var importantLines =
File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.TakeWhile(line => !line.Contains("CustomerCh"));
That's a good question, but I think you just misunderstand what you read.
The ./config --with-pdo-mysql
is something you have to put on only if you compile your own PHP code. If you install it with package managers, you just have to use the command line given by Jany Hartikainen: sudo apt-get install php5-mysql
and also sudo apt-get install pdo-mysql
Apart from the fact mysql_ is really discouraged, they are both independent. If you use PDO mysql_ is not implicated, and if you use mysql_ PDO is not required.
If you turn off PDO without changing any line in your code, you won't have a problem. But since you started to connect and write queries with PDO, you have to keep it and give up mysql_.
Several years ago the MySQL team published a script to migrate to MySQLi. I don't know if it can be customised, but it's official.
In case if you post SOAP message you need to use raw body parser:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.raw({ type: 'text/xml' }));
First of all, you can't pass to alert
second argument, use concatenation instead
alert("Input is " + inputValue);
However in order to get values from input better to use states like this
var MyComponent = React.createClass({_x000D_
getInitialState: function () {_x000D_
return { input: '' };_x000D_
},_x000D_
_x000D_
handleChange: function(e) {_x000D_
this.setState({ input: e.target.value });_x000D_
},_x000D_
_x000D_
handleClick: function() {_x000D_
console.log(this.state.input);_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<input type="text" onChange={ this.handleChange } />_x000D_
<input_x000D_
type="button"_x000D_
value="Alert the text input"_x000D_
onClick={this.handleClick}_x000D_
/>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
<MyComponent />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
Sort by picture and then by activity:
SELECT some_cols
FROM `prefix_users`
WHERE (some conditions)
ORDER BY pic_set, last_activity DESC;
Use Bootstrap FileStyle, which is used to style the file fields of forms. It is a plugin for a jQuery-based component library called Twitter Bootstrap
Sample usage:
Include:
<script type="text/javascript" src="js/bootstrap-filestyle.min.js"> </script>
Via JavaScript:
$(":file").filestyle();
Via data attributes:
<input type="file" class="filestyle" data-classButton="btn btn-primary" data-input="false" data-classIcon="icon-plus" data-buttonText="Your label here.">
My answer directly inspired from @valex very usefull, if you need several cols in the ORDER BY clause.
SELECT u.*
FROM users AS u
INNER JOIN (
SELECT p.*,
@num := if(@id = user_id, @num + 1, 1) as row_number,
@id := user_id as tmp
FROM (SELECT * FROM payments ORDER BY p.user_id ASC, date DESC) AS p,
(SELECT @num := 0) x,
(SELECT @id := 0) y
)
ON (p.user_id = u.id) and (p.row_number=1)
WHERE u.package = 1
To install android component do following steps
Fetching https://dl-ssl.google.com/android/repository/addons_list-2.xml
Fetched Add-ons List successfully
Fetching URL: https://dl-ssl.google.com/android/repository/repository-7.xml
Validate XML: https://dl-ssl.google.com/android/repository/repository-7.xml
Parse XML: https://dl-ssl.google.com/android/repository/repository-7.xml
https://dl-ssl.google.com/android/repository/addons_list-2.xml is main xml file where all other package list is available.
lets say you want to download platform api-9 and it is available on repository-7 then you have to do following steps
note the repository address and go to any other machine which has internet connection and type following link in any browser
https://dl-ssl.google.com/android/repository/repository-7.xml
Search for <sdk:url>**android-2.3.1_r02-linux.zip**</sdk:url>
under the api version which you want to download. This is the file name which you have to download. to download this file you have to type following URI in any downloader or browser and it will start download the file.
http://dl-ssl.google.com/android/repository/android-2.3.3_r02-linux.zip
General rule for any file replace android-2.3.3_r02-linux.zip with your package name
Once the download is complete,paste downloaded ZIP(or other format for other os) file in your flash/pen drive and paste the zip file at <android sdk dir>/temp
(ex:- c:\android-sdk\temp
) folder/directory in your offline machine.
Now start the SDK manager and select the package which you have paste in temp and click Install package button. Your package has been installed.
Restart your eclipse and AVD manager to get new packages.
Note:- if you are downloading sdk-tools or sdk platform-tools then choose the package for OS which is on offline machine(windows/Linux/Mac).
A more optimized way in mysql for this purpose*:
SELECT columnName DIV 1 AS columnName, moreColumns, etc
FROM myTable
WHERE ...
Using DIV 1 is a huge speed improvement over FLOOR, not to mention string based functions like FORMAT
mysql> SELECT BENCHMARK(10000000,1234567 DIV 7) ;
+-----------------------------------+
| BENCHMARK(10000000,1234567 DIV 7) |
+-----------------------------------+
| 0 |
+-----------------------------------+
1 row in set (0.83 sec)
mysql> SELECT BENCHMARK(10000000,1234567 / 7) ;
+---------------------------------+
| BENCHMARK(10000000,1234567 / 7) |
+---------------------------------+
| 0 |
+---------------------------------+
1 row in set (7.26 sec)
mysql> SELECT BENCHMARK(10000000,FLOOR(1234567 / 7)) ;
+----------------------------------------+
| BENCHMARK(10000000,FLOOR(1234567 / 7)) |
+----------------------------------------+
| 0 |
+----------------------------------------+
1 row in set (8.80 sec)
(*) NOTE: As pointed by Grbts, be aware of the behaviour of DIV 1 when used with non unsigned/positive values.
As android doesn't support such a thing, you can do it manually with FontCreator. It has good options for font modifying. I used this tool to build a custom font, even if it takes some times but you can always use it in your projects.
The main
function can have two parameters, argc
and argv
. argc
is an integer (int
) parameter, and it is the number of arguments passed to the program.
The program name is always the first argument, so there will be at least one argument to a program and the minimum value of argc
will be one. But if a program has itself two arguments the value of argc
will be three.
Parameter argv
points to a string array and is called the argument vector. It is a one dimensional string array of function arguments.
alias testcases="sed -n 's/func.*\(Test.*\)(.*/\1/p' | xargs | sed 's/ /|/g'"
go test -v -run $(cat coordinator_test.go | testcases)
Install PAR::Packer
. Example for *nix:
sudo cpan -i PAR::Packer
For Strawberry Perl for Windows or for ActivePerl and MSVC installed:
cpan -i PAR::Packer
Pack it with pp
. It will create an executable named "example" or "example.exe" on Windows.
pp -o example example.pl
This would work only on the OS where it was built.
P.S. It is really hard to find a Unix clone without Perl. Did you mean Windows?
Linux (Ubuntu 14.04)
As mentioned, try to kill ipython notebook processes properly by first going to the "running" tab in your ipynb/jupyter browser session, and then check open terminals on your console and shut down with ctrl-c. The latter should be avoided if possible.
If you run an ipython notebook list
and continue to see running ipython servers at different ports, make note of which ports the existing notebooks are being served to. Then shut down your TCP ports:
fuser -k 'port#'/tcp
I'm not sure if there are other risks involved with doing this. If so, let me know.
In pom.xml file of the project,
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>X.X.X.RELEASE</version>
<relativePath> ../PROJECTNAME/pom.xml</relativePath>
</parent>
Pointing relativepath to the same MAVEN project POM file solved the issue for me.
There is a lot of confusion about Repositories and Projects. In the past both terms were used pretty much interchangeably by the users and the GitHub's very own documentation. This is reflected by some of the answers and comments here that explain the subtle differences between those terms and when the one was preferred over the other. The difference were always subtle, e.g. like the issue tracker being part of the project but not part of the repository which might be thought of as a strictly git thing etc.
Currently repos and projects refer to a different kinds of entities that have separate APIs:
Since then it is no longer correct to call the repo a project or vice versa. Note that it is often confused in the official documentation and it is unfortunate that a term that was already widely used has been chosen as the name of the new entity but this is the case and we have to live with that.
The consequence is that repos and projects are usually confused and every time you read about GitHub projects you have to wonder if it's really about the projects or about repos. Had they chosen some other name or an abbreviation like "proj" then we could know that what is discussed is the new type of entity, a precise object with concrete properties, or a general speaking repo-like projectish kind of thingy.
The term that is usually unambiguous is "project board".
The first endpoint in the documentation of the Projects API:
is described as: List repository projects. It means that a repository can have many projects. So those two cannot mean the same thing. It includes Response if projects are disabled:
{
"message": "Projects are disabled for this repo",
"documentation_url": "https://developer.github.com/v3"
}
which means that some repos can have projects disabled. Again, those cannot be the same thing when a repo can have projects disabled.
There are some other interesting endpoints:
POST /repos/:owner/:repo/projects
POST /orgs/:org/projects
but there is no:
POST /users/:user/projects
Which leads us to another difference:
1. Repositories can belong to users or organizations
2. Projects can belong to repositories or organizations
or, more importantly:
1. Projects can belong to repositories but not the other way around
2. Projects can belong to organizations but not to users
3. Repositories can belong to organizations and to users
See also:
I know it's confusing. I tried to explain it as precisely as I could.
for a = 1 to 100 step 1
Command line in Windows . Please use %%a if running in Batch file.
for /L %a in (1,1,100) Do echo %a
BCL provided Convert.ToString(n, 2)
is good, but in case you need an alternate implementation which is few ticks faster than BCL provided one.
Following custom implementation works for all integers(-ve and +ve). Original source taken from https://davidsekar.com/algorithms/csharp-program-to-convert-decimal-to-binary
static string ToBinary(int n)
{
int j = 0;
char[] output = new char[32];
if (n == 0)
output[j++] = '0';
else
{
int checkBit = 1 << 30;
bool skipInitialZeros = true;
// Check the sign bit separately, as 1<<31 will cause
// +ve integer overflow
if ((n & int.MinValue) == int.MinValue)
{
output[j++] = '1';
skipInitialZeros = false;
}
for (int i = 0; i < 31; i++, checkBit >>= 1)
{
if ((n & checkBit) == 0)
{
if (skipInitialZeros)
continue;
else
output[j++] = '0';
}
else
{
skipInitialZeros = false;
output[j++] = '1';
}
}
}
return new string(output, 0, j);
}
Above code is my implementation. So, I'm eager to hear any feedback :)
I think the easiest way to accomplish it is to use querystring instead of HTTP headers.
prefer to use "set colsep" in sqlplus prompt instead of editing col name one by one. Use sed to edit the output file.
set colsep '","' -- separate columns with a comma
sed 's/^/"/;s/$/"/;s/\s *"/"/g;s/"\s */"/g' $outfile > $outfile.csv
If you are using C++11, and wish to move the elements rather than merely copying them, you can use std::move_iterator
along with insert (or copy):
#include <vector>
#include <iostream>
#include <iterator>
int main(int argc, char** argv) {
std::vector<int> dest{1,2,3,4,5};
std::vector<int> src{6,7,8,9,10};
// Move elements from src to dest.
// src is left in undefined but safe-to-destruct state.
dest.insert(
dest.end(),
std::make_move_iterator(src.begin()),
std::make_move_iterator(src.end())
);
// Print out concatenated vector.
std::copy(
dest.begin(),
dest.end(),
std::ostream_iterator<int>(std::cout, "\n")
);
return 0;
}
This will not be more efficient for the example with ints, since moving them is no more efficient than copying them, but for a data structure with optimized moves, it can avoid copying unnecessary state:
#include <vector>
#include <iostream>
#include <iterator>
int main(int argc, char** argv) {
std::vector<std::vector<int>> dest{{1,2,3,4,5}, {3,4}};
std::vector<std::vector<int>> src{{6,7,8,9,10}};
// Move elements from src to dest.
// src is left in undefined but safe-to-destruct state.
dest.insert(
dest.end(),
std::make_move_iterator(src.begin()),
std::make_move_iterator(src.end())
);
return 0;
}
After the move, src's element is left in an undefined but safe-to-destruct state, and its former elements were transfered directly to dest's new element at the end.
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
Instance variables or fields, along with static variables, are assigned default values based on the variable type:
0
\u0000
or 0
0.0
false
null
Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.
select field1, field2, 'example' as TempField
from table1
This should work across different SQL implementations.
MATLAB is a popular and widely adapted piece of a sophisticated software package. It'd be a mistake to think it's merely a math software since it has a wide range of "toolboxes". I recently used Matplotlib to plot some data from a database and it did the job without needing all the bells and whistles of MATLAB. However, it may not be proper to compare Python and MATLAB in every situation. As with everything else the decision depends on what you need to do.
I used MATLAB in undergrad for control systems design and simulation and also for image processing in grad school. For these fields MATLAB makes the most sense because of the powerful control and image processing toolboxes. As everyone mentioned, array operations, which are used in every MATLAB script you'd need to write, are very easy with MATLAB.
Another nice thing about MATLAB is that it's very easy and fast to do prototyping and trying out ideas using the built in toolbox functions. For instance, it takes no effort to import an image and compute it's histogram or do some simple processing on it. One disadvantage of MATLAB could be it's speed because of its interpreted nature. However, if one really needs speed than he can choose to implement the tested logic in C/C++, etc.
For further comparison with Python, I can say that MATLAB provides a full package for you to do your work without the need of looking around for external libraries and implementing extra functions.
One last point about MATLAB which I see is not mentioned in the answers here is that it has a very powerful visual modeling/simulation environment called Simulink. It's easier to design and simulate larger systems with Simulink.
Finally, again, it all depends on the problem you need to solve. If your problem domain can make use of one of MATLAB's toolboxes and you have access to MATLAB then you can be sure that you'll have the right tool to solve it.
It sets the default collation for the table; if you create a new column, that should be collated with latin_general_ci -- I think. Try specifying the collation for the individual column and see if that works. MySQL has some really bizarre behavior in regards to the way it handles this.
Set your HTML as
<div id="body" hidden="">
<h1>Numbers</h1>
</div>
<div id="body1" hidden="hidden">
Body 1
</div>
And now set the javascript as
function changeDiv()
{
document.getElementById('body').hidden = "hidden"; // hide body div tag
document.getElementById('body1').hidden = ""; // show body1 div tag
document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked";
// display text if JavaScript worked
}
Check, it works.
Use the following code:
df.column_name = df.column_name.astype('str')
Without lambda:
def sec_elem(s):
return s[1]
sorted(data, key=sec_elem)
You can have whichever children that you want to have the same state as the parents include android:duplicateParentState="true". Then if you disable the parent, whatever children you have that set on will follow suit.
This will allow you to dynamically control all states at once from the parent view.
<LinearLayout
android:id="@+id/some_parent_something"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:duplicateParentState="true"/>
<LinearLayout
android:id="@+id/my_layout"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:duplicateParentState="true">
<TextView
android:id="@+id/my_text_view"
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:duplicateParentState="true" />
<EditText
android:id="@+id/my_edit_view"
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:duplicateParentState="true" />
<View .../>
<View .../>
...
<View .../>
</LinearLayout>
</LinearLayout>
If you have multiple sections, here's how to get the last row in the last section (Swift 3):
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let visibleRows = tableView.indexPathsForVisibleRows, let lastRow = visibleRows.last?.row, let lastSection = visibleRows.map({$0.section}).last {
if indexPath.row == lastRow && indexPath.section == lastSection {
// Finished loading visible rows
}
}
}
you want fix it can edit file "/Applications/XAMPP/xamppfiles/xampp" with TextEdit.
Look for text "$XAMPP_ROOT/bin/mysql.server start > /dev/null &"
And add "unset DYLD_LIBRARY_PATH" on top of it. It should look like:
unset DYLD_LIBRARY_PATH
$XAMPP_ROOT/bin/mysql.server start > /dev/null &
hope can help you
Just adding my solution to this issue. I was uploading a .xlsx file to the webserver, then reading from it and bulk inserting to SQL Server. Was getting this same error message, tried all the suggested answers but none worked. Eventually I saved the file as excel 97-2003 (.xls) which worked... only issue I have now is that the original file had 110,000+ rows.
Marked anwser is perfect but it misses character 127(DEL) which is also a non-printable character
my answer would be
$string = preg_replace('/[\x00-\x1F\x7f-\xFF]/', '', $string);
baseKey choice;
if (Enum.TryParse("HKEY_LOCAL_MACHINE", out choice)) {
uint value = (uint)choice;
// `value` is what you're looking for
} else { /* error: the string was not an enum member */ }
Before .NET 4.5, you had to do the following, which is more error-prone and throws an exception when an invalid string is passed:
(uint)Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE")
Here is @germanattanasio 's working method, written for Swift 3
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.imageView?.image = myImage
let itemSize = CGSize(width:42.0, height:42.0)
UIGraphicsBeginImageContextWithOptions(itemSize, false, 0.0)
let imageRect = CGRect(x:0.0, y:0.0, width:itemSize.width, height:itemSize.height)
cell.imageView?.image!.draw(in:imageRect)
cell.imageView?.image! = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
}
Do a row div.
Like this:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
<div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
</div>_x000D_
</div>
_x000D_
If you're facing this problem when unit testing with @DataJpaTest
then you'll find the solution below.
Spring boot do not initialize @Repository
beans for @DataJpaTest
. So try one of the two fix below to have them available:
First
Use @SpringBootTest
instead. But this will boot up the whole application context.
Second(Better solutions)
Import the specific repository you need, like below
@DataJpaTest
@Import(MyRepository.class)
public class MyRepositoryTest {
@Autowired
private MyRepository myRepository;
indexPathForRow
is a class method!
The code should read:
NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:0] ;
To delete folder having files, no need of loops or recursive search. You can directly use:
FileUtils.deleteDirectory(<File object of directory>);
This function will directory delete the folder and all files in it.
I believe your 1:m relationships should already implicitly create DISTINCT JOINs.
But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.
SELECT DISTINCT a.valueA, c.valueC
FROM C
INNER JOIN B ON B.lookupC = C.id
INNER JOIN A ON A.lookupB = B.id
ORDER BY a.valueA, c.valueC
All has been pointed out. Just use either DELETE ON CASCADE
on the parent table
or delete from the child-table
and then parent
.
If []byte is ASCII byte numbers then first convert the []byte to string and use the strconv
package Atoi
method which convert string to int.
package main
import (
"fmt"
"strconv"
)
func main() {
byteNumber := []byte("14")
byteToInt, _ := strconv.Atoi(string(byteNumber))
fmt.Println(byteToInt)
}
go playground - https://play.golang.org/p/gEzxva8-BGP
To clarify what Gillian said about 4 string, if you have something like this:
string a,b,c,d;
a = b + c + d;
then it would be faster using strings and the plus operator. This is because (like Java, as Eric points out), it internally uses StringBuilder automatically (Actually, it uses a primitive that StringBuilder also uses)
However, if what you are doing is closer to:
string a,b,c,d;
a = a + b;
a = a + c;
a = a + d;
Then you need to explicitly use a StringBuilder. .Net doesn't automatically create a StringBuilder here, because it would be pointless. At the end of each line, "a" has to be an (immutable) string, so it would have to create and dispose a StringBuilder on each line. For speed, you'd need to use the same StringBuilder until you're done building:
string a,b,c,d;
StringBuilder e = new StringBuilder();
e.Append(b);
e.Append(c);
e.Append(d);
a = e.ToString();
Try use it:
Uri uri = Uri.fromFile(entry);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
String mime = "*/*";
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
if (mimeTypeMap.hasExtension(
mimeTypeMap.getFileExtensionFromUrl(uri.toString())))
mime = mimeTypeMap.getMimeTypeFromExtension(
mimeTypeMap.getFileExtensionFromUrl(uri.toString()));
intent.setDataAndType(uri,mime);
startActivity(intent);
Another solution if you don't want to modify your settings:
Download jms-1.1.jar from JBoss repository then:
mvn install:install-file -DgroupId=javax.jms -DartifactId=jms -Dversion=1.1 -Dpackaging=jar -Dfile=jms-1.1.jar
VBA is not VB/VB.NET
The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:
Do While counter < 20
counter = counter + 1
Loop
(But a For..Next might be more appropriate here.)
Happy coding.
call msbuild.bat
call unit-tests.bat
call deploy.bat
Here is my "bullet proof" solution, which is compilation of all good answers that I found on this topic (thanks to @Damjan and @Kachi). Here the exception is swallowed only if all other ways of detection did not succeeded. In my case I need to close the dialog automatically and this is the only way to protect the app from crash. I hope it will help you! Please, vote and leave comments if you have remarks or better solution. Thank you!
public void dismissWithCheck(Dialog dialog) {
if (dialog != null) {
if (dialog.isShowing()) {
//get the Context object that was used to great the dialog
Context context = ((ContextWrapper) dialog.getContext()).getBaseContext();
// if the Context used here was an activity AND it hasn't been finished or destroyed
// then dismiss it
if (context instanceof Activity) {
// Api >=17
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed()) {
dismissWithTryCatch(dialog);
}
} else {
// Api < 17. Unfortunately cannot check for isDestroyed()
if (!((Activity) context).isFinishing()) {
dismissWithTryCatch(dialog);
}
}
} else
// if the Context used wasn't an Activity, then dismiss it too
dismissWithTryCatch(dialog);
}
dialog = null;
}
}
public void dismissWithTryCatch(Dialog dialog) {
try {
dialog.dismiss();
} catch (final IllegalArgumentException e) {
// Do nothing.
} catch (final Exception e) {
// Do nothing.
} finally {
dialog = null;
}
}
I can't reproduce the @SilentGhost-beating performance quoted by @martineau. Here's my effort with comparisons:
=== maxelements.py ===
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
b = range(10000)
c = range(10000 - 1, -1, -1)
d = b + c
def maxelements_s(seq): # @SilentGhost
''' Return list of position(s) of largest element '''
m = max(seq)
return [i for i, j in enumerate(seq) if j == m]
def maxelements_m(seq): # @martineau
''' Return list of position(s) of largest element '''
max_indices = []
if len(seq):
max_val = seq[0]
for i, val in ((i, val) for i, val in enumerate(seq) if val >= max_val):
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
def maxelements_j(seq): # @John Machin
''' Return list of position(s) of largest element '''
if not seq: return []
max_val = seq[0] if seq[0] >= seq[-1] else seq[-1]
max_indices = []
for i, val in enumerate(seq):
if val < max_val: continue
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
Results from a beat-up old laptop running Python 2.7 on Windows XP SP3:
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_s(me.a)"
100000 loops, best of 3: 6.88 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_m(me.a)"
100000 loops, best of 3: 11.1 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_j(me.a)"
100000 loops, best of 3: 8.51 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_s(a100)"
1000 loops, best of 3: 535 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_m(a100)"
1000 loops, best of 3: 558 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_j(a100)"
1000 loops, best of 3: 489 usec per loop
just remove new
in the $obj_md =& new MDB2();
We had the same problem and you have to use
git fetch
git push origin branch_name
git branch -r
Hope this help someone facing the same problem
As a picture is worth a thousand words..
When you find the IIS6 manager (I have found that searching for IIS may return 2 results) go to the SMTP server properties then 'Access' then press the relay button.
Then you can either select all or only allow certain ip's like 127.0.0.1
Take the following folder structure
notice:
Now in the index.html.en
file you'll want to put the following markup
<p>
<span>src="check_mark.png"</span>
<img src="check_mark.png" />
<span>I'm purple because I'm referenced from this current directory</span>
</p>
<p>
<span>src="/check_mark.png"</span>
<img src="/check_mark.png" />
<span>I'm green because I'm referenced from the ROOT directory</span>
</p>
<p>
<span>src="subfolder/check_mark.png"</span>
<img src="subfolder/check_mark.png" />
<span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>
<p>
<span>src="/subfolder/check_mark.png"</span>
<img src="/subfolder/check_mark.png" />
<span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>
<p>
<span>src="../subfolder/check_mark.png"</span>
<img src="../subfolder/check_mark.png" />
<span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>
<p>
<span>src="subfolder/subfolder/check_mark.png"</span>
<img src="subfolder/subfolder/check_mark.png" />
<span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>
<p>
<span>src="/subfolder/subfolder/check_mark.png"</span>
<img src="/subfolder/subfolder/check_mark.png" />
<span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>
Now if you load up the index.html.en
file located in the second subfolder
http://example.com/subfolder/subfolder/
This will be your output
1 ) Open the SpringToolSuite4.ini File.
2 ) Search For the "openFile" text in the SpringToolSuite4.ini file.
3 ) Provide the javaw.exe file location in SpringToolSuite4.ini
4 ) Note : Provide the New Line between -vm and your javaw.exe file location path as shown below.
openFile
-vm
C:\Program Files\Java\jdk1.8.0\bin\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.8
-Xms256m
It seems that when you change to the latest SDK (2.2) building no longer generates an R.java file. Or at least not in the way we're used to. To solve this delete the package underneath the gen folder and clean without building. This solves the issue for me.
you have to write only one line in maps_activity.xml
map:cameraZoom="13"
I hope this will solve your problem...
You can also add the toolbar in Visual Studio to have the buttons available.
View > Toolbars > Text Editor
Using base graphics, the standard way to do this is to use axes=FALSE, then create your own axes using Axis (or axis). For example,
x <- 1:20
y <- runif(20)
plot(x, y, axes=FALSE, frame.plot=TRUE)
Axis(side=1, labels=FALSE)
Axis(side=2, labels=FALSE)
The lattice equivalent is
library(lattice)
xyplot(y ~ x, scales=list(alternating=0))
I think the better answer for this questions is
array_diff()
because it Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays.
Whereas
array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved.
Something that may get missed: in my chaining project, it turns out a space separated list also needs a space separated semicolon at the end.
In other words, this doesn't work:
transform: translate(50%, 50%) rotate(90deg);
but this does:
transform: translate(50%, 50%) rotate(90deg) ; //has a space before ";"
From C++14 using std and also its numeric literals:
#include <chrono>
#include <thread>
using namespace std::chrono;
std::this_thread::sleep_for(123ms);
Add FormsModule
in your NgModule
imports (hence ngModel
is a part of FormsModule
).
Note it can be
AppModule
or feature module loaded lazily via lazy loading.
imports: [
...,
FormsModule,
...
]
I find the answer. 1/First put in the presets, i have this example "Output format MPEG2 DVD HQ"
-vcodec mpeg2video -vstats_file MFRfile.txt -r 29.97 -s 352x480 -aspect 4:3 -b 4000k -mbd rd -trellis -mv0 -cmp 2 -subcmp 2 -acodec mp2 -ab 192k -ar 48000 -ac 2
If you want a report includes the commands -vstats_file MFRfile.txt into the presets like the example. this can make a report which it's ubicadet in the folder source of your file Source. you can put any name if you want , i solved my problem "i write many times in this forum" reading a complete .docx about mpeg properties. finally i can do my progress bar reading this txt file generated.
Regards.
Try using *
unpack, like below:
>>> a=set('abcde')
>>> a
{'a', 'd', 'e', 'b', 'c'}
>>> l=['f','g']
>>> l
['f', 'g']
>>> {*l, *a}
{'a', 'd', 'e', 'f', 'b', 'g', 'c'}
>>>
Non Editor version:
a=set('abcde')
l=['f', 'g']
print({*l, *a})
Output:
{'a', 'd', 'e', 'f', 'b', 'g', 'c'}
Question is a little vague.
list_of_lines = multiple_lines.split("\n")
for line in list_of_lines:
list_of_items_in_line = line.split(",")
first_int = int(list_of_items_in_line[0])
etc.
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
are there any cases where it doesn't work?
Just to throw this in the mix, if you are developing on a local server, it might not work. You need to specify a scheme, otherwise the browser may assume that src="//cdn.example.com/js_file.js"
is src="file://cdn.example.com/js_file.js"
, which will break since you're not hosting this resource locally.
Microsoft Internet Explorer seem to be particularly sensitive to this, see this question: Not able to load jQuery in Internet Explorer on localhost (WAMP)
You would probably always try to find a solution that works on all your environments with the least amount of modifications needed.
The solution used by HTML5Boilerplate is to have a fallback when the resource is not loaded correctly, but that only works if you incorporate a check:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- If jQuery is not defined, something went wrong and we'll load the local file -->
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
UPDATE: HTML5Boilerplate now uses <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
after deciding to deprecate protocol relative URLs, see [here][3].
select v.SQL_TEXT,
v.PARSING_SCHEMA_NAME,
v.FIRST_LOAD_TIME,
v.DISK_READS,
v.ROWS_PROCESSED,
v.ELAPSED_TIME,
v.service
from v$sql v
where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss')>ADD_MONTHS(trunc(sysdate,'MM'),-2)
where
clause is optional. You can sort the results according to FIRST_LOAD_TIME and find the records up to 2 months ago.
The reason it is throwing that exception is because you have the argument rb
, which opens the file in binary mode. Change that to r
, which will by default open the file in text mode.
Your code:
import csv
ifile = open('sample.csv', "rb")
read = csv.reader(ifile)
for row in read :
print (row)
New code:
import csv
ifile = open('sample.csv', "r")
read = csv.reader(ifile)
for row in read :
print (row)
NOTE: Confirmed with Access 2003, don't know about earlier versions.
For a query in an MDB you can right-click in the query designer (anywhere in the empty space where the tables are), select Properties from the context menu, and enter text in the Description property.
You're limited to 256 characters, but it's better than nothing.
You can get at the description programatically with something like this:
Dim db As Database
Dim qry As QueryDef
Set db = Application.CurrentDb
Set qry = db.QueryDefs("myQuery")
Debug.Print qry.Properties("Description")
For Windows10:
1) Kill VS2015 Process if hung
2) Disable Windows Defender
3) Open VS2015 as Administrator
4) Enable Windows Defender
5) Initial VS2015 startup is complete
To enable/disable draggable in jQuery I used:
$("#draggable").draggable({ disabled: true });
$("#draggable").draggable({ disabled: false });
@Calciphus answer didn't work for me with the opacity problem, so I used:
div.ui-state-disabled.ui-draggable-disabled {opacity: 1;}
Worked on mobile devices either.
Here is the code: http://jsfiddle.net/nn5aL/1/
NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.
You can use INSERT with SELECT UNION ALL:
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
...
Only for small datasets though, which should be fine for your 4 records.
In regards to the octal misinterpretation of .js - I just used this...
parseInt(parseFloat(nv))
and after testing with leading zeros, came back everytime with the correct representation.
hope this helps.
BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:
function getOffsetTop (el) {
if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
return el.offsetTop || 0
}
function getOffsetLeft (el) {
if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
return el.offsetleft || 0
}
function coordinates(el) {
var y1 = getOffsetTop(el) - window.scrollY;
var x1 = getOffsetLeft(el) - window.scrollX;
var y2 = y1 + el.offsetHeight;
var x2 = x1 + el.offsetWidth;
return {
x1: x1, x2: x2, y1: y1, y2: y2
}
}
$('*[data-customerID="22"]');
You should be able to omit the *
, but if I recall correctly, depending on which jQuery version you’re using, this might give faulty results.
Note that for compatibility with the Selectors API (document.querySelector{,all}
), the quotes around the attribute value (22
) may not be omitted in this case.
Also, if you work with data attributes a lot in your jQuery scripts, you might want to consider using the HTML5 custom data attributes plugin. This allows you to write even more readable code by using .dataAttr('foo')
, and results in a smaller file size after minification (compared to using .attr('data-foo')
).
Use round
, floor
or ceil
methods to round it to the closest integer, along with intval()
which is limited.
http://php.net/manual/en/function.round.php
string _connString = "metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=DATABASE;persist security info=True;user id=sa;password=YourPassword;multipleactiveresultsets=True;App=EntityFramework"";
EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(_connString);
ctx = new Entities(_connString);
You can get the connection string from the web.config, and just set that in the EntityConnectionStringBuilder constructor, and use the EntityConnectionStringBuilder as an argument in the constructor for the context.
Cache the connection string by username. Simple example using a couple of generic methods to handle adding/retrieving from cache.
private static readonly ObjectCache cache = MemoryCache.Default;
// add to cache
AddToCache<string>(username, value);
// get from cache
string value = GetFromCache<string>(username);
if (value != null)
{
// got item, do something with it.
}
else
{
// item does not exist in cache.
}
public void AddToCache<T>(string token, T item)
{
cache.Add(token, item, DateTime.Now.AddMinutes(1));
}
public T GetFromCache<T>(string cacheKey) where T : class
{
try
{
return (T)cache[cacheKey];
}
catch
{
return null;
}
}
int (*x)()
is not a pointer to member function. A pointer to member function is written like this: int (A::*x)(void) = &A::f;
.
For a more simple and up to date answer:
backdrop-filter: blur(6px);
Note browser support is not perfect but in most cases a blur would be non essential.
Use ../
:
background-image: url('../images/bg.png');
You can use that as often as you want, e.g. ../../images/
or even at different positions, e.g. ../images/../images/../images/
(same as ../images/
of course)
With C# 6.0, this is now a non-issue as you can do:
nameof(SomeProperty)
This expression is resolved at compile-time to "SomeProperty"
.
For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:
long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));
This will print:
Duration: 1:23:45.678
function scroll_to_anchor(anchor_id){
var tag = $("#"+anchor_id+"");
$('html,body').animate({scrollTop: tag.offset().top},'slow');
}
example to uninstall package 'oauth2client' on MacOS:
pip uninstall oauth2client
Use HTML textarea with runat="server"
to access it in server side.
This solution has less pain than using javascript or regex.
<textarea runat="server" id="txt1" maxlength="100" />
Note: To access Text
Property in server side, you should use txt1.Value
instead of txt1.Text
If your xml is written by java.lang.String
you can just using HttpClient
in this way
public void post() throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.baidu.com");
String xml = "<xml>xxxx</xml>";
HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
}
pay attention to the Exceptions.
BTW, the example is written by the httpclient version 4.x
For me this was caused by using a dynamic ipadress using installation. I reinstalled Oracle using a static ipadress and then everything was fine
$("#myTable > tbody").empty();
It won't touch the headers.
SDK tools required build tool version installation helped me. You just need to install required build tool version from,
SDK Manager -> SDK tool -> Show Package details -> Select required build tool version and install it.
The technique I use most often is find | xargs
. For example, if you want to make every file in this directory and all of its subdirectories world-readable, you can do:
find . -type f -print0 | xargs -0 chmod go+r
find . -type d -print0 | xargs -0 chmod go+rx
The -print0
option terminates with a NULL character instead of a space. The -0
option splits its input the same way. So this is the combination to use on files with spaces.
You can picture this chain of commands as taking every line output by find
and sticking it on the end of a chmod
command.
If the command you want to run as its argument in the middle instead of on the end, you have to be a bit creative. For instance, I needed to change into every subdirectory and run the command latemk -c
. So I used (from Wikipedia):
find . -type d -depth 1 -print0 | \
xargs -0 sh -c 'for dir; do pushd "$dir" && latexmk -c && popd; done' fnord
This has the effect of for dir $(subdirs); do stuff; done
, but is safe for directories with spaces in their names. Also, the separate calls to stuff
are made in the same shell, which is why in my command we have to return back to the current directory with popd
.
just commenting the line of user and password in file ./server/default/conf/props jmx-console-users.properties worked for me
class DayOfWeek {
static $values = array(
self::MONDAY,
self::TUESDAY,
// ...
);
const MONDAY = 0;
const TUESDAY = 1;
// ...
}
$today = DayOfWeek::MONDAY;
// If you want to check if a value is valid
assert( in_array( $today, DayOfWeek::$values ) );
Don't use reflection. It makes it extremely difficult to reason about your code and track down where something is being used, and tends to break static analysis tools (eg what's built into your IDE).
This looks a little better than your previous version but get rid of that .Activate on that line and see if you still get that error.
Dim sh1 As Worksheet
set sh1 = Workbooks.Add(filenum(lngPosition) & ".csv")
Creates a worksheet object. Not until you create that object do you want to start working with it. Once you have that object you can do the following:
sh1.Range("A69").Paste
sh1.Range("A69").Select
The sh1. explicitely tells Excel which object you are saying to work with... otherwise if you start selecting other worksheets while this code is running you could wind up pasting data to the wrong place.
Several possiblies that causes this problem. The root cause is mismatched of compiler version between projects and IDE. For windows environment you can refer to this blog to do the detail troubleshooting.
echo date_format(date_create('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
$formatteddate = new DateTime('17 Oct 2008');
echo $datetime->format('c');
// Output : 2008-10-17T00:00:00+02:00
echo date_format(new DateTime('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
echo date_create('17 Oct 2008')->format('c');
// Output : 2008-10-17T00:00:00+02:00
1) You could also use 'Y-m-d\TH:i:sP'
as an alternative to 'c'
for your format.
2) The default time zone of your input is the time zone of your server. If you want the input to be for a different time zone, you need to set your time zone explicitly. This will also impact your output, however :
echo date_format(date_create('17 Oct 2008 +0800'), 'c');
// Output : 2008-10-17T00:00:00+08:00
3) If you want the output to be for a time zone different from that of your input, you can set your time zone explicitly :
echo date_format(date_create('17 Oct 2008')->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2008-10-16T18:00:00-04:00
I am just adding example here because I think examples make it easier to understand.
In printf() they behave identically so you can use any either %d or %i. But they behave differently in scanf().
For example:
int main()
{
int num,num2;
scanf("%d%i",&num,&num2);// reading num using %d and num2 using %i
printf("%d\t%d",num,num2);
return 0;
}
Output:
You can see the different results for identical inputs.
num
:
We are reading num
using %d
so when we enter 010
it ignores the first 0
and treats it as decimal 10
.
num2
:
We are reading num2
using %i
.
That means it will treat decimals, octals, and hexadecimals differently.
When it give num2
010
it sees the leading 0
and parses it as octal.
When we print it using %d
it prints the decimal equivalent of octal 010
which is 8
.
sys.columns.is_identity = 1
e.g.,
select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1
Additional attributes (in this case, the second onClick
) will be ignored. So, instead of onclick
calling both fbLikeDump();
and WriteCookie();
, it will only call fbLikeDump();
. To fix, simply define a single onclick
attribute and call both functions within it:
<input type="button" value="Don't show this again! " onclick="fbLikeDump();WriteCookie();" />
I have the same issue. I try to write a code in package.json file as below
"scripts": {
"start": "<your-script-file>.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
With STL, programmers use iterators
for traversing through containers, since iterator is an abstract concept, implemented in all standard containers. For example, std::list
has no operator []
at all.
im using following module:
#!/usr/bin/python
# module for getting the lan ip address of the computer
import os
import socket
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', bytes(ifname[:15], 'utf-8'))
# Python 2.7: remove the second argument for the bytes call
)[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith("127.") and os.name != "nt":
interfaces = ["eth0","eth1","eth2","wlan0","wlan1","wifi0","ath0","ath1","ppp0"]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break;
except IOError:
pass
return ip
Tested with windows and linux (and doesnt require additional modules for those) intended for use on systems which are in a single IPv4 based LAN.
The fixed list of interface names does not work for recent linux versions, which have adopted the systemd v197 change regarding predictable interface names as pointed out by Alexander. In such cases, you need to manually replace the list with the interface names on your system, or use another solution like netifaces.
I have modified working solution to handle both the case.. when video is uploaded and when image is uploaded .. hope it will help some.
HTML
<input type="file" id="fileInput">
<div> duration: <span id='sp'></span><div>
Javascript
var fileEl = document.querySelector("input");
fileEl.onchange = function(e) {
var file = e.target.files[0]; // selected file
if (!file) {
console.log("nothing here");
return;
}
console.log(file);
console.log('file.size-' + file.size);
console.log('file.type-' + file.type);
console.log('file.acutalName-' + file.name);
let start = performance.now();
var mime = file.type, // store mime for later
rd = new FileReader(); // create a FileReader
if (/video/.test(mime)) {
rd.onload = function(e) { // when file has read:
var blob = new Blob([e.target.result], {
type: mime
}), // create a blob of buffer
url = (URL || webkitURL).createObjectURL(blob), // create o-URL of blob
video = document.createElement("video"); // create video element
//console.log(blob);
video.preload = "metadata"; // preload setting
video.addEventListener("loadedmetadata", function() { // when enough data loads
console.log('video.duration-' + video.duration);
console.log('video.videoHeight-' + video.videoHeight);
console.log('video.videoWidth-' + video.videoWidth);
//document.querySelector("div")
// .innerHTML = "Duration: " + video.duration + "s" + " <br>Height: " + video.videoHeight; // show duration
(URL || webkitURL).revokeObjectURL(url); // clean up
console.log(start - performance.now());
// ... continue from here ...
});
video.src = url; // start video load
};
} else if (/image/.test(mime)) {
rd.onload = function(e) {
var blob = new Blob([e.target.result], {
type: mime
}),
url = URL.createObjectURL(blob),
img = new Image();
img.onload = function() {
console.log('iamge');
console.dir('this.height-' + this.height);
console.dir('this.width-' + this.width);
URL.revokeObjectURL(this.src); // clean-up memory
console.log(start - performance.now()); // add image to DOM
}
img.src = url;
};
}
var chunk = file.slice(0, 1024 * 1024 * 10); // .5MB
rd.readAsArrayBuffer(chunk); // read file object
};
jsFiddle Url
Union is not what you want. You want to use joins to create single rows. It's a little unclear what constitutes a unique row in your tables and how they really relate to each other and it's also unclear if one table will have rows for every country in every year. But I think this will work:
CREATE VIEW V AS (
SELECT i.country,i.year,p.pop,f.food,i.income FROM
INCOME i
LEFT JOIN
POP p
ON
i.country=p.country
LEFT JOIN
Food f
ON
i.country=f.country
WHERE
i.year=p.year
AND
i.year=f.year
);
The left (outer) join will return rows from the first table even if there are no matches in the second. I've written this assuming you would have a row for every country for every year in the income table. If you don't things get a bit hairy as MySQL does not have built in support for FULL OUTER JOINs last I checked. There are ways to simulate it, and they would involve unions. This article goes into some depth on the subject: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/
A simple solution would be to simply create a dump of just the table you wish to restore separately. You can use the mysqldump command to do so with the following syntax:
mysqldump -u [user] -p[password] [database] [table] > [output_file_name].sql
Then import it as normal, and it will only import the dumped table.
Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?
Sql server unlike oracle does not need commits unless you are using transactions.
Immediatly after your update statement the table will be commited, don't use the commit command in this scenario.
Try,
var newList =
(
from x in empCollection
select new {Loc = x.empLoc, PL = x.empPL, Shift = x.empShift}
).Distinct();
You can use this code on view.blade. {{var_dump($animales)}}
First, let me go over a few terms. If you just want your question answered, scroll down to "Answering your question".
Object identity: When you create an object, you can assign it to a variable. You can then also assign it to another variable. And another.
>>> button = Button()
>>> cancel = button
>>> close = button
>>> dismiss = button
>>> print(cancel is close)
True
In this case, cancel
, close
, and dismiss
all refer to the same object in memory. You only created one Button
object, and all three variables refer to this one object. We say that cancel
, close
, and dismiss
all refer to identical objects; that is, they refer to one single object.
Object equality: When you compare two objects, you usually don't care that it refers to the exact same object in memory. With object equality, you can define your own rules for how two objects compare. When you write if a == b:
, you are essentially saying if a.__eq__(b):
. This lets you define a __eq__
method on a
so that you can use your own comparison logic.
Rationale: Two objects have the exact same data, but are not identical. (They are not the same object in memory.) Example: Strings
>>> greeting = "It's a beautiful day in the neighbourhood."
>>> a = unicode(greeting)
>>> b = unicode(greeting)
>>> a is b
False
>>> a == b
True
Note: I use unicode strings here because Python is smart enough to reuse regular strings without creating new ones in memory.
Here, I have two unicode strings, a
and b
. They have the exact same content, but they are not the same object in memory. However, when we compare them, we want them to compare equal. What's happening here is that the unicode object has implemented the __eq__
method.
class unicode(object):
# ...
def __eq__(self, other):
if len(self) != len(other):
return False
for i, j in zip(self, other):
if i != j:
return False
return True
Note: __eq__
on unicode
is definitely implemented more efficiently than this.
Rationale: Two objects have different data, but are considered the same object if some key data is the same. Example: Most types of model data
>>> import datetime
>>> a = Monitor()
>>> a.make = "Dell"
>>> a.model = "E770s"
>>> a.owner = "Bob Jones"
>>> a.warranty_expiration = datetime.date(2030, 12, 31)
>>> b = Monitor()
>>> b.make = "Dell"
>>> b.model = "E770s"
>>> b.owner = "Sam Johnson"
>>> b.warranty_expiration = datetime.date(2005, 8, 22)
>>> a is b
False
>>> a == b
True
Here, I have two Dell monitors, a
and b
. They have the same make and model. However, they neither have the same data nor are the same object in memory. However, when we compare them, we want them to compare equal. What's happening here is that the Monitor object implemented the __eq__
method.
class Monitor(object):
# ...
def __eq__(self, other):
return self.make == other.make and self.model == other.model
When comparing to None
, always use is not
. None is a singleton in Python - there is only ever one instance of it in memory.
By comparing identity, this can be performed very quickly. Python checks whether the object you're referring to has the same memory address as the global None object - a very, very fast comparison of two numbers.
By comparing equality, Python has to look up whether your object has an __eq__
method. If it does not, it examines each superclass looking for an __eq__
method. If it finds one, Python calls it. This is especially bad if the __eq__
method is slow and doesn't immediately return when it notices that the other object is None
.
Did you not implement __eq__
? Then Python will probably find the __eq__
method on object
and use that instead - which just checks for object identity anyway.
When comparing most other things in Python, you will be using !=
.
To answer the question posted in the comment above - try something like this:
unsigned short int x = 65529U;
short int y = (short int)x;
printf("%d\n", y);
or
unsigned short int x = 65529U;
short int y = 0;
memcpy(&y, &x, sizeof(short int);
printf("%d\n", y);
from jquery api
Added to jQuery in version 1.4, the .delay()
method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show()
or .hide()
which do not use the effects queue.
Gummi is the best LaTeX editor. It is a free, open source, cross-platform, program, featuring a live preview pane.
http://gummi.midnightcoding.org/
e4 http://gummi.midnightcoding.org/wp-content/uploads/20091012-1large(1).png
Because we can not use Where clause with aggregate functions like count(),min(), sum() etc. so having clause came into existence to overcome this problem in sql. see example for having clause go through this link
First, Eloquent automatically converts it's timestamps (created_at
, updated_at
) into carbon objects. You could just use updated_at
to get that nice feature, or specify edited_at
in your model in the $dates
property:
protected $dates = ['edited_at'];
Now back to your actual question. Carbon has a bunch of comparison functions:
eq()
equalsne()
not equalsgt()
greater thangte()
greater than or equalslt()
less thanlte()
less than or equalsUsage:
if($model->edited_at->gt($model->created_at)){
// edited at is newer than created at
}
You can CHANGE user interface LANGUAGE like this:
Open VS > VS Community > Preferences > Environment > Visual Style > User Interface language
Woala!!!
The Kotlin Way
fun showPopupMenu(view: View) {
PopupMenu(view.context, view).apply {
menuInflater.inflate(R.menu.popup_men, menu)
setOnMenuItemClickListener { item ->
Toast.makeText(view.context, "You Clicked : " + item.title, Toast.LENGTH_SHORT).show()
true
}
}.show()
}
UPDATE: In the above code, the apply function returns this
which is not required, so we can use run
which don't return anything and to make it even simpler we can also remove the curly braces of showPopupMenu method.
Even Simpler:
fun showPopupMenu(view: View) = PopupMenu(view.context, view).run {
menuInflater.inflate(R.menu.popup_men, menu)
setOnMenuItemClickListener { item ->
Toast.makeText(view.context, "You Clicked : ${item.title}", Toast.LENGTH_SHORT).show()
true
}
show()
}
I was having the same issue this morning. It appears that for a DATE or DATETIME field, an empty value cannot be inserted. I got around this by first checking for an empty value (mydate = "") and if it was empty setting mydate = "NULL" before insert.
The DATE and DATETIME fields don't behave in the same way as VARCHAR fields.
Either use one of the standard date and time format strings which only specifies the date (e.g. "D" or "d"), or a custom date and time format string which only uses the date parts (e.g. "yyyy/MM/dd").
PHP has a method called md5 ;-) Just $password = md5($passToEncrypt);
If you are searching in a SQL u can use a MySQL Method MD5() too....
SELECT * FROM user WHERE Password='. md5($password) .'
or SELECT * FROM ser WHERE Password=MD5('. $password .')
To insert it u can do it the same way.
I have found that using cabs(double)
, cabsf(float)
, cabsl(long double)
, __cabsf(float)
, __cabs(double)
, __cabsf(long double)
is the solution
You can use Will Dean's suggestion [
#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))
] to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.
The case where it doesn't work is when the "array" is really just a pointer, not an actual array. Also, because of the way arrays are passed to functions (converted to a pointer to the first element), it doesn't work across function calls even if the signature looks like an array — some_function(string parameter[])
is really some_function(string *parameter)
.
Run command rndc querylog on
or add querylog yes;
to options{};
section in named.conf
to activate that channel.
Also make sure you’re checking correct directory if your bind is chrooted.