theStatement=theConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet theResult=theStatement.executeQuery(query);
//Get the size of the data returned
theResult.last();
int size = theResult.getRow() * theResult.getMetaData().getColumnCount();
theResult.beforeFirst();
A direction quotation from the documentation on 5.3. Tuples and Sequences:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
Its undefined
because, console.log(response)
runs before doCall(urlToCall);
is finished. You have to pass in a callback function aswell, that runs when your request is done.
First, your function. Pass it a callback:
function doCall(urlToCall, callback) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return callback(finalData);
});
}
Now:
var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
// Here you have access to your variable
console.log(response);
})
@Rodrigo, posted a good resource in the comments. Read about callbacks in node and how they work. Remember, it is asynchronous code.
Solved jQuery: Add element after another element
<script>
$( "p" ).append( "<strong>Hello</strong>" );
</script>
OR
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery ( ".sidebar_cart" ) .append( "<a href='http://#'>Continue Shopping</a>" );
});
</script>
The *_all() functions are so simple that for a few methods I'd just write the functions. If you have lots of identical functions, you can write a generic function:
def apply_on_all(seq, method, *args, **kwargs):
for obj in seq:
getattr(obj, method)(*args, **kwargs)
Or create a function factory:
def create_all_applier(method, doc=None):
def on_all(seq, *args, **kwargs):
for obj in seq:
getattr(obj, method)(*args, **kwargs)
on_all.__doc__ = doc
return on_all
start_all = create_all_applier('start', "Start all instances")
stop_all = create_all_applier('stop', "Stop all instances")
...
It is prohibiting the opening of Eclipse app because it was not registered with Apple by an identified developer. This is a security feature, however, you can override the security setting and open the app by doing the following:
The last step will add an exception for Eclipse to your security settings and now you will be able to open it without any warnings.
Note, these steps work for other *.app apps that may encounter the same issue.
Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/
But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing
-rw-r--r--@
thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:
-rw-r--rw-@
This did it. The message disappeared.
One point I noticed with Primefaces 3.4 and Netbeans 7.2:
Remove the Netbeans auto-filled parameters for function handleFileUpload i.e. (event) otherwise event could be null.
<h:form>
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload(event)}"
mode="advanced"
update="messages"
sizeLimit="100000"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
<p:growl id="messages" showDetail="true"/>
</h:form>
First of all you shouldn't reach the service by using the ActivityManager
. (Discussed here)
Services can run on their own, be bound to an Activity or both. The way to check in an Activity if your Service is running or not is by making an interface (that extends Binder) where you declare methods that both, the Activity
and the Service
, understand. You can do this by making your own Interface where you declare for example "isServiceRunning()
".
You can then bind your Activity to your Service, run the method isServiceRunning(), the Service will check for itself if it is running or not and returns a boolean to your Activity.
You can also use this method to stop your Service or interact with it in another way.
Many answers provided for this question. Just wanted to add one more which uses bashism-
#! /bin/bash
while read -r || [[ -n "$REPLY" ]]; do
[[ "$REPLY" =~ ^(-rwx|drwx).*[[:digit:]]+$ ]] && echo "Got one -> $REPLY"
done <"$1"
@kurumi answer for bash, which uses case is also correct but it will not read last line of file if there is no newline sequence at the end(Just save the file without pressing 'Enter/Return' at the last line).
You can have multiple .gitignore
, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore
: git check-ignore -v -- afile
.
And you can have different version of a .gitignore
file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.
If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore
files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.
Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile
in order to see which gitignore run (from which .gitignore
file) is applied to 'yourfile
', and better understand why said file is ignored.
See "which gitignore
rule is ignoring my file?"
There is no need to have two functions within one element, you need just one that calls the other two!
<a href="#" onclick="my_func()" >click</a>
function my_func() {
my_func_1();
my_func_2();
}
Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:
foo[ c( rep(FALSE, 5), TRUE ) ]
Asked question title is general, but authors use case stated in the body of the question is specific. So any other answers may be used.
But in order to fully answer the title question it should be clarified that it seems like all of the approaches may fail in some cases and require some rework. I reviewed all of them (and some additional) in decreasing of reliability order (in my opinion):
==
(accepted answer).Despite the fact that this is accepted answer and has most upvotes count, I think this method should not be used at all. Because in fact this approach is discouraged in python as mentioned several times here.
But if one still want to use it - should be aware of some pandas-specific dtypes like pd.CategoricalDType
, pd.PeriodDtype
, or pd.IntervalDtype
. Here one have to use extra type( )
in order to recognize dtype correctly:
s = pd.Series([pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')])
s
s.dtype == pd.PeriodDtype # Not working
type(s.dtype) == pd.PeriodDtype # working
>>> 0 2002-03-01
>>> 1 2012-02-01
>>> dtype: period[D]
>>> False
>>> True
Another caveat here is that type should be pointed out precisely:
s = pd.Series([1,2])
s
s.dtype == np.int64 # Working
s.dtype == np.int32 # Not working
>>> 0 1
>>> 1 2
>>> dtype: int64
>>> True
>>> False
isinstance()
approach.This method has not been mentioned in answers so far.
So if direct comparing of types is not a good idea - lets try built-in python function for this purpose, namely - isinstance()
.
It fails just in the beginning, because assumes that we have some objects, but pd.Series
or pd.DataFrame
may be used as just empty containers with predefined dtype
but no objects in it:
s = pd.Series([], dtype=bool)
s
>>> Series([], dtype: bool)
But if one somehow overcome this issue, and wants to access each object, for example, in the first row and checks its dtype like something like that:
df = pd.DataFrame({'int': [12, 2], 'dt': [pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')]},
index = ['A', 'B'])
for col in df.columns:
df[col].dtype, 'is_int64 = %s' % isinstance(df.loc['A', col], np.int64)
>>> (dtype('int64'), 'is_int64 = True')
>>> (dtype('<M8[ns]'), 'is_int64 = False')
It will be misleading in the case of mixed type of data in single column:
df2 = pd.DataFrame({'data': [12, pd.Timestamp('2013-01-02')]},
index = ['A', 'B'])
for col in df2.columns:
df2[col].dtype, 'is_int64 = %s' % isinstance(df2.loc['A', col], np.int64)
>>> (dtype('O'), 'is_int64 = False')
And last but not least - this method cannot directly recognize Category
dtype. As stated in docs:
Returning a single item from categorical data will also return the value, not a categorical of length “1”.
df['int'] = df['int'].astype('category')
for col in df.columns:
df[col].dtype, 'is_int64 = %s' % isinstance(df.loc['A', col], np.int64)
>>> (CategoricalDtype(categories=[2, 12], ordered=False), 'is_int64 = True')
>>> (dtype('<M8[ns]'), 'is_int64 = False')
So this method is also almost inapplicable.
df.dtype.kind
approach.This method yet may work with empty pd.Series
or pd.DataFrames
but has another problems.
First - it is unable to differ some dtypes:
df = pd.DataFrame({'prd' :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
'str' :['s1', 's2'],
'cat' :[1, -1]})
df['cat'] = df['cat'].astype('category')
for col in df:
# kind will define all columns as 'Object'
print (df[col].dtype, df[col].dtype.kind)
>>> period[D] O
>>> object O
>>> category O
Second, what is actually still unclear for me, it even returns on some dtypes None.
df.select_dtypes
approach.This is almost what we want. This method designed inside pandas so it handles most corner cases mentioned earlier - empty DataFrames, differs numpy or pandas-specific dtypes well. It works well with single dtype like .select_dtypes('bool')
. It may be used even for selecting groups of columns based on dtype:
test = pd.DataFrame({'bool' :[False, True], 'int64':[-1,2], 'int32':[-1,2],'float': [-2.5, 3.4],
'compl':np.array([1-1j, 5]),
'dt' :[pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')],
'td' :[pd.Timestamp('2012-03-02')- pd.Timestamp('2016-10-20'),
pd.Timestamp('2010-07-12')- pd.Timestamp('2000-11-10')],
'prd' :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
'intrv':pd.arrays.IntervalArray([pd.Interval(0, 0.1), pd.Interval(1, 5)]),
'str' :['s1', 's2'],
'cat' :[1, -1],
'obj' :[[1,2,3], [5435,35,-52,14]]
})
test['int32'] = test['int32'].astype(np.int32)
test['cat'] = test['cat'].astype('category')
Like so, as stated in the docs:
test.select_dtypes('number')
>>> int64 int32 float compl td
>>> 0 -1 -1 -2.5 (1-1j) -1693 days
>>> 1 2 2 3.4 (5+0j) 3531 days
On may think that here we see first unexpected (at used to be for me: question) results - TimeDelta
is included into output DataFrame
. But as answered in contrary it should be so, but one have to be aware of it. Note that bool
dtype is skipped, that may be also undesired for someone, but it's due to bool
and number
are in different "subtrees" of numpy dtypes. In case with bool, we may use test.select_dtypes(['bool'])
here.
Next restriction of this method is that for current version of pandas (0.24.2), this code: test.select_dtypes('period')
will raise NotImplementedError
.
And another thing is that it's unable to differ strings from other objects:
test.select_dtypes('object')
>>> str obj
>>> 0 s1 [1, 2, 3]
>>> 1 s2 [5435, 35, -52, 14]
But this is, first - already mentioned in the docs. And second - is not the problem of this method, rather the way strings are stored in DataFrame
. But anyway this case have to have some post processing.
df.api.types.is_XXX_dtype
approach.This one is intended to be most robust and native way to achieve dtype recognition (path of the module where functions resides says by itself) as i suppose. And it works almost perfectly, but still have at least one caveat and still have to somehow distinguish string columns.
Besides, this may be subjective, but this approach also has more 'human-understandable' number
dtypes group processing comparing with .select_dtypes('number')
:
for col in test.columns:
if pd.api.types.is_numeric_dtype(test[col]):
print (test[col].dtype)
>>> bool
>>> int64
>>> int32
>>> float64
>>> complex128
No timedelta
and bool
is included. Perfect.
My pipeline exploits exactly this functionality at this moment of time, plus a bit of post hand processing.
Hope I was able to argument the main point - that all discussed approaches may be used, but only pd.DataFrame.select_dtypes()
and pd.api.types.is_XXX_dtype
should be really considered as the applicable ones.
If you have forgot the MySQL root password, can’t remember or want to break in….. you can reset the mysql database password from the command line in either Linux or OS X as long as you know the root user password of the box you are on:
(1) Stop MySQL
sudo /usr/local/mysql/support-files/mysql.server stop
(2) Start it in safe mode:
sudo mysqld_safe --skip-grant-tables
(3) This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:
mysql -u root
UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';
In the UPDATE command above just replace the 'password' with your own new password, make sure to keep the quotation marks
(4) Save and quite
FLUSH PRIVILEGES;
\q
(5) Start MySQL
sudo /usr/local/mysql/support-files/mysql.server start
If you decide to add a .pch file manually and you want to use Objective-C just like before xCode 6 you will also have to import UIKit and Foundation frameworks in the .pch file. Otherwise you will have to import these frameworks manually in each header file. You can add the following code anyway as it tests for the language used:
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#endif
I presume you mean curve-fitting and not anti-aliasing from the context of your question. PyPlot doesn't have any built-in support for this, but you can easily implement some basic curve-fitting yourself, like the code seen here, or if you're using GuiQwt it has a curve fitting module. (You could probably also steal the code from SciPy to do this as well).
Just to add. Another disadvantage would be, .inc files are not recognized by IDE thus, you could not take advantage of auto-complete or code prediction features.
[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
class MyFirebaseIIDService: FirebaseInstanceIdService
{
const string TAG = "MyFirebaseIIDService";
NotificationHub hub;
public override void OnTokenRefresh()
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
Log.Debug(TAG, "FCM token: " + refreshedToken);
SendRegistrationToServer(refreshedToken);
}
void SendRegistrationToServer(string token)
{
// Register with Notification Hubs
hub = new NotificationHub(Constants.NotificationHubName,
Constants.ListenConnectionString, this);
Employee employee = JsonConvert.DeserializeObject<Employee>(Settings.CurrentUser);
//if user is not logged in
if (employee != null)
{
var tags = new List<string>() { employee.Email};
var regID = hub.Register(token, tags.ToArray()).RegistrationId;
Log.Debug(TAG, $"Successful registration of ID {regID}");
}
else
{
FirebaseInstanceId.GetInstance(Firebase.FirebaseApp.Instance).DeleteInstanceId();
hub.Unregister();
}
}
}
I used DecimalFormat for formatting the BigDecimal instead of formatting the String, seems no problems with it.
The code is something like this:
bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(0);
df.setGroupingUsed(false);
String result = df.format(bd);
After a full day of search, I disabled Avast for 10 minutes and Windows Firewall (important) and everything started working!
This was my error:
Mail server connection failed; nested exception is javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target. Failed messages: javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Here is how to fix the issue in Avast 19.8.2393 by adding an exclusion to SMTP port 587 (or whichever port your application uses):
Open Avast
Click on 'Settings'
Click on 'Troubleshooting' and then 'Open old settings'
In my case, I just removed 587 from SMTP ports.
Now I am able to use Avast and also have my Windows Firewall switched on (no need to add additional exclusion for the Firewall).
Here are my application.properties e-mail properties:
###### I am using a Google App Password which I generated in my Gmail Security settings ######
spring.mail.host = smtp.gmail.com
spring.mail.port = 587
spring.mail.protocol = smtp
spring.mail.username = gmail account
spring.mail.password = password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
because a lambda function is supposed to be one-lined, as its the simplest form of a function, an entrance, then return
I had more than 100MB data, therefore I could not restore database using Pgadmin4.
I used simply postgres client, and write below command.
postgres@khan:/$ pg_restore -d database_name /home/khan/Downloads/dump.sql
It worked fine and took few seconds.You can see below link for more information. https://www.postgresql.org/docs/8.1/app-pgrestore.html
Not sure about the subelements, but all browsers should support this now:
for (val of lineChartData) {
document.write(val);
}
This might give you some ideas For-each over an array in JavaScript?
If you just need to get a few items from the JSON object, I would use Json.NET's LINQ to JSON JObject
class. For example:
JToken token = JObject.Parse(stringFullOfJson);
int page = (int)token.SelectToken("page");
int totalPages = (int)token.SelectToken("total_pages");
I like this approach because you don't need to fully deserialize the JSON object. This comes in handy with APIs that can sometimes surprise you with missing object properties, like Twitter.
Documentation: Serializing and Deserializing JSON with Json.NET and LINQ to JSON with Json.NET
What sort of button, neither a Forms Control nor an ActiveX control should affect the used range.
It is a known problem that excel does not keep track of the used range very well. Any reference to the used range via VBA will reset the value to the current used range. So try running this sub procedure:
Sub ResetUsedRng()
Application.ActiveSheet.UsedRange
End Sub
Failing that you may well have some formatting hanging round. Try clearing/deleting all the cells after your last row.
Regarding the above also see:
Another method to find the last used cell:
Dim rLastCell As Range
Set rLastCell = ActiveSheet.Cells.Find(What:="*", After:=.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
Change the search direction to find the first used cell.
Better be late than never. I used GSON to convert list of HashMap to string if in case you want to have a serialized list.
List<HashMap<String, String>> list = new ArrayList<>();
HashMap<String,String> hashMap = new HashMap<>();
hashMap.add("key", "value");
hashMap.add("key", "value");
hashMap.add("key", "value");
list.add(hashMap);
String json = new Gson().toJson(list);
This json
produces [{"key":"value","key":"value","key":"value"}]
We may need more information. Here is what I did to reproduce on SQL Server 2008:
CREATE DATABASE [Test] ON PRIMARY
(
NAME = N'Test'
, FILENAME = N'...Test.mdf'
, SIZE = 3072KB
, FILEGROWTH = 1024KB
)
LOG ON
(
NAME = N'Test_log'
, FILENAME = N'...Test_log.ldf'
, SIZE = 1024KB
, FILEGROWTH = 10%
)
COLLATE SQL_Latin1_General_CP850_BIN2
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MyTable]
(
[SomeCol] [varchar](50) NULL
) ON [PRIMARY]
GO
Insert MyTable( SomeCol )
Select '±' Collate SQL_Latin1_General_CP1_CI_AS
GO
Select SomeCol, SomeCol Collate SQL_Latin1_General_CP1_CI_AS
From MyTable
Results show the original character. Declaring collation in the query should return the proper character from SQL Server's perspective however it may be the case that the presentation layer is then converting to something yet different like UTF-8.
It's used to make std::string
interoperable with C code that requires a null terminated char*
.
For class and text xpath-
//div[contains(@class,'Caption') and (text(),'Model saved')]
and
For class and id xpath-
//div[contains(@class,'gwt-HTML') and @id="alertLabel"]
You can use the text
method and pass a function that returns the modified text, using the native String.prototype.replace
method to perform the replacement:
?$(".text_div").text(function () {
return $(this).text().replace("contains", "hello everyone");
});?????
Here's a working example.
If you save color code in the colors.xml which is under the values folder,then you should call the following:
root.setBackgroundColor(getResources().getColor(R.color.name));
name
means you declare in the <color/>
tag.
You don't need to use quotes and you can use any path you like!
Try ps -ef
. man ps
will give you all the options.
-A Display information about other users' processes, including those without controlling terminals.
-e Identical to -A.
-f Display the uid, pid, parent pid, recent CPU usage, process start time, controlling tty, elapsed CPU usage, and the associated command. If the -u option is also used, display
the user name rather then the numeric uid. When -o or -O is used to add to the display following -f, the command field is not truncated as severely as it is in other formats.
Use command >> file_to_append_to
to append to a file.
For example echo "Hello" >> testFile.txt
CAUTION: if you only use a single >
you will overwrite the contents of the file. To ensure that doesn't ever happen, you can add set -o noclobber
to your .bashrc
.
This ensures that if you accidentally type command > file_to_append_to
to an existing file, it will alert you that the file exists already. Sample error message: file exists: testFile.txt
Thus, when you use >
it will only allow you to create a new file, not overwrite an existing file.
sudo cp hello.php /var/www/
What output do you get?
var timecompare = {
tstr: "",
get: function (current_time, startTime, endTime) {
this.tstr = "";
var s = current_time.split(":"), t1 = tm1.split(":"), t2 = tm2.split(":"), t1s = Number(t1[0]), t1d = Number(t1[1]), t2s = Number(t2[0]), t2d = Number(t2[1]);
if (t1s < t2s) {
this.t(t1s, t2s);
}
if (t1s > t2s) {
this.t(t1s, 23);
this.t(0, t2s);
}
var saat_dk = Number(s[1]);
if (s[0] == tm1.substring(0, 2) && saat_dk >= t1d)
return true;
if (s[0] == tm2.substring(0, 2) && saat_dk <= t2d)
return true;
if (this.tstr.indexOf(s[0]) != 1 && this.tstr.indexOf(s[0]) != -1 && !(this.tstr.indexOf(s[0]) == this.tstr.length - 2))
return true;
return false;
},
t: function (ii, brk) {
for (var i = 0; i <= 23; i++) {
if (i < ii)
continue;
var s = (i < 10) ? "0" + i : i + "";
this.tstr += "," + s;
if (brk == i)
break;
}
}};
I tried everything and nothing worked so here is another solution that finally worked (for me).
I had to check Enable Java EE configuration
under Preferences -> Maven -> Jave EE configuration
After that you can check that more entries were added in Deployment assemblies
of the project settings.
With a little effort of templatizing this, it wold work with any list of objects.
#include <iostream>
#include <string>
#include <vector>
char non_repeating_char(std::string str){
while(str.size() >= 2){
std::vector<size_t> rmlist;
for(size_t i = 1; i < str.size(); i++){
if(str[0] == str[i]) {
rmlist.push_back(i);
}
}
if(rmlist.size()){
size_t s = 0; // Need for terator position adjustment
str.erase(str.begin() + 0);
++s;
for (size_t j : rmlist){
str.erase(str.begin() + (j-s));
++s;
}
continue;
}
return str[0];
}
if(str.size() == 1) return str[0];
else return -1;
}
int main(int argc, char ** args)
{
std::string test = "FabaccdbefafFG";
test = args[1];
char non_repeating = non_repeating_char(test);
Std::cout << non_repeating << '\n';
}
Trying to do more friendly solution of DecimalToString (https://stackoverflow.com/a/34486763/3852139):
private static decimal Trim(this decimal value)
{
var s = value.ToString(CultureInfo.InvariantCulture);
return s.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator)
? Decimal.Parse(s.TrimEnd('0'), CultureInfo.InvariantCulture)
: value;
}
private static decimal? Trim(this decimal? value)
{
return value.HasValue ? (decimal?) value.Value.Trim() : null;
}
private static void Main(string[] args)
{
Console.WriteLine("=>{0}", 1.0000m.Trim());
Console.WriteLine("=>{0}", 1.000000023000m.Trim());
Console.WriteLine("=>{0}", ((decimal?) 1.000000023000m).Trim());
Console.WriteLine("=>{0}", ((decimal?) null).Trim());
}
Output:
=>1
=>1.000000023
=>1.000000023
=>
There is a variation on the same theme that uses a for loop, instead of a while loop, to limit the scope of the line variable. Whether it's "better" is a matter of personal taste.
for(String line = reader.readLine(); line != null; line = reader.readLine()) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
Windows 10:
Android Studio -> File -> Other Settings -> Default Project Structure... -> JDK location:
copy string shown, such as:
C:\Program Files\Android\Android Studio\jre
In file locator directory window, right-click on "This PC" ->
Properties -> Advanced System Settings -> Environment Variables... -> System Variables
click on the New... button under System Variables, then type and paste respectively:
.......Variable name: JAVA_HOME
.......Variable value: C:\Program Files\Android\Android Studio\jre
and hit OK buttons to close out.
Some installations may require JRE_HOME to be set as well, the same way.
To check, open a NEW black console window, then type echo %JAVA_HOME%
. You should get back the full path you typed into the system variable. Windows 10 seems to support spaces in the filename paths for system variables very well, and does not seem to need ~tilde eliding.
After testing on Juno, Kepler and Luna, I found JD only works for *.class files on build path.
*.class without source
to Class File Editor
with a cup iconfunction converToLocalTime(serverDate) {
var dt = new Date(Date.parse(serverDate));
var localDate = dt;
var gmt = localDate;
var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
var localNow = new Date().getTimezoneOffset(); // get the timezone
// offset in minutes
var localTime = min - localNow; // get the local time
var dateStr = new Date(localTime * 1000 * 60);
// dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return dateStr;
}
I was looking for a solution to this and used the indirect one found on this page initially, but I found it quite long and clunky for what I was trying to do. After a bit of research, I found a more elegant solution (to my problem) using R1C1 notation - I think you can't mix different notation styles without using VBA though.
Depending on what you're trying to do with the self referenced cell, something like this example should get a cell to reference itself where the cell is F13:
Range("F13").FormulaR1C1 = "RC"
And you can then reference cells in relative positions to that cell such as - where your cell is F13 and you need to reference G12 from it.
Range("F13").FormulaR1C1 = "R[-1]C[1]"
You're essentially telling Excel to find F13 and then move down 1 row and up one column from that.
How this fit into my project was to apply a vlookup across a range where the lookup value was relative to each cell in the range without having to specify each lookup cell separately:
Sub Code()
Dim Range1 As Range
Set Range1 = Range("B18:B23")
Range1.Locked = False
Range1.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-1],DATABYCODE,2,FALSE),"""")"
Range1.Locked = True
End Sub
My lookup value is the cell to the left of each cell (column -1) in my DIM'd range and DATABYCODE is the named range I'm looking up against.
Hope that makes a little sense? Thought it was worth throwing into the mix as another way to approach the problem.
About the simplest way to store a single preference in an Android Activity is to do something like this:
Editor e = this.getPreferences(Context.MODE_PRIVATE).edit();
e.putString("password", mPassword);
e.commit();
If you're worried about the security of these then you could always encrypt the password before storing it.
Generally, placement new is used to get rid of allocation cost of a 'normal new'.
Another scenario where I used it is a place where I wanted to have access to the pointer to an object that was still to be constructed, to implement a per-document singleton.
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w
covers a-zA-Z and some other word characters. It all depends on what you need specifically.
Or if you don't want to build it just remove it from settings.gradle
file
For installing mysql-shell
with homebrew, run
brew cask install mysql-shell
you can then launch the mysql shell with
mysqlsh
if you want to enter SQL mode directly, run
mysqlsh --sql
The HTTP POST payload is just a flat bunch of bytes. Django (like most frameworks) decodes it into a dictionary from either URL encoded parameters, or MIME-multipart encoding. If you just dump the JSON data in the POST content, Django won't decode it. Either do the JSON decoding from the full POST content (not the dictionary); or put the JSON data into a MIME-multipart wrapper.
In short, show the JavaScript code. The problem seems to be there.
Check android studio event log as it could be low storage issue.
emulator: ERROR: Not enough disk space to run AVD 'Nexus_5_API_21'. Exiting...
Try this
products.sort(function (a, b) {
return a.title.rendered - b.title.rendered;
});
OR
You can import lodash/underscore library, it has many build functions available for manipulating, filtering, sorting the array and all.
Using underscore: (below one is just an example)
import * as _ from 'underscore';
let sortedArray = _.sortBy(array, 'title');
Using subprocess.run
import subprocess
ps = subprocess.run(['ps', '-A'], check=True, capture_output=True)
processNames = subprocess.run(['grep', 'process_name'],
input=ps.stdout, capture_output=True)
print(processNames.stdout)
I have come to share an solution. The error happened to me after forcing the notbook to hang up. possible solution clean preject
.
According to mongoDB documentation: "...That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes."
So add indexes for your other fields and it will work. I had a similar problem and this solved it.
You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/
You don't have to struggle any longer, when there exists a way lilke this:
$stmt = $pdo->prepare("SELECT * FROM someTable WHERE col = :val");
$stmt->execute([":val" => $bind]);
You could try using Linq to project the list:
var output = lst.Select(x => x % 2 == 0).ToList();
This will return a new list of bools such that {1, 2, 3, 4, 5}
will map to {false, true, false, true, false}
.
Well, glad I asked. The solution I finally discovered was here:
How do I configure SQL Server Express to allow remote tcp/ip connections on port 1433?
So far, so good, and entirely expected. But then:
(Also, if you follow these steps, it's not necessary to enable SQL Server Browser, and you only need to allow port 1433, not 1434.)
These extra five steps are something I can't remember ever having had to do in a previous version of SQL Server, Express or otherwise. They appear to have been necessary because I'm using a named instance (myservername\SQLEXPRESS) on the server instead of a default instance. See here:
Configure a Server to Listen on a Specific TCP Port (SQL Server Configuration Manager)
Just to stick with the proposed question as indicated by the title, you can actually iterate over each match in a string using String.prototype.replace()
. For example the following does just that to get an array of all words based on a regular expression:
function getWords(str) {
var arr = [];
str.replace(/\w+/g, function(m) {
arr.push(m);
});
return arr;
}
var words = getWords("Where in the world is Carmen Sandiego?");
// > ["Where", "in", "the", "world", "is", "Carmen", "Sandiego"]
If I wanted to get capture groups or even the index of each match I could do that too. The following shows how each match is returned with the entire match, the 1st capture group and the index:
function getWords(str) {
var arr = [];
str.replace(/\w+(?=(.*))/g, function(m, remaining, index) {
arr.push({ match: m, remainder: remaining, index: index });
});
return arr;
}
var words = getWords("Where in the world is Carmen Sandiego?");
After running the above, words
will be as follows:
[
{
"match": "Where",
"remainder": " in the world is Carmen Sandiego?",
"index": 0
},
{
"match": "in",
"remainder": " the world is Carmen Sandiego?",
"index": 6
},
{
"match": "the",
"remainder": " world is Carmen Sandiego?",
"index": 9
},
{
"match": "world",
"remainder": " is Carmen Sandiego?",
"index": 13
},
{
"match": "is",
"remainder": " Carmen Sandiego?",
"index": 19
},
{
"match": "Carmen",
"remainder": " Sandiego?",
"index": 22
},
{
"match": "Sandiego",
"remainder": "?",
"index": 29
}
]
In order to match multiple occurrences similar to what is available in PHP with preg_match_all
you can use this type of thinking to make your own or use something like YourJS.matchAll()
. YourJS more or less defines this function as follows:
function matchAll(str, rgx) {
var arr, extras, matches = [];
str.replace(rgx.global ? rgx : new RegExp(rgx.source, (rgx + '').replace(/[\s\S]+\//g , 'g')), function() {
matches.push(arr = [].slice.call(arguments));
extras = arr.splice(-2);
arr.index = extras[0];
arr.input = extras[1];
});
return matches[0] ? matches : null;
}
We show up two functions that prints a SINGLE character to binary.
void printbinchar(char character)
{
char output[9];
itoa(character, output, 2);
printf("%s\n", output);
}
printbinchar(10) will write into the console
1010
itoa is a library function that converts a single integer value to a string with the specified base. For example... itoa(1341, output, 10) will write in output string "1341". And of course itoa(9, output, 2) will write in the output string "1001".
The next function will print into the standard output the full binary representation of a character, that is, it will print all 8 bits, also if the higher bits are zero.
void printbincharpad(char c)
{
for (int i = 7; i >= 0; --i)
{
putchar( (c & (1 << i)) ? '1' : '0' );
}
putchar('\n');
}
printbincharpad(10) will write into the console
00001010
Now i present a function that prints out an entire string (without last null character).
void printstringasbinary(char* s)
{
// A small 9 characters buffer we use to perform the conversion
char output[9];
// Until the first character pointed by s is not a null character
// that indicates end of string...
while (*s)
{
// Convert the first character of the string to binary using itoa.
// Characters in c are just 8 bit integers, at least, in noawdays computers.
itoa(*s, output, 2);
// print out our string and let's write a new line.
puts(output);
// we advance our string by one character,
// If our original string was "ABC" now we are pointing at "BC".
++s;
}
}
Consider however that itoa don't adds padding zeroes, so printstringasbinary("AB1") will print something like:
1000001
1000010
110001
You could use CommitMonitor. This little tool uses very little RAM and notifies you of all the commits you've missed.
Your solution is fine.
Using ===
would just be silly in this case, as the field's value
will always be a String
.
if string.startswith('"'):
string = string[1:]
if string.endswith('"'):
string = string[:-1]
I just found out a workaround with shell by retrieving the previous command.
Press Ctrl-R to bring up reverse search command:
reverse-i-search
Then start typing git commit -m, this will add this as search command, and this brings the previous git commit with its message:
reverse-i-search`git commit -m`: git commit -m "message"
Enter. That's it!
(tested in Ubuntu shell)
string result = "i am '[email protected]'"; // string
int in1 = result.IndexOf('\''); // get the index of first quote
int in2 = result.IndexOf('\'', in1 + 1); // get the index of second
string quoted_text = result.Substring(in1 + 1, in2 - in1); // get the string between quotes
The python libs are obsolete with this function. I've done one that works correctly:
import os
import shutil
def copydirectorykut(src, dst):
os.chdir(dst)
list=os.listdir(src)
nom= src+'.txt'
fitx= open(nom, 'w')
for item in list:
fitx.write("%s\n" % item)
fitx.close()
f = open(nom,'r')
for line in f.readlines():
if "." in line:
shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
else:
if not os.path.exists(dst+'/'+line[:-1]):
os.makedirs(dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
f.close()
os.remove(nom)
os.chdir('..')
When we create new types by defining classes, we can take advantage of certain features of Python to make the new classes convenient to use. One of these features is "special methods", also referred to as "magic methods".
Special methods have names that begin and end with two underscores. We define them, but do not usually call them directly by name. Instead, they execute automatically under under specific circumstances.
It is convenient to be able to output the value of an instance of an object by using a print statement. When we do this, we would like the value to be represented in the output in some understandable unambiguous format. The repr special method can be used to arrange for this to happen. If we define this method, it can get called automatically when we print the value of an instance of a class for which we defined this method. It should be mentioned, though, that there is also a str special method, used for a similar, but not identical purpose, that may get precedence, if we have also defined it.
If we have not defined, the repr method for the Point3D class, and have instantiated my_point as an instance of Point3D, and then we do this ...
print my_point ... we may see this as the output ...
Not very nice, eh?
So, we define the repr or str special method, or both, to get better output.
**class Point3D(object):
def __init__(self,a,b,c):
self.x = a
self.y = b
self.z = c
def __repr__(self):
return "Point3D(%d, %d, %d)" % (self.x, self.y, self.z)
def __str__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1, 2, 3)
print my_point # __repr__ gets called automatically
print my_point # __str__ gets called automatically**
Output ...
(1, 2, 3) (1, 2, 3)
Your MySQL binaries should be somewhere under your XAMPP folder. Look for a /bin folder, and you'll find the mysql.exe client around. Let's assume it is in c:\xampp\mysql\bin, then you should fireup a command prompt in this folder.
That means, fire up "cmd", and type:
cd c:\xampp\mysql\bin
mysql.exe -u root --password
If you want to use mysqldump.exe, you should also find it there.
Log into your mysql server, and start typing your commands.
Hope it helps...
Just wanted to share a solution for unsigned long aswell.
unsigned long ToUInt(char* str)
{
unsigned long mult = 1;
unsigned long re = 0;
int len = strlen(str);
for(int i = len -1 ; i >= 0 ; i--)
{
re = re + ((int)str[i] -48)*mult;
mult = mult*10;
}
return re;
}
An example from official spring manual:
<bean id="inheritedTestBean" abstract="true"
class="org.springframework.beans.TestBean">
<property name="name" value="parent"/>
<property name="age" value="1"/>
</bean>
<bean id="inheritsWithDifferentClass"
class="org.springframework.beans.DerivedTestBean"
parent="inheritedTestBean" init-method="initialize">
<property name="name" value="override"/>
<!-- the age property value of 1 will be inherited from parent -->
</bean>
Is that what you was looking for? Updated link
Going off the answer from @BlondeFurious, here is some Java code to get each hexadecimal value from 100% to 0% alpha:
for (double i = 1; i >= 0; i -= 0.01) {
i = Math.round(i * 100) / 100.0d;
int alpha = (int) Math.round(i * 255);
String hex = Integer.toHexString(alpha).toUpperCase();
if (hex.length() == 1)
hex = "0" + hex;
int percent = (int) (i * 100);
System.out.println(String.format("%d%% — %s", percent, hex));
}
Output:
100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00
A JavaScript version is below:
var text = document.getElementById('text');_x000D_
for (var i = 1; i >= 0; i -= 0.01) {_x000D_
i = Math.round(i * 100) / 100;_x000D_
var alpha = Math.round(i * 255);_x000D_
var hex = (alpha + 0x10000).toString(16).substr(-2).toUpperCase();_x000D_
var perc = Math.round(i * 100);_x000D_
text.innerHTML += perc + "% — " + hex + " (" + alpha + ")</br>";_x000D_
}
_x000D_
<div id="text"></div>
_x000D_
You can also just Google "number to hex" where 'number' is any value between 0 and 255.
If you're using anaconda distribution of Python,
$ conda list | grep tensorflow
tensorflow 1.0.0 py35_0 conda-forge
To check it using Jupyter Notebook (IPython Notebook)
In [1]: import tensorflow as tf
In [2]: tf.__version__
Out[2]: '1.0.0'
Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.
note I changed the varchar2(32000) to CLOB
set serveroutput ON
CREATE TABLE testclob
(
id NUMBER,
c CLOB,
d VARCHAR2(4000)
);
DECLARE
reallybigtextstring CLOB := '123';
i INT;
BEGIN
WHILE Length(reallybigtextstring) <= 60000 LOOP
reallybigtextstring := reallybigtextstring
|| '000000000000000000000000000000000';
END LOOP;
INSERT INTO testclob
(id,
c,
d)
VALUES (0,
reallybigtextstring,
'done');
dbms_output.Put_line('I have finished inputting your clob: '
|| Length(reallybigtextstring));
END;
/
SELECT *
FROM testclob;
"I have finished inputting your clob: 60030"
Maybe I am missing something here, but did you allocate any memory for that PString before you accessed it?
PString * initializeString() {
PString *str;
str = (PString *) malloc(sizeof(PString));
str->length = &length;
return str;
}
First of all, dynamically pivot using pivot xml
again needs to be parsed. We have another way of doing this by storing the column names in a variable and passing them in the dynamic sql as below.
Consider we have a table like below.
If we need to show the values in the column YR
as column names and the values in those columns from QTY
, then we can use the below code.
declare
sqlqry clob;
cols clob;
begin
select listagg('''' || YR || ''' as "' || YR || '"', ',') within group (order by YR)
into cols
from (select distinct YR from EMPLOYEE);
sqlqry :=
'
select * from
(
select *
from EMPLOYEE
)
pivot
(
MIN(QTY) for YR in (' || cols || ')
)';
execute immediate sqlqry;
end;
/
RESULT
function logout(url){
var str = url.replace("http://", "http://" + new Date().getTime() + "@");
var xmlhttp;
if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4) location.reload();
}
xmlhttp.open("GET",str,true);
xmlhttp.setRequestHeader("Authorization","Basic YXNkc2E6")
xmlhttp.send();
return false;
}
Using Environment class we can get application. Properties values
@Autowired,
private Environment env;
and access using
String password =env.getProperty(your property key);
Simple but effective and assumes you know the checkbox will be found:
$("#some_id")[0].checked;
Gives true
/false
To merge one branch into another, such as merging "feature_x" branch into "master" branch:
git checkout master
git merge feature_x
This page is the first result for several search engines when looking for "git merge one branch into another". However, the original question is more specific and special case than the title would suggest.
It is also more complex than both the subject and the search expression. As such, this is a minimal but explanatory answer for the benefit of most visitors.
Port: In simple language, "Port" is a number used by a particular software to identify its data coming from internet.
Each software, like Skype, Chrome, Youtube has its own port number and that's how they know which internet data is for itself.
Socket: "IP address and Port " together is called "Socket". It is used by another computer to send data to one particular computer's particular software.
IP address is used to identify the computer and Port is to identify the software such as IE, Chrome, Skype etc.
In every home, there is one mailbox and multiple people. The mailbox is a host. Your own home mailbox is a localhost. Each person in a home has a room. All letters for that person are sent to his room, hence the room number is a port.
Here are the three web pages on which we found the answer. The most difficult part was setting up static ports for SQLEXPRESS.
Provisioning a SQL Server Virtual Machine on Windows Azure. These initial instructions provided 25% of the answer.
How to Troubleshoot Connecting to the SQL Server Database Engine. Reading this carefully provided another 50% of the answer.
How to configure SQL server to listen on different ports on different IP addresses?. This enabled setting up static ports for named instances (eg SQLEXPRESS.) It took us the final 25% of the way to the answer.
<video width="1000px" loop="true" autoplay="autoplay" controls muted></video>
worked for me
I think you can get this error if your database model is not correct and the underlying data contains a null which the model is attempting to map to a non-null object.
For example, some auto-generated models can attempt to map nvarchar(1) columns to char rather than string and hence if this column contains nulls it will throw an error when you attempt to access the data.
Note, LinqPad has a compatibility option if you want it to generate a model like that, but probably doesn't do this by default, which might explain it doesn't give you the error.
Writing this answer for people who wants to get a file to download with specific content from javascript. I was struggling with the same thing.
const data = {name: 'Ronn', age: 27}; //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile'; //filename to download
a.click();
Check Blob documentation here - Blob MDN
People will learn your interface from code completion in their IDE or in Javadoc, not from reading the source. So there's no point in putting "public" in the source - nobody's reading the source.
This is backwards from what Bootstrap is designed for, but you can do this:
<div class="row">
<div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
<div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
<div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
</div>
This will make each element 33.3% wide on small and extra small devices but 100% wide on medium and larger devices.
JSFiddle: http://jsfiddle.net/jdwire/sggt8/embedded/result/
I think you're looking for the visible-xs
and/or visible-sm
classes. These will let you make certain elements only visible to small screen devices.
For example, if you want a element to only be visible to small and extra-small devices, do this:
<div class="visible-xs visible-sm">You're using a fairly small device.</div>
To show it only for larger screens, use this:
<div class="hidden-xs hidden-sm">You're probably not using a phone.</div>
See http://getbootstrap.com/css/#responsive-utilities-classes for more information.
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
Following line in above code is not working
DB_PASSWORD=$(eval echo ${DB_PASSWORD} | base64 --decode)
Correct line is:
DB_PASSWORD=`echo $PASSWORD|base64 -d`
And save the password in other file as PASSWORD.
Maybe I'm a little bit late :), but here is a nice and brief solution by chrisjhoughton, which allows to perform a callback function when the wait is over.
https://gist.github.com/chrisjhoughton/7890303
var waitForEl = function(selector, callback) {
if (jQuery(selector).length) {
callback();
} else {
setTimeout(function() {
waitForEl(selector, callback);
}, 100);
}
};
waitForEl(selector, function() {
// work the magic
});
If you need to pass parameters to a callback function, you can use it this way:
waitForEl("#" + elDomId, () => callbackFunction(param1, param2));
But be careful! This solution by default can fall into a trap of an infinite loop.
Several improvements of the topicstarter's suggestion are also provided in The GitHub thread.
Enjoy!
System.Text.ASCIIEncoding.Unicode.GetByteCount(yourString);
Or
System.Text.ASCIIEncoding.ASCII.GetByteCount(yourString);
This is for vmware workstation 6.5
It is pretty far down.
select Create new virtual machine ->
select custom ->
on compatibility page take defaults ->
check I will install os later
-> click through several pages choosing other for OS, give it a name, make sure it IS NOT in the same folder as the VMDK file. Choose bridged network.
You will now see a screen asking to select disk, select existing virual disk. then browse and select the VMDK file
Operators first()
and take(1)
aren't the same.
The first()
operator takes an optional predicate
function and emits an error
notification when no value matched when the source completed.
For example this will emit an error:
import { EMPTY, range } from 'rxjs';
import { first, take } from 'rxjs/operators';
EMPTY.pipe(
first(),
).subscribe(console.log, err => console.log('Error', err));
... as well as this:
range(1, 5).pipe(
first(val => val > 6),
).subscribe(console.log, err => console.log('Error', err));
While this will match the first value emitted:
range(1, 5).pipe(
first(),
).subscribe(console.log, err => console.log('Error', err));
On the other hand take(1)
just takes the first value and completes. No further logic is involved.
range(1, 5).pipe(
take(1),
).subscribe(console.log, err => console.log('Error', err));
Then with empty source Observable it won't emit any error:
EMPTY.pipe(
take(1),
).subscribe(console.log, err => console.log('Error', err));
Jan 2019: Updated for RxJS 6
I don't think there's a NULL column value, when rows are returned within a datareader using the column name.
If you do datareader["columnName"].ToString();
it will always give you a value that can be a empty string (String.Empty
if you need to compare).
I would use the following and wouldn't worry too much:
employee.FirstName = sqlreader["columnNameForFirstName"].ToString();
Most previous answers are correct and my answer is very similar to aaronasterling, you could also do 3 single quotations s1='''some very long string............'''
Set the ValueMember
/DisplayMember
properties to the name of the properties of your Language
objects.
class Language
{
string text;
string value;
public string Text
{
get
{
return text;
}
}
public string Value
{
get
{
return value;
}
}
public Language(string text, string value)
{
this.text = text;
this.value = value;
}
}
...
combo.DisplayMember= "Text";
combo.ValueMember = "Value";
combo.Items.Add(new Language("English", "en"));
Sorry EMS, but I actually just got another response from the matplotlib mailling list (Thanks goes out to Benjamin Root).
The code I am looking for is adjusting the savefig call to:
fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
#Note that the bbox_extra_artists must be an iterable
This is apparently similar to calling tight_layout, but instead you allow savefig to consider extra artists in the calculation. This did in fact resize the figure box as desired.
import matplotlib.pyplot as plt
import numpy as np
plt.gcf().clear()
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')
This produces:
[edit] The intent of this question was to completely avoid the use of arbitrary coordinate placements of arbitrary text as was the traditional solution to these problems. Despite this, numerous edits recently have insisted on putting these in, often in ways that led to the code raising an error. I have now fixed the issues and tidied the arbitrary text to show how these are also considered within the bbox_extra_artists algorithm.
mp3 files sometimes throw strange mime types as per this answer: https://stackoverflow.com/a/2755288/14482130
If you are doing some user validation do not allow 'application/octet-stream' or 'application/x-zip-compressed' as suggested above since they can contain be .exe or other potentially dangerous files.
In order to validate when mime type gives a false negative you can use fleep as per this answer https://stackoverflow.com/a/52570299/14482130 to finish the validation.
I'm on OSX 10.10.2, and succeeded in using JPype.
Ran into installation problems with Jnius (others have too), Javabridge installed but gave mysterious errors when I tried to use it, PyJ4 has this inconvenience of having to start a Gateway server in Java first, JCC wouldn't install. Finally, JPype ended up working. There's a maintained fork of JPype on Github. It has the major advantages that (a) it installs properly and (b) it can very efficiently convert java arrays to numpy array (np_arr = java_arr[:]
)
The installation process was:
git clone https://github.com/originell/jpype.git
cd jpype
python setup.py install
And you should be able to import jpype
The following demo worked:
import jpype as jp
jp.startJVM(jp.getDefaultJVMPath(), "-ea")
jp.java.lang.System.out.println("hello world")
jp.shutdownJVM()
When I tried calling my own java code, I had to first compile (javac ./blah/HelloWorldJPype.java
), and I had to change the JVM path from the default (otherwise you'll get inexplicable "class not found" errors). For me, this meant changing the startJVM command to:
jp.startJVM('/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/MacOS/libjli.dylib', "-ea")
c = jp.JClass('blah.HelloWorldJPype')
# Where my java class file is in ./blah/HelloWorldJPype.class
...
list(your_iterator)
The limit for the length of a command line is not imposed by the shell, but by the operating system. This limit is usually in the range of hundred kilobytes. POSIX denotes this limit ARG_MAX
and on POSIX conformant systems you can query it with
$ getconf ARG_MAX # Get argument limit in bytes
E.g. on Cygwin this is 32000, and on the different BSDs and Linux systems I use it is anywhere from 131072 to 2621440.
If you need to process a list of files exceeding this limit, you might want to look at the xargs
utility, which calls a program repeatedly with a subset of arguments not exceeding ARG_MAX
.
To answer your specific question, yes, it is possible to attempt to run a command with too long an argument list. The shell will error with a message along "argument list too long".
Note that the input to a program (as read on stdin or any other file descriptor) is not limited (only by available program resources). So if your shell script reads a string into a variable, you are not restricted by ARG_MAX
. The restriction also does not apply to shell-builtins.
In my case this was because a file named ociw32.dll had been placed in c:\windows\system32. This is however only allowed to exist in c:\oracle\11.2.0.3\bin.
Deleting the file from system32, which had been placed there by an installation of Crystal Reports, fixed this issue
A sha256 is 256 bits long -- as its name indicates.
Since sha256 returns a hexadecimal representation, 4 bits are enough to encode each character (instead of 8, like for ASCII), so 256 bits would represent 64 hex characters, therefore you need a varchar(64)
, or even a char(64)
, as the length is always the same, not varying at all.
And the demo :
$hash = hash('sha256', 'hello, world!');
var_dump($hash);
Will give you :
$ php temp.php
string(64) "68e656b251e67e8358bef8483ab0d51c6619f3e7a1a9f0e75838d41ff368f728"
i.e. a string with 64 characters.
Open Visual Studio then select File
-> New
-> Project
Select Visual C#
-> Class library
Compile Project Or Build the solution, to create Dll File
Go to the class library folder (Debug Folder)
This is what you have to do since sess.createCriteria is deprecated:
CriteriaBuilder builder = getSession().getCriteriaBuilder();
CriteriaQuery<User> q = builder.createQuery(User.class);
Root<User> usr = q.from(User.class);
ParameterExpression<String> p = builder.parameter(String.class);
q.select(usr).where(builder.like(usr.get("name"),p))
.orderBy(builder.asc(usr.get("name")));
TypedQuery<User> query = getSession().createQuery(q);
query.setParameter(p, "%" + Main.filterName + "%");
List<User> list = query.getResultList();
Thinking that manually setting up .gitmodules
is enough is WRONG
My local git version 2.22.0
as of this writing.
So I came to this thread wondering why wasn't git submodule init
working; I setup the .gitmodules
file and proceeded to do git submodule init
...
IMPORTANT
git submodule add company/project.git includes/project
is required (when adding the module for the first time), this will:
.git/config
.gitmodules
fileincludes/project
in this example).you must then git commit
after you have added the submodule, this will commit .gitmodules
and the tracked submodule location.
When the project is cloned again, it will have the .gitmodules
and the empty submodules directory (e.g. includes/project
in this example). At this point .git/config
does not have submodule config yet, until git submodule init
is run, and remember this only works because .gitmodules
AND includes/project
are tracked in the main git repo.
Also for reference see:
import os
import shutil
# Gather directory contents
contents = [os.path.join(target_dir, i) for i in os.listdir(target_dir)]
# Iterate and remove each item in the appropriate manner
[os.remove(i) if os.path.isfile(i) or os.path.islink(i) else shutil.rmtree(i) for i in contents]
An earlier comment also mentions using os.scandir in Python 3.5+. For example:
import os
import shutil
with os.scandir(target_dir) as entries:
for entry in entries:
if entry.is_file() or entry.is_symlink():
os.remove(entry.path)
elif entry.is_dir():
shutil.rmtree(entry.path)
If you want your JSON to have a validated Typescript type, you will need to do that validation work yourself. This is nothing new. In plain Javascript, you would need to do the same.
I like to express my validation logic as a set of "transforms". I define a Descriptor
as a map of transforms:
type Descriptor<T> = {
[P in keyof T]: (v: any) => T[P];
};
Then I can make a function that will apply these transforms to arbitrary input:
function pick<T>(v: any, d: Descriptor<T>): T {
const ret: any = {};
for (let key in d) {
try {
const val = d[key](v[key]);
if (typeof val !== "undefined") {
ret[key] = val;
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
throw new Error(`could not pick ${key}: ${msg}`);
}
}
return ret;
}
Now, not only am I validating my JSON input, but I am building up a Typescript type as I go. The above generic types ensure that the result infers the types from your "transforms".
In case the transform throws an error (which is how you would implement validation), I like to wrap it with another error showing which key caused the error.
In your example, I would use this as follows:
const value = pick(JSON.parse('{"name": "Bob", "error": false}'), {
name: String,
error: Boolean,
});
Now value
will be typed, since String
and Boolean
are both "transformers" in the sense they take input and return a typed output.
Furthermore, the value
will actually be that type. In other words, if name
were actually 123
, it will be transformed to "123"
so that you have a valid string. This is because we used String
at runtime, a built-in function that accepts arbitrary input and returns a string
.
You can see this working here. Try the following things to convince yourself:
const value
definition to see that the pop-over shows the correct type."Bob"
to 123
and re-run the sample. In your console, you will see that the name has been properly converted to the string "123"
.The best solution is using DATE() function and extracting yy, mm, and dd from the string with RIGHT(), MID() and LEFT() functions, the final will be some DATE(LEFT(),MID(),RIGHT()), details here
BOOST_VERSION is defined in the boost header file version.hpp.
You have to pass the route parameters to the route
method, for example:
<li><a href="{{ route('user.profile', $nickname) }}">Profile</a></li>
<li><a href="{{ route('user.settings', $nickname) }}">Settings</a></li>
It's because, both routes have a {nickname}
in the route declaration. I've used $nickname
for example but make sure you change the $nickname
to appropriate value/variable, for example, it could be something like the following:
<li><a href="{{ route('user.settings', auth()->user()->nickname) }}">Settings</a></li>
This can happen when trying to install a debug/unsigned APK on top of a signed release APK from the Play store.
H:\>adb install -r "Signed.apk"
2909 KB/s (220439 bytes in 0.074s)
pkg: /data/local/tmp/Signed.apk
Success
H:\>adb install -r "AppName.apk"
2753 KB/s (219954 bytes in 0.078s)
pkg: /data/local/tmp/AppName.apk
Failure [INSTALL_FAILED_VERSION_DOWNGRADE]
The solution to this is to uninstall and then reinstall or re run it from the IDE.
Try downloading the certificates/profiles directly from the member centre rather than doing it from Xcode.
It worked for me when I manually downloaded them from the member centre.
CSS for IE10+ and IE9
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
/* IE10+ styles */
}
@media screen\0 {
/* IE8,9,10 styles*/
}
>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM
Try replacing %I
with %H
.
HttpWebRequest request =(HttpWebRequest)WebRequest.Create("some url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)";
request.Accept = "/";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
doc.Save(request.GetRequestStream());
HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
Hope it helps
I'm adding this answer because after researching the web, I ended up at this answer but still didn't know which subfolder of the IIS logs folder to look in.
If your server has multiple websites, you will need to know the IIS ID for the site. An easy way to get this in IIS is to simply click on the Sites folder in the left panel. The ID for each site is shown in the right panel.
Once you know the ID, let's call it n, the corresponding logs are in the W3SVCn subfolder of the IIS logs folder. So, if your website ID is 4, say, and the IIS logs are in the default location, then the logs are in this folder:
%SystemDrive%\inetpub\logs\LogFiles\W3SVC4
Acknowlegements:
The reason why your X-axis plots frequencies only till 500 Hz is your command statement 'f = Fs/2*linspace(0,1,NFFT/2+1);'. Your Fs is 1000. So when you divide it by 2 & then multiply by values ranging from 0 to 1, it returns a vector of length NFFT/2+1. This vector consists of equally spaced frequency values, ranging from 0 to Fs/2 (i.e. 500 Hz). Since you plot using 'plot(f,2*abs(Y(1:NFFT/2+1)))' command, your X-axis limit is 500 Hz.
NSArray *array = [NSArray arrayWithObjects:@"One",@"Two",@"Three", nil];
NSString *stringFromArray = [array componentsJoinedByString:@" "];
The first line initializes an array with objects. The second line joins all elements of that array by adding the string inside the "" and returns a string.
I also put an answer there, but the article @Colonel Panic's update refers to suggests forcing TLS 1.2. In the future, when TLS 1.2 is compromised or just superceded, having your code stuck to TLS 1.2 will be considered a deficiency. Negotiation to TLS1.2 is enabled in .Net 4.6 by default. If you have the option to upgrade your source to .Net 4.6, I would highly recommend that change over forcing TLS 1.2.
If you do force TLS 1.2, strongly consider leaving some type of breadcrumb that will remove that force if you do upgrade to the 4.6 or higher framework.
public static extern int FindWindow(string lpClassName, String lpWindowName);
In order to find the window, you need the class name of the window. Here are some examples:
C#:
const string lpClassName = "Winamp v1.x";
IntPtr hwnd = FindWindow(lpClassName, null);
Example from a program that I made, written in VB:
hParent = FindWindow("TfrmMain", vbNullString)
In order to get the class name of a window, you'll need something called Win Spy
Once you have the handle of the window, you can send messages to it using the SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam)
function.
hWnd
, here, is the result of the FindWindow
function. In the above examples, this will be hwnd
and hParent
. It tells the SendMessage
function which window to send the message to.
The second parameter, wMsg
, is a constant that signifies the TYPE of message that you are sending. The message might be a keystroke (e.g. send "the enter key" or "the space bar" to a window), but it might also be a command to close the window (WM_CLOSE
), a command to alter the window (hide it, show it, minimize it, alter its title, etc.), a request for information within the window (getting the title, getting text within a text box, etc.), and so on. Some common examples include the following:
Public Const WM_CHAR = &H102
Public Const WM_SETTEXT = &HC
Public Const WM_KEYDOWN = &H100
Public Const WM_KEYUP = &H101
Public Const WM_LBUTTONDOWN = &H201
Public Const WM_LBUTTONUP = &H202
Public Const WM_CLOSE = &H10
Public Const WM_COMMAND = &H111
Public Const WM_CLEAR = &H303
Public Const WM_DESTROY = &H2
Public Const WM_GETTEXT = &HD
Public Const WM_GETTEXTLENGTH = &HE
Public Const WM_LBUTTONDBLCLK = &H203
These can be found with an API viewer (or a simple text editor, such as notepad) by opening (Microsoft Visual Studio Directory)/Common/Tools/WINAPI/winapi32.txt
.
The next two parameters are certain details, if they are necessary. In terms of pressing certain keys, they will specify exactly which specific key is to be pressed.
C# example, setting the text of windowHandle
with WM_SETTEXT
:
x = SendMessage(windowHandle, WM_SETTEXT, new IntPtr(0), m_strURL);
More examples from a program that I made, written in VB, setting a program's icon (ICON_BIG
is a constant which can be found in winapi32.txt
):
Call SendMessage(hParent, WM_SETICON, ICON_BIG, ByVal hIcon)
Another example from VB, pressing the space key (VK_SPACE
is a constant which can be found in winapi32.txt
):
Call SendMessage(button%, WM_KEYDOWN, VK_SPACE, 0)
Call SendMessage(button%, WM_KEYUP, VK_SPACE, 0)
VB sending a button click (a left button down, and then up):
Call SendMessage(button%, WM_LBUTTONDOWN, 0, 0&)
Call SendMessage(button%, WM_LBUTTONUP, 0, 0&)
No idea how to set up the listener within a .DLL, but these examples should help in understanding how to send the message.
Starting an Activity is not the right approach for this behavior. Instead have your BroadcastReceiver use an intent to start a Service which can continue to run as long as possible. (See http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle)
See also Persistent service
I am using ipython 2.0, so just two line.
from IPython.display import Image
Image(filename='output1.png')
Class names should be nouns in UpperCamelCase, with the first letter of every word capitalised. Use whole words — avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). The naming conventions can be read over here:
http://www.oracle.com/technetwork/java/codeconventions-135099.html
.val didnt work for me, because i'm grabbing the value attribute server side and the value wasn't always updated. so i used :
var counter = 0;
$('a.myClickableLink').click(function(event){
event.preventDefault();
counter++;
...
$('#myInput').attr('value', counter);
}
Hope it helps someone.
Is there a reason why you aren't using a table variable and the aggregate SUM operator, instead of a cursor? SQL excels at set-oriented operations. 99.87% of the time that you find yourself using a cursor, there's a set-oriented alternative that's more efficient:
declare @MonthsSale table
(
MonthNumber int,
MonthName varchar(9),
MonthSale decimal(18,2)
)
insert into @MonthsSale
select
1, 'January', 100.00
union select
2, 'February', 200.00
union select
3, 'March', 300.00
union select
4, 'April', 400.00
union select
5, 'May', 500.00
union select
6, 'June', 600.00
union select
7, 'July', 700.00
union select
8, 'August', 800.00
union select
9, 'September', 900.00
union select
10, 'October', 1000.00
union select
11, 'November', 1100.00
union select
12, 'December', 1200.00
select * from @MonthsSale
select SUM(MonthSale) as [TotalSales] from @MonthsSale
A little late here but generally I've seen this problem occur when you get a 'tablespace full' error when running in a 'innodb_file_per_table' mode. Without going into too much detail (more here), the database server's tablespace is defined by the innodb_data_file_path setting and by default is rather small. Even made larger, the 'tablespace full' can still occur with larger queries and such (lots of non-table 'stuff' is stored in there, undo logs, caches, etc...).
Anyways, I found that if you look in the OS directory where the files-per-table are stored, /var/lib/mysql by default on OSX, /usr/local/var/mysql with homebrew iirc, you'll find an orphaned tablename.ibd file without it's normal companion tablename.frm file. If you move that .ibd file to a safe temporary location (just to be safe) that should fix the problem.
$ ls /var/lib/mysql
table1.frm
table1.idb
table2.frm
table2.ibd
table3.idb <- problem table, no table3.frm
table4.frm
table4.idb
$ mkdir /tmp/mysql_orphans
$ mv /var/lib/mysql/table3.ibd /tmp/mysql_orphans/
One caveat though, make sure what ever is causing the problem originally, e.g. long running query, locked table, etc... has been cleared. Otherwise you just end up with another orphaned .ibd file when you try a second time.
Use hidden input in your login page. Like:
<input name="location" value="<?php if(!empty($_SERVER['HTTP_REFERER'])) echo $_SERVER['HTTP_REFERER']; else echo 'products.php'; ?>" type="text" style="display: none;" />
This code to check the network availability for all versions of Android including Android 9.0 and above:
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
// For 29 api or above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
} else return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Don't forget to add network-state permission in your manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Also, add @SuppressWarnings( "deprecation" ) before the method to avoid android studio deprecation warning.
NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24'
- it is a performance killer:
DATE()
for all rows, including those, that don't matchIt is much faster to use
SELECT * FROM tablename
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'
as this will allow index use without calculation.
EDIT
As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read
SELECT * FROM tablename
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'
The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.
Switch to the develop branch:
$ git checkout develop
Creates feature/foo branch of develop.
$ git checkout -b feature/foo develop
merge the changes to develop without a fast-forward
$ git checkout develop
$ git merge --no-ff myFeature
Now push changes to the server
$ git push origin develop
$ git push origin feature/foo
Use http://[jenkins-server]/exit
This page shows how to use URL commands.
Guys why bother with all the faff. This works perfectly. No code required
<RichTextBox>
<FlowDocument>
<Paragraph>
<Run Text="{Binding Mytextbinding}"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
.ui-slider .ui-slider-handle{
width:50px;
height:50px;
background:url(../images/slider_grabber.png) no-repeat; overflow: hidden;
position:absolute;
top: -10px;
border-style:none;
}
You can also choose between a dark or light ReCaptcha theme. I used this in one of my Angular 8 Apps
Yes. It's like the difference between a tollbooth and a door. The ManualResetEvent
is the door, which needs to be closed (reset) manually. The AutoResetEvent
is a tollbooth, allowing one car to go by and automatically closing before the next one can get through.
I consider this simpler than any prior correct answer. I'll also throw in javadoc. :-)
/**
* Converts the given string to title case, where the first
* letter is capitalized and the rest of the string is in
* lower case.
*
* @param s a string with unknown capitalization
* @return a title-case version of the string
*/
public static String toTitleCase(String s)
{
if (s.isEmpty())
{
return s;
}
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
Strings of length 1 do not needed to be treated as a special case because s.substring(1)
returns the empty string when s
has length 1.
As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).
Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from
.
Using compose (1.6.2 in my machine), the docker-compose.yml
file would read:
version: "2"
services:
nginx:
build:
context: .
dockerfile: nginx/Dockerfile
ports:
- "80:80"
links:
- fpm
volumes_from:
- data
fpm:
image: php:fpm
volumes_from:
- data
data:
build:
context: .
dockerfile: data/Dockerfile
volumes:
- /var/www/html
Note that data
publishes a volume that is linked to the nginx
and fpm
services. Then the Dockerfile
for the data service, that contains your source code:
FROM busybox
# content
ADD path/to/source /var/www/html
And the Dockerfile
for nginx, that just replaces the default config:
FROM nginx
# config
ADD config/default.conf /etc/nginx/conf.d
For the sake of completion, here's the config file required for the example to work:
server {
listen 0.0.0.0:80;
root /var/www/html;
location / {
index index.php index.html;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass fpm:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
}
which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT
, which is fpm:9000
thanks to the hostnames defined by compose, and the SCRIPT_FILENAME
).
You can use https://ip-api.io/ to get country name, city name, latitude and longitude. It supports IPv6.
As a bonus it will tell if ip address is a tor node, public proxy or spammer.
Php Code:
$result = json_decode(file_get_contents('http://ip-api.io/json/64.30.228.118'));
var_dump($result);
Output:
{
"ip": "64.30.228.118",
"country_code": "US",
"country_name": "United States",
"region_code": "FL",
"region_name": "Florida",
"city": "Fort Lauderdale",
"zip_code": "33309",
"time_zone": "America/New_York",
"latitude": 26.1882,
"longitude": -80.1711,
"metro_code": 528,
"suspicious_factors": {
"is_proxy": false,
"is_tor_node": false,
"is_spam": false,
"is_suspicious": false
}
Include servlet-api.jar from your server lib folder.
Do this step
For this, you would use a goto statement. Such as:
switch(value){
case 1:
goto case 3;
case 2:
goto case 3;
case 3:
DoCase123();
//This would work too, but I'm not sure if it's slower
case 4:
goto case 5;
case 5:
goto case 6;
case 6:
goto case 7;
case 7:
DoCase4567();
}
It gives you the remainder of a division.
int c=11, d=5;
cout << (c/d) * d + c % d; // gives you the value of c
Have you tried turning it off and on again? :-)
I had the same issue after upgrading to Docker 1.10.1 on my Mac. I did the following:
On the Docker Quickstart Terminal
$ exit
$ exit
then
docker-machine kill default
then restarted Docker Quickstart Terminal
This solved my problem.
You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?
You could use str.split
to do this.
s = "<alpha.Customer[cus_Y4o9qMEZAugtnW] active_card=<alpha.AlphaObject[card]\
...>, created=1324336085, description='Customer for My Test App',\
livemode=False>"
val = s.split('[', 1)[1].split(']')[0]
Then we have:
>>> val
'cus_Y4o9qMEZAugtnW'
In my case, I was copying and pasting code from my other classes, so I did not notice that the getter code was bad written:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "credito")
public Set getConceptoses() {
return this.letrases;
}
public void setConceptoses(Set conceptoses) {
this.conceptoses = conceptoses;
}
All references conceptoses but if you look at the get says letrases
I'll try to answer all your questions by addressing the larger question: How can I sync data between a webserver and an android app?
Syncing data between your webserver and an android app requires a couple of different components on your android device.
This is how your phone actually stores the data it receives from the webserver. One possible method for accomplishing this is writing your own custom ContentProvider backed by a Sqlite database. A decent tutorial for a content provider can be found here: http://thinkandroid.wordpress.com/2010/01/13/writing-your-own-contentprovider/
A ContentProvider defines a consistent interface to interact with your stored data. It could also allow other applications to interact with your data if you wanted. Behind your ContentProvider could be a Sqlite database, a Cache, or any arbitrary storage mechanism.
While I would certainly recommend using a ContentProvider with a Sqlite database you could use any java based storage mechanism you wanted.
This is the format you use to send the data between your webserver and your android app. The two most popular formats these days are XML and JSON. When choosing your format, you should think about what sort of serialization libraries are available. I know off-hand that there's a fantastic library for json serialization called gson: https://github.com/google/gson, although I'm sure similar libraries exist for XML.
You'll want some sort of asynchronous task which can get new data from your server and refresh the mobile content to reflect the content of the server. You'll also want to notify the server whenever you make local changes to content and want to reflect those changes. Android provides the SyncAdapter pattern as a way to easily solve this pattern. You'll need to register user accounts, and then Android will perform lots of magic for you, and allow you to automatically sync. Here's a good tutorial: http://www.c99.org/2010/01/23/writing-an-android-sync-provider-part-1/
As for how you identify if the records are the same, typically you'll create items with a unique id which you store both on the android device and the server. You can use that to make sure you're referring to the same reference. Furthermore, you can store column attributes like "updated_at" to make sure that you're always getting the freshest data, or you don't accidentally write over newly written data.
The obvious, simple answer is missing, so for completeness:
But is there any way to have values in an object literal's properties depend on other properties declared earlier?
No. All of the solutions here defer it until after the object is created (in various ways) and then assign the third property. The simplest way is to just do this:
var foo = {
a: 5,
b: 6
};
foo.c = foo.a + foo.b;
All others are just more indirect ways to do the same thing. (Felix's is particularly clever, but requires creating and destroying a temporary function, adding complexity; and either leaves an extra property on the object or [if you delete
that property] impacts the performance of subsequent property accesses on that object.)
If you need it to all be within one expression, you can do that without the temporary property:
var foo = function(o) {
o.c = o.a + o.b;
return o;
}({a: 5, b: 6});
Or of course, if you need to do this more than once:
function buildFoo(a, b) {
var o = {a: a, b: b};
o.c = o.a + o.b;
return o;
}
then where you need to use it:
var foo = buildFoo(5, 6);
Try this code
var today = DateTime.Today;
var q = db.Games.Where(t => DbFunctions.TruncateTime(t.StartDate) <= today);
I think another place to look is /var/lib
.
If you go there you can see three mysql folders with 'interesting' permissions:
user group
mysql mysql
Here is what I did to solve my problem with root password:
after running
sudo apt-get purge mysql*
sudo rm -rf /etc/mysql
I also ran the following (instead of my_username put yours):
cd /var/lib
sudo chown --from=mysql <my_username> mysql* -R
sudo rm -rf mysql*
And then:
sudo apt-get install mysql-server
which prompted me to select a new root password. I hope it helps
I would use a https://docs.flutter.io/flutter/widgets/Stack-class.html to be able to freely position widgets.
To create circles
new BoxDecoration(
color: effectiveBackgroundColor,
image: backgroundImage != null
? new DecorationImage(image: backgroundImage, fit: BoxFit.cover)
: null,
shape: BoxShape.circle,
),
and https://docs.flutter.io/flutter/widgets/Transform/Transform.rotate.html to position the white dots.
Working jsbin: http://jsbin.com/ANAYeDU/4/edit
Main bit:
function answers()
{
var element = document.getElementById("mySelect");
var elementValue = element.value;
if(elementValue == "To measure time"){
alert("Thats correct");
}
}
You can able to consume a Restful Web service in Spring using RestTemplate.class.
Example :
public class Application {
public static void main(String args[]) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> call= restTemplate.getForEntity("http://localhost:8080/SpringExample/hello",String.class);
System.out.println(call.getBody())
}
}
Tested on both spark-shell
version 1.6.3
and spark2-shell
version 2.3.0.2.6.5.179-4
, you can directly pipe to the shell's stdin like
spark-shell <<< "1+1"
or in your use case,
spark-shell < file.spark
Know the master key yourself. Don't hard code it.
Use py-bcrypt
(bcrypt), powerful hashing technique to generate a password yourself.
Basically you can do this (an idea...)
import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)
save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.
This is basically how login should work these days.
It really depends on the application. For a normal project, I would recommend using only Access, but sometimes, the needs are specific and an Excel spreadsheet might be more appropriate.
For instance, in a project I had to develop for a former employer, the need was to give access to different persons on forms(pre-filled with some data, different for each person) and have them complete them, then re-import the data.
Since the form was using heavy number crunching, it made more sense to build it in Excel.
The Excel workbooks for the different persons were built from a template using VBA, then saved in a proper location, with the access rights on the folder.
All workbooks were attached as External tables to the workbooks, using named ranges. I could then query the workbooks from the Access Application. All administrative stuff was made from the db, but the end users only had access to their respective workbook.
Developping an Excel/Access application this way was a pleasant experience and the UI was more user-friendly than it would have been using Access.
I have to say that in this case, it would have taken a lot more time doing it in Access than it took using Excel. Also, the Application Object Model seems better though in Excel than in Access.
If you plan to use Excel as a front-end, do not forget to lock all the cells, but the editable ones and don't be affraid to use masked rows and columnns (to construct output tables for the access database, to perform intermediate calculations, etc).
You should also turn off autocalculation while importing data.
Stored procedures are a batch of SQL statements that can be executed in a couple of ways. Most major DBMs support stored procedures; however, not all do. You will need to verify with your particular DBMS help documentation for specifics. As I am most familiar with SQL Server I will use that as my samples.
To create a stored procedure the syntax is fairly simple:
CREATE PROCEDURE <owner>.<procedure name>
<Param> <datatype>
AS
<Body>
So for example:
CREATE PROCEDURE Users_GetUserInfo
@login nvarchar(30)=null
AS
SELECT * from [Users]
WHERE ISNULL(@login,login)=login
A benefit of stored procedures is that you can centralize data access logic into a single place that is then easy for DBA's to optimize. Stored procedures also have a security benefit in that you can grant execute rights to a stored procedure but the user will not need to have read/write permissions on the underlying tables. This is a good first step against SQL injection.
Stored procedures do come with downsides, basically the maintenance associated with your basic CRUD operation. Let's say for each table you have an Insert, Update, Delete and at least one select based on the primary key, that means each table will have 4 procedures. Now take a decent size database of 400 tables, and you have 1600 procedures! And that's assuming you don't have duplicates which you probably will.
This is where using an ORM or some other method to auto generate your basic CRUD operations has a ton of merit.
I've just applied Nepster's solution and works like a charm. There is a minor modification to run it from a Fragment.
To your Fragment
// sending intent to onNewIntent() of MainActivity
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("transparent_nav_changed", true);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
And to your OnNewIntent() of the Activity you would like to restart.
// recreate activity when transparent_nav was just changed
if (getIntent().getBooleanExtra("transparent_nav_changed", false)) {
finish(); // finish and create a new Instance
Intent restarter = new Intent(MainActivity.this, MainActivity.class);
startActivity(restarter);
}
First check with dmesg | grep tty
if system recognize your adapter.
Then try to run minicom with sudo minicom -s
, go to "Serial port setup" and change the first line to /dev/ttyUSB0
.
Don't forget to save config as default with "Save setup as dfl". It works for me on Ubuntu 11.04 on VirtualBox.
Thanks for the replies, it works!
And since the source files are in mixed formats, I added a list of source formats to be tried in sequence (sourceFormats
), and on UnicodeDecodeError
I try the next format:
from __future__ import with_statement
import os
import sys
import codecs
from chardet.universaldetector import UniversalDetector
targetFormat = 'utf-8'
outputDir = 'converted'
detector = UniversalDetector()
def get_encoding_type(current_file):
detector.reset()
for line in file(current_file):
detector.feed(line)
if detector.done: break
detector.close()
return detector.result['encoding']
def convertFileBestGuess(filename):
sourceFormats = ['ascii', 'iso-8859-1']
for format in sourceFormats:
try:
with codecs.open(fileName, 'rU', format) as sourceFile:
writeConversion(sourceFile)
print('Done.')
return
except UnicodeDecodeError:
pass
def convertFileWithDetection(fileName):
print("Converting '" + fileName + "'...")
format=get_encoding_type(fileName)
try:
with codecs.open(fileName, 'rU', format) as sourceFile:
writeConversion(sourceFile)
print('Done.')
return
except UnicodeDecodeError:
pass
print("Error: failed to convert '" + fileName + "'.")
def writeConversion(file):
with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:
for line in file:
targetFile.write(line)
# Off topic: get the file list and call convertFile on each file
# ...
(EDIT by Rudro Badhon: this incorporates the original try multiple formats until you don't get an exception as well as an alternate approach that uses chardet.universaldetector)
Add /y
to the command line of xcopy
:
Example:
xcopy /y c:\mmyinbox\test.doc C:\myoutbox
I have always taken it to mean absent. Here are four cases in the C language that matches to this use of absent
R f(void)
- Function parameters are absentvoid f(P)
- Return value is absentvoid *p
- Type of what is pointed to is absent(void) p
- Usage of value is absentOther C descendants use it for other things. The D
programming language uses it for cases where an initializer is absent
T t = void;
- initializing value is absentBelow code worked for me:
<input #fileInput type="file" id="avatar" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" />
application/pdf means .pdf
application/msword means .doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document means .docx
Check the mozilla documentation on window.open. The window features ("directory=...,...,height=350") etc. arguments should be a string:
window.open('/pageaddress.html','winname',"directories=0,titlebar=0,toolbar=0,location=0,status=0,menubar=0,scrollbars=no,resizable=no,width=400,height=350");
Try if that works in your browsers. Note that some of the features might be overridden by user preferences, such as "location" (see doc.)
I'm using a popup to show the map in a new window. I'm using the following url
https://www.google.com/maps?z=15&daddr=LATITUDE,LONGITUDE
HTML snippet
<a target='_blank' href='https://www.google.com/maps?z=15&daddr=${location.latitude},${location.longitude}'>Calculate route</a>
I just realized that the hist
documentation is explicit about what to do when you already have an np.histogram
counts, bins = np.histogram(data)
plt.hist(bins[:-1], bins, weights=counts)
The important part here is that your counts are simply the weights. If you do it like that, you don't need the bar function anymore
Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.
above is excerpted from the Spring doc website https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html.
So, it seemed to be invoked when Spring container has started, if you want to do something at that time.
It just has one method to set the context, so you will get the context and do something to sth now already in context I think.
Dynamic module import landed in Firefox 67+.
(async () => {
await import('./synth/BubbleSynth.js')
})()
With error handling:
(async () => {
await import('./synth/BubbleSynth.js').catch((error) => console.log('Loading failed' + error))
})()
It also works for any kind of non-modules libraries, on this case the lib is available on the window object, the old way, but only on demand, which is nice.
Example using suncalc.js, the server must have CORS enabled to works this way!
(async () => {
await import('https://cdnjs.cloudflare.com/ajax/libs/suncalc/1.8.0/suncalc.min.js')
.then(function(){
let times = SunCalc.getTimes(new Date(), 51.5,-0.1);
console.log("Golden Hour today in London: " + times.goldenHour.getHours() + ':' + times.goldenHour.getMinutes() + ". Take your pics!")
})
})()
_x000D_
You could capture the (2001)
part and replace the rest with nothing.
public static string extractYearString(string input) {
return input.replaceAll(".*\(([0-9]{4})\).*", "$1");
}
var subject = "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)";
var result = extractYearString(subject);
System.out.println(result); // <-- "2001"
.*\(([0-9]{4})\).*
means
.*
match anything\(
match a (
character(
begin capture[0-9]{4}
any single digit four times)
end capture\)
match a )
character.*
anything (rest of string)Yes, there is.
Surprising, huh? You can get a specific value from a multiple return using a simple mute
function:
package main
import "fmt"
import "strings"
func µ(a ...interface{}) []interface{} {
return a
}
type A struct {
B string
C func()(string)
}
func main() {
a := A {
B:strings.TrimSpace(µ(E())[1].(string)),
C:µ(G())[0].(func()(string)),
}
fmt.Printf ("%s says %s\n", a.B, a.C())
}
func E() (bool, string) {
return false, "F"
}
func G() (func()(string), bool) {
return func() string { return "Hello" }, true
}
https://play.golang.org/p/IwqmoKwVm-
Notice how you select the value number just like you would from a slice/array and then the type to get the actual value.
You can read more about the science behind that from this article. Credits to the author.
Probably you are looking for JavaScript™ for Acrobat® API Reference.
This reference should be the most complete. But, as @Orbling said, not all PDF viewers might support all of the API.
EDIT:
It turns out there are newer versions of the reference in Acrobat SDK (thanks to @jss).
Acrobat Developer Center contains links to different versions of documentation. Current version of JavaScript reference from Acrobat DC SDK is available there too.
Using the date helper worked for me
$this->load->helper('date');
You can find documentation for date_helper
here.
$data = array(
'created' => now(),
'modified' => now()
);
$this->db->insert('TABLENAME', $data);
Yes, you can monitor the localhost traffic using the Npcap Loopback Adapter
I got this error too when I had my server as an exception for the proxy in the SVN config file like this: http-proxy-exceptions = *.repo.domain.com
The solution for me was to use the svn server IP instead of the name. For some reason the name was not getting properly resolved from Eclipse Juno - Subclipse and from TortoiseSVN.
So, what worked for me: http-proxy-exceptions = XXX.XX.X.X
(the server IP)
MySqlBDConfig.java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "mysqlEmFactory" ,transactionManagerRef = "mysqlTransactionManager")
public class MySqlBDConfig{
@Autowired
private Environment env;
@Bean(name="mysqlProperities")
@ConfigurationProperties(prefix="spring.mysql")
public DataSourceProperties mysqlProperities(){
return new DataSourceProperties();
}
@Bean(name="mysqlDataSource")
public DataSource interfaceDS(@Qualifier("mysqlProperities")DataSourceProperties dataSourceProperties){
return dataSourceProperties.initializeDataSourceBuilder().build();
}
@Primary
@Bean(name="mysqlEmFactory")
public LocalContainerEntityManagerFactoryBean mysqlEmFactory(@Qualifier("mysqlDataSource")DataSource mysqlDataSource,EntityManagerFactoryBuilder builder){
return builder.dataSource(mysqlDataSource).packages("PACKAGE OF YOUR MODELS").build();
}
@Bean(name="mysqlTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(@Qualifier("mysqlEmFactory")EntityManagerFactory factory){
return new JpaTransactionManager(factory);
}
}
H2DBConfig.java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "dsEmFactory" ,transactionManagerRef = "dsTransactionManager")
public class H2DBConfig{
@Autowired
private Environment env;
@Bean(name="dsProperities")
@ConfigurationProperties(prefix="spring.h2")
public DataSourceProperties dsProperities(){
return new DataSourceProperties();
}
@Bean(name="dsDataSource")
public DataSource dsDataSource(@Qualifier("dsProperities")DataSourceProperties dataSourceProperties){
return dataSourceProperties.initializeDataSourceBuilder().build();
}
@Bean(name="dsEmFactory")
public LocalContainerEntityManagerFactoryBean dsEmFactory(@Qualifier("dsDataSource")DataSource dsDataSource,EntityManagerFactoryBuilder builder){
LocalContainerEntityManagerFactoryBean em = builder.dataSource(dsDataSource).packages("PACKAGE OF YOUR MODELS").build();
HibernateJpaVendorAdapter ven = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(ven);
HashMap<String, Object> prop = new HashMap<>();
prop.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));
prop.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));
em.setJpaPropertyMap(prop);
em.afterPropertiesSet();
return em;
}
@Bean(name="dsTransactionManager")
public PlatformTransactionManager dsTransactionManager(@Qualifier("dsEmFactory")EntityManagerFactory factory){
return new JpaTransactionManager(factory);
}
}
application.properties
#---mysql DATASOURCE---
spring.mysql.driverClassName = com.mysql.jdbc.Driver
spring.mysql.url = jdbc:mysql://127.0.0.1:3306/test
spring.mysql.username = root
spring.mysql.password = root
#----------------------
#---H2 DATASOURCE----
spring.h2.driverClassName = org.h2.Driver
spring.h2.url = jdbc:h2:file:~/test
spring.h2.username = root
spring.h2.password = root
#---------------------------
#------JPA-----
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext ac=SpringApplication.run(KeopsSageInvoiceApplication.class, args);
UserMysqlDao userRepository = ac.getBean(UserMysqlDao.class)
//for exemple save a new user using your repository
userRepository.save(new UserMysql());
}
}
From the manual:
Possible values for the parameter timeout: … x set timeout to x seconds
and
readlines(sizehint=None, eol='\n') Read a list of lines, until timeout. sizehint is ignored and only present for API compatibility with built-in File objects.
Note that this function only returns on a timeout.
So your readlines
will return at most every 2 seconds. Use read()
as Tim suggested.
moment(d).isAfter(ahead30now); // true
http://momentjs.com/docs/#/query/is-after/
if (moment(d).isAfter(ahead30now)) {
// allow input time
console.log('UTC TIME DB', d.format());
} else {
}
If you are using numpy, you can use dtype 'float128' and get a max float of 10e+4931
>>> np.finfo(np.float128)
finfo(resolution=1e-18, min=-1.18973149536e+4932, max=1.18973149536e+4932, dtype=float128)
multi\hskip0pt-\hskip0pt disciplinary
You can e.g. define like
\def\:{\hskip0pt}
and then write
multi\:-\:disciplinary
Note that the babel Russian language package has its own set of dashes that do not prohibit hyphenation, "~
(double quotation+tilde) for example.
simply add box-sizing: border-box;
I doubt for Keys.TAB
in sendKeys
method... if you want to use TAB you need to do something like below:
Actions builder = new Actions(driver);
builder.keyDown(Keys.TAB).perform()
adb shell
su
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
This assumes your /system is yaffs2 and that it's at /dev/block/mtdblock3 the easier/better way to do this on most Android phones is:
adb shell
su
mount -o remount,rw /system
Done. This just says remount /system read-write, you don't have to specify filesystem or mount location.
I always use object, it is more easily extendable, JSON array is not. For example you originally had some data as a json array, then you needed to add a status header on it you'd be a bit stuck, unless you'd nested the data in an object. The only disadvantage is a slight increase in complexity of creation / parsing.
So instead of
[datum0, datum1, datumN]
You'd have
{data: [datum0, datum1, datumN]}
then later you can add more...
{status: "foo", data: [datum0, datum1, datumN]}
Nice explanation from http://www.journaldev.com/753/how-to-copy-arrays-in-java
Java Array Copy Methods
Object.clone(): Object class provides clone() method and since array in java is also an Object, you can use this method to achieve full array copy. This method will not suit you if you want partial copy of the array.
System.arraycopy(): System class arraycopy() is the best way to do partial copy of an array. It provides you an easy way to specify the total number of elements to copy and the source and destination array index positions. For example System.arraycopy(source, 3, destination, 2, 5) will copy 5 elements from source to destination, beginning from 3rd index of source to 2nd index of destination.
Arrays.copyOf(): If you want to copy first few elements of an array or full copy of array, you can use this method. Obviously it’s not versatile like System.arraycopy() but it’s also not confusing and easy to use.
Arrays.copyOfRange(): If you want few elements of an array to be copied, where starting index is not 0, you can use this method to copy partial array.
The best way in my opinion is Reflection as others have recommended. Here's a sample that evaluates each local field for null. If it finds one that is not null, method will return false.
public class User {
String id = null;
String name = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isNull() {
Field fields[] = this.getClass().getDeclaredFields();
for (Field f : fields) {
try {
Object value = f.get(this);
if (value != null) {
return false;
}
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
public static void main(String args[]) {
System.out.println(new User().isNull());
}
}
According to the official docu it's recommended to downgrade the whole Python environment:
conda install python=3.5
Using this Log-Entry
framework:
Script:
Function Main {
Log -File "D:\Apps\Logs\$Env:computername.log"
$tcp = (get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductVersionRaw
$dfs = (get-childitem C:\Windows\Microsoft.NET\Framework\v2.0.50727\dfsvc.exe).Versioninfo.ProductVersionRaw
Log "TCPIP.sys Version on $computer is:" $tcp
Log "DFSVC.exe Version on $computer is:" $dfs
If (get-wmiobject win32_share | where-object {$_.Name -eq "REMINST"}) {Log "The REMINST share exists on $computer"}
Else {Log "The REMINST share DOES NOT exist on $computer - Please create as per standards"}
"KB2450944", "KB3150513", "KB3176935" | ForEach {
$hotfix = Get-HotFix -Id $_ -ErrorAction SilentlyContinue
If ($hotfix) {Log -Color Green Hotfix $_ is installed}
Else {Log -Color Red Hotfix $_ " is NOT installed - Please ensure you install this hotfix"}
}
}
Log File (at D:\Apps\Logs\<computername>.log
):
2017-05-31 Write-Log (version: 01.00.02, PowerShell version: 5.1.14393.1198)
19:19:29.00 C:\Users\User\PowerShell\Write-Log\Check.ps1
19:19:29.47 TCPIP.sys Version on is: {Major: 10, Minor: 0, Build: 14393, Revision: 1066, MajorRevision: 0, MinorRevision: 1066}
19:19:29.50 DFSVC.exe Version on is: {Major: 2, Minor: 0, Build: 50727, Revision: 8745, MajorRevision: 0, MinorRevision: 8745}
19:19:29.60 The REMINST share DOES NOT exist on - Please create as per standards
Error at 25,13: Cannot find the requested hotfix on the 'localhost' computer. Verify the input and run the command again.
19:19:33.41 Hotfix KB2450944 is NOT installed - Please ensure you install this hotfix
19:19:37.03 Hotfix KB3150513 is installed
19:19:40.77 Hotfix KB3176935 is installed
19:19:40.77 End
You also have the Trim, TrimEnd and TrimStart methods of the System.String class. The trim method will strip whitespace (with a couple of Unicode quirks) from the leading and trailing portion of the string while allowing you to optionally specify the characters to remove.
#Note there are spaces at the beginning and end
Write-Host " ! This is a test string !%^ "
! This is a test string !%^
#Strips standard whitespace
Write-Host " ! This is a test string !%^ ".Trim()
! This is a test string !%^
#Strips the characters I specified
Write-Host " ! This is a test string !%^ ".Trim('!',' ')
This is a test string !%^
#Now removing ^ as well
Write-Host " ! This is a test string !%^ ".Trim('!',' ','^')
This is a test string !%
Write-Host " ! This is a test string !%^ ".Trim('!',' ','^','%')
This is a test string
#Powershell even casts strings to character arrays for you
Write-Host " ! This is a test string !%^ ".Trim('! ^%')
This is a test string
TrimStart and TrimEnd work the same way just only trimming the start or end of the string.
A slight generalization to Peter's answer -- you can specify a range over the original array's shape if you want to go beyond three dimensional arrays.
e.g. to flatten all but the last two dimensions:
arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)
EDIT: A slight generalization to my earlier answer -- you can, of course, also specify a range at the beginning of the of the reshape too:
arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)
One thing a lot of the answers miss is that (at least in Windows) the ping
command returns 0 (indicating success) if it receives the reply "Destination host unreachable."
Here is my code that checks if b'TTL='
is in the response, since that is only present when the ping reached the host. Note: Most of this code is based on the other answers here.
import platform
import subprocess
def ping(ipAddr, timeout=100):
'''
Send a ping packet to the specified host, using the system ping command.
Accepts ipAddr as string for the ping destination.
Accepts timeout in ms for the ping timeout.
Returns True if ping succeeds otherwise Returns False.
Ping succeeds if it returns 0 and the output includes b'TTL='
'''
if platform.system().lower() == 'windows':
numFlag = '-n'
else:
numFlag = '-c'
completedPing = subprocess.run(['ping', numFlag, '1', '-w', str(timeout), ipAddr],
stdout=subprocess.PIPE, # Capture standard out
stderr=subprocess.STDOUT) # Capture standard error
# print(completedPing.stdout)
return (completedPing.returncode == 0) and (b'TTL=' in completedPing.stdout)
print(ping('google.com'))
Note: This captures the output instead of printing it, so if you want to see the output of ping
, you'll need to print completedPing.stdout
before returning.
'\r'
means 'carriage return' and it is similar to '\n'
which means 'line break' or more commonly 'new line'
in the old days of typewriters, you would have to move the carriage that writes back to the start of the line, and move the line down in order to write onto the next line.
in the modern computer era we still have this functionality for multiple reasons. but mostly we use only '\n'
and automatically assume that we want to start writing from the start of the line, since it would not make much sense otherwise.
however, there are some times when we want to use JUST the '\r'
and that would be if i want to write something to an output, and the instead of going down to a new line and writing something else, i want to write something over what i already wrote, this is how many programs in linux or in windows command line are able to have 'progress' information that changes on the same line.
nowadays most systems use only the '\n'
to denote a newline. but some systems use both together.
you can see examples of this given in some of the other answers, but the most common are:
'\r\n'
'\r'
'\n'
and some other programs also have specific uses for them.
for more information about the history of these characters
Now with laravel 4.2 it is easy to get user's id:
$userId = Auth::id();
that is all.
But to retrieve user's data other than id, you use:
$email = Auth::user()->email;
For more details, check security part of the documentation
Number.prototype.truncate = function(places) {
var shift = Math.pow(10, places);
return Math.trunc(this * shift) / shift;
};
No simple way AFAIK. If the target is to keep statement cache ratio high (i.e to not create a statement per every parameter count), you may do the following:
create a statement with a few (e.g. 10) parameters:
... WHERE A IN (?,?,?,?,?,?,?,?,?,?) ...
Bind all actuall parameters
setString(1,"foo"); setString(2,"bar");
Bind the rest as NULL
setNull(3,Types.VARCHAR) ... setNull(10,Types.VARCHAR)
NULL never matches anything, so it gets optimized out by the SQL plan builder.
The logic is easy to automate when you pass a List into a DAO function:
while( i < param.size() ) {
ps.setString(i+1,param.get(i));
i++;
}
while( i < MAX_PARAMS ) {
ps.setNull(i+1,Types.VARCHAR);
i++;
}
Necroing this question but there's an explanation that no-one seems to have considered.
STATISTICS - Statistics are not available or misleading
If all of the following are true:
Then sql server may be incorrectly assuming that the columns are uncorrelated, leading to lower than expected cardinality estimates for applying both restrictions and a poor execution plan being selected. The fix in this case would be to create a statistics object linking the two columns, which is not an expensive operation.