This is probably the closest translation from your C code to Python code.
A = 1
B = "hello"
buf = "A = %d\n , B= %s\n" % (A, B)
c = 2
buf += "C=%d\n" % c
f = open('output.txt', 'w')
print >> f, c
f.close()
The %
operator in Python does almost exactly the same thing as C's sprintf
. You can also print the string to a file directly. If there are lots of these string formatted stringlets involved, it might be wise to use a StringIO
object to speed up processing time.
So instead of doing +=
, do this:
import cStringIO
buf = cStringIO.StringIO()
...
print >> buf, "A = %d\n , B= %s\n" % (A, B)
...
print >> buf, "C=%d\n" % c
...
print >> f, buf.getvalue()
Do this:
First, yy to copy the current line, and then p to paste.
I know that you're currently using jQuery, but what if you defined the onclick handler inline. Then you could do:
<a href='/link/for/non-js-users.htm' onclick='loadContent(5);return false;'>
Article 5</a>
var q = from b in listOfBoxes
group b by b.Owner into g
select new
{
Owner = g.Key,
Boxes = g.Count(),
TotalWeight = g.Sum(item => item.Weight),
TotalVolume = g.Sum(item => item.Volume)
};
Suppose you want to get the number of missing values(NaN) in a column(series) known as price in a dataframe called reviews
#import the dataframe
import pandas as pd
reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv", index_col=0)
To get the missing values, with n_missing_prices as the variable, simple do
n_missing_prices = sum(reviews.price.isnull())
print(n_missing_prices)
sum is the key method here, was trying to use count before i realized sum is the right method to use in this context
I hade this error when transfering a csv to mssql I converted the columns to DT_NTEXT and some columns on mssql where set to nvarchar(255).
setting them to nvarchar(max) resolved it.
There are two ways to do this. First is like this:
while True: # Loop continuously
inp = raw_input() # Get the input
if inp == "": # If it is a blank line...
break # ...break the loop
The second is like this:
inp = raw_input() # Get the input
while inp != "": # Loop until it is a blank line
inp = raw_input() # Get the input again
Note that if you are on Python 3.x, you will need to replace raw_input
with input
.
Postgres hasn't implemented an equivalent to INSERT OR REPLACE
. From the ON CONFLICT
docs (emphasis mine):
It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.
Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE
applies more generally, since it lets you set new values based on preexisting data. For example:
INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;
cgi.escape
is fine. It escapes:
<
to <
>
to >
&
to &
That is enough for all HTML.
EDIT: If you have non-ascii chars you also want to escape, for inclusion in another encoded document that uses a different encoding, like Craig says, just use:
data.encode('ascii', 'xmlcharrefreplace')
Don't forget to decode data
to unicode
first, using whatever encoding it was encoded.
However in my experience that kind of encoding is useless if you just work with unicode
all the time from start. Just encode at the end to the encoding specified in the document header (utf-8
for maximum compatibility).
Example:
>>> cgi.escape(u'<a>bá</a>').encode('ascii', 'xmlcharrefreplace')
'<a>bá</a>
Also worth of note (thanks Greg) is the extra quote
parameter cgi.escape
takes. With it set to True
, cgi.escape
also escapes double quote chars ("
) so you can use the resulting value in a XML/HTML attribute.
EDIT: Note that cgi.escape has been deprecated in Python 3.2 in favor of html.escape
, which does the same except that quote
defaults to True.
-z string
True if the string is null (an empty string)
You technically have two options when speaking of ISO dates.
In general, if you're filtering specifically on Date values alone OR looking to persist date in a neutral fashion. Microsoft recommends using the language neutral format of ymd
or y-m-d
. Which are both valid ISO formats.
Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.
Because of this, your safest bet is to persist/filter based on the always netural ymd
format.
The code:
select convert(char(10), getdate(), 126) -- ISO YYYY-MM-DD
select convert(char(8), getdate(), 112) -- ISO YYYYMMDD (safest)
Use Do...Loop with Until keyword
num=0
Do Until //certain_condition_to_break_loop
num=num+1
Loop
This loop will continue to execute, Until the condition becomes true
While...Wend is the old syntax and does not provide feature to break loop! Prefer do while loops
Yes, its definitely possible to avoid the intermediate conversion to JSON. Using a deep-copy tool like Dozer you can convert the map directly to a POJO. Here is a simplistic example:
Example POJO:
public class MyPojo implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private Integer age;
private Double savings;
public MyPojo() {
super();
}
// Getters/setters
@Override
public String toString() {
return String.format(
"MyPojo[id = %s, name = %s, age = %s, savings = %s]", getId(),
getName(), getAge(), getSavings());
}
}
Sample conversion code:
public class CopyTest {
@Test
public void testCopyMapToPOJO() throws Exception {
final Map<String, String> map = new HashMap<String, String>(4);
map.put("id", "5");
map.put("name", "Bob");
map.put("age", "23");
map.put("savings", "2500.39");
map.put("extra", "foo");
final DozerBeanMapper mapper = new DozerBeanMapper();
final MyPojo pojo = mapper.map(map, MyPojo.class);
System.out.println(pojo);
}
}
Output:
MyPojo[id = 5, name = Bob, age = 23, savings = 2500.39]
Note: If you change your source map to a Map<String, Object>
then you can copy over arbitrarily deep nested properties (with Map<String, String>
you only get one level).
create trigger doct_trigger
after delete on doctor
for each row
delete from patient where patient.PrimaryDoctor_SSN=doctor.SSN ;
From your question, it is unclear as-to which columns you want to use to determine duplicates. The general idea behind the solution is to create a key based on the values of the columns that identify duplicates. Then, you can use the reduceByKey or reduce operations to eliminate duplicates.
Here is some code to get you started:
def get_key(x):
return "{0}{1}{2}".format(x[0],x[2],x[3])
m = data.map(lambda x: (get_key(x),x))
Now, you have a key-value RDD
that is keyed by columns 1,3 and 4.
The next step would be either a reduceByKey
or groupByKey
and filter
.
This would eliminate duplicates.
r = m.reduceByKey(lambda x,y: (x))
You can get a pretty coarse idea of the OS you're using by checking sys.platform
.
Once you have that information you can use it to determine if calling something like os.uname()
is appropriate to gather more specific information. You could also use something like Python System Information on unix-like OSes, or pywin32 for Windows.
There's also psutil if you want to do more in-depth inspection without wanting to care about the OS.
It is very simple. Define the trailimage
variable outside the function and set its value in the makeObj function. Now you can access its value from anywhere.
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
...
}
You can use \centering
with your parbox to do this.
(Sorry for the Google cached link; the original one I had doesn't work anymore.)
The accepted practice if to use the IllegalArgumentException( String message ) to declare a parameter to be invalid and give as much detail as possible... So to say that a parameters was found to be null while exception non-null, you would do something like this:
if( variable == null )
throw new IllegalArgumentException("The object 'variable' cannot be null");
You have virtually no reason to implicitly use the "NullPointerException". The NullPointerException is an exception thrown by the Java Virtual Machine when you try to execute code on null reference (Like toString()).
You can use the following rule to redirect from https to http :
RewriteEngine On
RewriteCond %{HTTPS} ^on$
RewriteRule ^(.*)$ http://example.com/$1 [NC,L,R]
Explanation :
RewriteCond %{HTTPS} ^on$
Checks if the HTTPS is on (Request is made using https)
Then
RewriteRule ^(.*)$ http://example.com/$1 [NC,L,R]
Redirect any request (https://example.com/foo) to http://example.com/foo .
$1 is part of the regex in RewriteRule pattern, it contains whatever value was captured in (.+) , in this case ,it captures the full request_uri everything after the domain name.
[NC,L,R] are the flags, NC makes the uri case senstive, you can use both uppercase or lowercase letters in the request.
L flag tells the server to stop proccessing other rules if the currunt rule has matched, it is important to use the L flag to avoid rule confliction when you have more then on rules in a block.
R flag is used to make an external redirection.
Best Utility in terms of speed is Nmap.
write @ cmd prompt:
Nmap -sn -oG ip.txt 192.168.1.1-255
this will just ping all the ip addresses in the range given and store it in simple text file
It takes just 2 secs to scan 255 hosts using Nmap.
You are checking whether the string contains all illegal characters. Change the ||
s to &&
s.
In many cases an element must be positioned for z-index
to work.
Indeed, applying position: relative
to the elements in the question would likely solve the problem (but there's not enough code provided to know for sure).
Actually, position: fixed
, position: absolute
and position: sticky
will also enable z-index
, but those values also change the layout. With position: relative
the layout isn't disturbed.
Essentially, as long as the element isn't position: static
(the default setting) it is considered positioned and z-index
will work.
Many answers to "Why isn't z-index working?" questions assert that z-index
only works on positioned elements. As of CSS3, this is no longer true.
Elements that are flex items or grid items can use z-index
even when position
is static
.
From the specs:
Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.5.4. Z-axis Ordering: the
z-index
propertyThe painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.
Here's a demonstration of z-index
working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/
Use String#slice
, also aliased as []
.
a = "hello there"
a[1] #=> "e"
a[1,3] #=> "ell"
a[1..3] #=> "ell"
a[6..-1] #=> "there"
a[6..] #=> "there" (requires Ruby 2.6+)
a[-3,2] #=> "er"
a[-4..-2] #=> "her"
a[12..-1] #=> nil
a[-2..-4] #=> ""
a[/[aeiou](.)\1/] #=> "ell"
a[/[aeiou](.)\1/, 0] #=> "ell"
a[/[aeiou](.)\1/, 1] #=> "l"
a[/[aeiou](.)\1/, 2] #=> nil
a["lo"] #=> "lo"
a["bye"] #=> nil
Seems like last_accessed_on, is a date time, and you are converting '23-07-2014 09:37:00' to a varchar. This would not work, and give you conversion errors. Try
last_accessed_on= convert(datetime,'23-07-2014 09:37:00', 103)
I think you can avoid the cast though, and update with '23-07-2014 09:37:00'. It should work given that the format is correct.
Your query is not going to work because in last_accessed_on (which is DateTime2 type), you are trying to pass a Varchar value.
You query would be
UPDATE student_queues SET Deleted=0 , last_accessed_by='raja', last_accessed_on=convert(datetime,'23-07-2014 09:37:00', 103)
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'
Easy peasy:
var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings
string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
You could do this:
String strz[] = strs.toArray(String[strs.size()]);
String theFirstOne = strz[0];
The javadoc for Collection gives the following caveat wrt ordering of the elements of the array:
If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
The definition of an inline
function doesn't have to be in a header file but, because of the one definition rule (ODR) for inline functions, an identical definition for the function must exist in every translation unit that uses it.
The easiest way to achieve this is by putting the definition in a header file.
If you want to put the definition of a function in a single source file then you shouldn't declare it inline
. A function not declared inline
does not mean that the compiler cannot inline the function.
Whether you should declare a function inline
or not is usually a choice that you should make based on which version of the one definition rules it makes most sense for you to follow; adding inline
and then being restricted by the subsequent constraints makes little sense.
It looks to me as though the basic problem is that you have one wait()
call rather than a loop that waits until there are no more children. You also only wait if the last fork()
is successful rather than if at least one fork()
is successful.
You should only use _exit()
if you don't want normal cleanup operations - such as flushing open file streams including stdout
. There are occasions to use _exit()
; this is not one of them. (In this example, you could also, of course, simply have the children return instead of calling exit()
directly because returning from main()
is equivalent to exiting with the returned status. However, most often you would be doing the forking and so on in a function other than main()
, and then exit()
is often appropriate.)
Hacked, simplified version of your code that gives the diagnostics I'd want. Note that your for
loop skipped the first element of the array (mine doesn't).
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(void)
{
pid_t child_pid, wpid;
int status = 0;
int i;
int a[3] = {1, 2, 1};
printf("parent_pid = %d\n", getpid());
for (i = 0; i < 3; i++)
{
printf("i = %d\n", i);
if ((child_pid = fork()) == 0)
{
printf("In child process (pid = %d)\n", getpid());
if (a[i] < 2)
{
printf("Should be accept\n");
exit(1);
}
else
{
printf("Should be reject\n");
exit(0);
}
/*NOTREACHED*/
}
}
while ((wpid = wait(&status)) > 0)
{
printf("Exit status of %d was %d (%s)\n", (int)wpid, status,
(status > 0) ? "accept" : "reject");
}
return 0;
}
Example output (MacOS X 10.6.3):
parent_pid = 15820
i = 0
i = 1
In child process (pid = 15821)
Should be accept
i = 2
In child process (pid = 15822)
Should be reject
In child process (pid = 15823)
Should be accept
Exit status of 15823 was 256 (accept)
Exit status of 15822 was 0 (reject)
Exit status of 15821 was 256 (accept)
Add #include "afxwin.h"
in your source file. It will solve your issue.
I just use the "New Class" dialog in Eclipse and set the base class as Activity. I'm not aware of any other way to do this. What other method would you expect to be available?
To actually explain what happens:
The ADB executable has two components
When you start ADB for the first time you may notice a message like "starting ADB server". If you updated ADB after that, the newer executable needs to kill the obsolete server and start a new one with matching version.
This can also happen when you have multiple versions of ADB present on your development machine (Genymotion, Android SDK, phone OEM companion apps, various standalone scripts).
This does not concern the ADB installed on your phone/emulator.
The obvious (not necessarily easy) solution is to make sure you use the same version of ADB everywhere.
For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan
Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.
const appRoot = require('app-root-path');
const winston = require('winston');
// define the custom settings for each transport (file, console)
const options = {
file: {
level: 'info',
filename: `${appRoot}/logs/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
console: {
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
},
};
// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
],
exitOnError: false, // do not exit on handled exceptions
});
} else {
logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console),
],
exitOnError: false, // do not exit on handled exceptions
});
}
// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
write(message) {
logger.info(message);
},
};
module.exports = logger;
After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log
,
" to the respective app.log created by you.
After this go to your index.js and include the following code in it.
const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));
winston.info('You have successfully started working with winston and morgan');
this works for me in Angular 7
// in component.ts
checked: boolean = true;
changeValue(value) {
this.checked = !value;
}
// in component.html
<mat-checkbox value="checked" (click)="changeValue(checked)" color="primary">
some Label
</mat-checkbox>
I hope help someone ... greetings. let me know if someone have some easiest
had a space in the current working directory and usign $(pwd)
to map volumes. Doesn't like spaces in directory names.
declare @string varchar(20)= 'TEST STRING'
Select left(@string, len(@string)-1) as Tada
output:
Tada
--------------------
TEST STRIN
prop.table is a nice friendly way of obtaining proportions of tables.
m <- matrix(1:4,2)
m
[,1] [,2]
[1,] 1 3
[2,] 2 4
Leaving margin blank gives you proportions of the whole table
prop.table(m, margin=NULL)
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
Giving it 1 gives you row proportions
prop.table(m, 1)
[,1] [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667
And 2 is column proportions
prop.table(m, 2)
[,1] [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286
DATEDIFF but note it returns an integer so if you need fractions of hours use something like this:-
CAST(DATEDIFF(ss, startDate, endDate) AS decimal(precision, scale)) / 3600
R.color.black
or some color are obviously integers. It needs a RGB value. You can give your own like #FF123454
which represents various primary colors
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
I just borrow some other guys' idea and write some code below that may be helpful.
import android.content.Context;
import android.graphics.Canvas;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
public class AutoResizeTextView extends TextView {
private static final int MAX_SIZE = 1000;
private static final int MIN_SIZE = 5;
private TextPaint mTextPaint;
private float mSpacingMult = 1.0f;
private float mSpacingAdd = 0.0f;
private boolean needAdapt = false;
private boolean adapting = false;
public AutoResizeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public AutoResizeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public AutoResizeTextView(Context context) {
super(context);
init();
}
private void init() {
mTextPaint = new TextPaint();
}
@Override
protected void onDraw(Canvas canvas) {
if (adapting) {
return;
}
if (needAdapt) {
adaptTextSize();
} else {
super.onDraw(canvas);
}
}
private void adaptTextSize() {
CharSequence text = getText();
int viewWidth = getMeasuredWidth();
int viewHeight = getMeasuredHeight();
if (viewWidth==0 || viewHeight==0
|| TextUtils.isEmpty(text)) {
return;
}
adapting = true;
/* binary search */
int bottom=MIN_SIZE, top=MAX_SIZE, mid = 0;
while (bottom <= top) {
mid = (bottom + top)/2;
mTextPaint.setTextSize(mid);
int textWidth = (int) mTextPaint.measureText(text, 0, text.length());
int textHeight = getTextHeight(text, viewWidth);
if (textWidth<viewWidth && textHeight<viewHeight) {
bottom = mid+1;
} else {
top = mid-1;
}
}
int newSize = mid-1;
setTextSize(TypedValue.COMPLEX_UNIT_PX, newSize);
adapting=false;
needAdapt = false;
invalidate();
}
private int getTextHeight(CharSequence text, int targetWidth) {
StaticLayout layout = new StaticLayout(text, mTextPaint, targetWidth,
Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
return layout.getHeight();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
needAdapt = true;
}
@Override
protected void onTextChanged(CharSequence text, int start,
int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
needAdapt = true;
}
@Override
public void setLineSpacing(float add, float mult) {
super.setLineSpacing(add, mult);
mSpacingMult = mult;
mSpacingAdd = add;
}
}
HTML
<span id="radiobutt">
<input type="radio" name="rad1" value="1" />
<input type="radio" name="rad1" value="2" />
<input type="radio" name="rad1" value="3" />
</span>
<div>
<input type="text" id="textbox1" />
<input type="checkbox" id="checkbox1" />
</div>
Javascript
$("#radiobutt input[type=radio]").each(function(i){
$(this).click(function () {
if(i==2) { //3rd radiobutton
$("#textbox1").attr("disabled", "disabled");
$("#checkbox1").attr("disabled", "disabled");
}
else {
$("#textbox1").removeAttr("disabled");
$("#checkbox1").removeAttr("disabled");
}
});
});
Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.
<?php
function getSSLPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>
When you set the SSL Version with curl to v3 then it works.
Edit:
Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.
http://curl.haxx.se/docs/caextract.html
here you can download the root certificates.
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
Then you can use the CURLOPT_SSL_VERIFYPEER
option with true
otherwise you get an error.
Very simple solution. Just rename your database and configure your new database name in your project.
The problem is the when you import your database, you got any errors and then the database will be corrupted. The log files will have the corrupted database name. You can rename your database easily using phpmyadmin for mysql.
phpmyadmin -> operations -> Rename database to
Use Firebug to inspect the table in question, and see where does it inherit the border from. (check the right column). Try setting on-the-fly inline style border:none; to see if you get rid of it. Could also be the browsers default stylesheets. In this case, use a CSS reset. http://developer.yahoo.com/yui/reset/
So, I hear this works:
Data$X1<-as.character(Data$X1)
Data$GEOID<-as.character(Data$BLKIDFP00)
Data<-within(Data,X1<-ifelse(is.na(Data$X1),GEOID,Data$X2))
But I admit I have only intermittent luck with it.
When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "LoginActivity".
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
The answer you get to this question from the Android platform is: "Don't make an exit button. Finish activities the user no longer wants, and the Activity manager will clean them up as it sees fit."
Assuming you have referenced and correctly integrated your font to your site (presumably using an @font-face kit) it should be alright to just reference yours the way you do. Presumably it is like this so they have fall backs incase some browsers do not render the fonts correctly
I hit this page trying to pad hexadecimal values when I realized that DEC2HEX()
provides that very feature for free.
You just need to add a second parameter. For example, tying to turn 12
into 0C
DEC2HEX(12,2)
=> 0C
DEC2HEX(12,4)
=> 000C
... and so on
This is working code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.DataTextField = "user_name";
DropDownList1.DataValueField = "user_id";
DropDownList1.DataSource = getData();// get the data into the list you can set it
DropDownList1.DataBind();
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("your default selected text"));
}
}
As others have said, you can/should prepend the string with @
(though you could also just escape the backslashes), but what they glossed over (that is, didn't bring it up despite making a change related to it) was the fact that, as I recently discovered, using \
at the beginning of a pathname, without .
to represent the current directory, refers to the root of the current directory tree.
C:\foo\bar>cd \
C:\>
versus
C:\foo\bar>cd .\
C:\foo\bar>
(Using .
by itself has the same effect as using .\
by itself, from my experience. I don't know if there are any specific cases where they somehow would not mean the same thing.)
You could also just leave off the leading .\
, if you want.
C:\foo>cd bar
C:\foo\bar>
In fact, if you really wanted to, you don't even need to use backslashes. Forwardslashes work perfectly well! (Though a single /
doesn't alias to the current drive root as \
does.)
C:\>cd foo/bar
C:\foo\bar>
You could even alternate them.
C:\>cd foo/bar\baz
C:\foo\bar\baz>
...I've really gone off-topic here, though, so feel free to ignore all this if you aren't interested.
key, value = max(stats.iteritems(), key=lambda x:x[1])
If you don't care about value (I'd be surprised, but) you can do:
key, _ = max(stats.iteritems(), key=lambda x:x[1])
I like the tuple unpacking better than a [0] subscript at the end of the expression. I never like the readability of lambda expressions very much, but find this one better than the operator.itemgetter(1) IMHO.
This question helped me.
So, try this:
Controller code:
[HttpGet]
public HttpResponseMessage Test()
{
var path = System.Web.HttpContext.Current.Server.MapPath("~/Content/test.docx");;
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(path);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = stream.Length;
return result;
}
View Html markup (with click event and simple url):
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
// httproute = "" - using this to construct proper web api links.
window.location.href = "@Url.Action("GetFile", "Data", new { httproute = "" })";
});
});
</script>
<button id="btn">
Button text
</button>
<a href=" @Url.Action("GetFile", "Data", new { httproute = "" }) ">Data</a>
instead of click on Restore Database click on Restore File and Filegroups..
thats work on my sql server
Actually, you don't need to modify the object
prototype and add a function there. The following should work well for your purpose.
var __next_objid=1;
function objectId(obj) {
if (obj==null) return null;
if (obj.__obj_id==null) obj.__obj_id=__next_objid++;
return obj.__obj_id;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
prefer this links about properties in objective-c in iOS...
https://techguy1996.blogspot.com/2020/02/properties-in-objective-c-ios.html
To expand on the answer provided by @Orion Edwards, this is how you would do fully from code-behind (no styles set). Basically create a custom class that inherits from Border which has its Child set to a TextBox. The example below assumes that you only want a single line and that the border is a child of a Canvas. Also assumes you would need to adjust the MaxLength property of the TextBox based on the width of the Border. The example below also sets the cursor of the Border to mimic a Textbox by setting it to the type 'IBeam'. A margin of '3' is set so that the TextBox isn't absolutely aligned to the left of the border.
double __dX = 20;
double __dY = 180;
double __dW = 500;
double __dH = 40;
int __iMaxLen = 100;
this.m_Z3r0_TextBox_Description = new CZ3r0_TextBox(__dX, __dY, __dW, __dH, __iMaxLen, TextAlignment.Left);
this.Children.Add(this.m_Z3r0_TextBox_Description);
Class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
namespace ifn0tz3r0Exp
{
class CZ3r0_TextBox : Border
{
private TextBox m_TextBox;
private SolidColorBrush m_Brush_Green = new SolidColorBrush(Colors.MediumSpringGreen);
private SolidColorBrush m_Brush_Black = new SolidColorBrush(Colors.Black);
private SolidColorBrush m_Brush_Transparent = new SolidColorBrush(Colors.Transparent);
public CZ3r0_TextBox(double _dX, double _dY, double _dW, double _dH, int _iMaxLen, TextAlignment _Align)
{
/////////////////////////////////////////////////////////////
//TEXTBOX
this.m_TextBox = new TextBox();
this.m_TextBox.Text = "This is a vertically centered one-line textbox embedded in a border...";
Canvas.SetLeft(this, _dX);
Canvas.SetTop(this, _dY);
this.m_TextBox.FontFamily = new FontFamily("Consolas");
this.m_TextBox.FontSize = 11;
this.m_TextBox.Background = this.m_Brush_Black;
this.m_TextBox.Foreground = this.m_Brush_Green;
this.m_TextBox.BorderBrush = this.m_Brush_Transparent;
this.m_TextBox.BorderThickness = new Thickness(0.0);
this.m_TextBox.Width = _dW;
this.m_TextBox.MaxLength = _iMaxLen;
this.m_TextBox.TextAlignment = _Align;
this.m_TextBox.VerticalAlignment = System.Windows.VerticalAlignment.Center;
this.m_TextBox.FocusVisualStyle = null;
this.m_TextBox.Margin = new Thickness(3.0);
this.m_TextBox.CaretBrush = this.m_Brush_Green;
this.m_TextBox.SelectionBrush = this.m_Brush_Green;
this.m_TextBox.SelectionOpacity = 0.3;
this.m_TextBox.GotFocus += this.CZ3r0_TextBox_GotFocus;
this.m_TextBox.LostFocus += this.CZ3r0_TextBox_LostFocus;
/////////////////////////////////////////////////////////////
//BORDER
this.BorderBrush = this.m_Brush_Transparent;
this.BorderThickness = new Thickness(1.0);
this.Background = this.m_Brush_Black;
this.Height = _dH;
this.Child = this.m_TextBox;
this.FocusVisualStyle = null;
this.MouseDown += this.CZ3r0_TextBox_MouseDown;
this.Cursor = Cursors.IBeam;
/////////////////////////////////////////////////////////////
}
private void CZ3r0_TextBox_MouseDown(object _Sender, MouseEventArgs e)
{
this.m_TextBox.Focus();
}
private void CZ3r0_TextBox_GotFocus(object _Sender, RoutedEventArgs e)
{
this.BorderBrush = this.m_Brush_Green;
}
private void CZ3r0_TextBox_LostFocus(object _Sender, RoutedEventArgs e)
{
this.BorderBrush = this.m_Brush_Transparent;
}
}
}
I depends on the version and the distro.
For example the default download pre-2.2 from the MongoDB site uses: /data/db
but the Ubuntu install at one point used to use: var/lib/mongodb
.
I think these have been standardised now so that 2.2+ will only use data/db
whether it comes from direct download on the site or from the repos.
Here's a gitHub project that does just that.
It records audio from the browser in mp3 format, and it automatically saves it to the webserver. https://github.com/Audior/Recordmp3js
You can also view a detailed explanation of the implementation: http://audior.ec/blog/recording-mp3-using-only-html5-and-javascript-recordmp3-js/
The reason for this warning is that const in c doesn't mean constant. It means "read only". So the value is stored at a memory address and could potentially be changed by machine code.
vector:
list:
In general, use vector when you don't care what type of sequential container that you're using, but if you're doing many insertions or erasures to and from anywhere in the container other than the end, you're going to want to use list. Or if you need random access, then you're going to want vector, not list. Other than that, there are naturally instances where you're going to need one or the other based on your application, but in general, those are good guidelines.
Thanks for the answers above. Here's how I did it, I hope it helps those who follow. I'm looking to pass a registration number from one page to another, hence regName and regValue:
Create your first page, call it set_reg.php:
<?php
session_start();
$_SESSION['regName'] = $regValue;
?>
<form method="get" action="get_reg.php">
<input type="text" name="regName" value="">
<input type="submit">
</form>
Create your second page, call it get_reg.php:
<?php
session_start();
$regValue = $_GET['regName'];
echo "Your registration is: ".$regValue.".";
?>
<p><a href="set_reg.php">Back to set_reg.php</a>
Although not as comprehensive as the answer above, for my purposes this illustrates in simple fashion the relationship between the various elements.
Just open your sql file with a text editor and search for 'utf8mb4' and replace with utf8.I hope it would work for you
The auto-indent is based on the current syntax mode. I know that if you are editing Foo.java, then entering a {
and hitting Enter indents the following line.
As for tabs, there are two settings. Within Vim, type a colon and then "set tabstop=4" which will set the tabs to display as four spaces. Hit colon again and type "set expandtab" which will insert spaces for tabs.
You can put these settings in a .vimrc (or _vimrc on Windows) in your home directory, so you only have to type them once.
This can happen if you have a table and forget to assign UITableViewDelegate and UITableViewDataSource to the class
To display a value nicely, you can use the pprint module. The easiest way to dump all variables with it is to do
from pprint import pprint
pprint(globals())
pprint(locals())
If you are running in CGI, a useful debugging feature is the cgitb module, which displays the value of local variables as part of the traceback.
Use the namespace System.Net.Mail. Here is a link to the MSDN page
You can send emails using SmtpClient class.
I paraphrased the code sample, so checkout MSDNfor details.
MailMessage message = new MailMessage(
"[email protected]",
"[email protected]",
"Subject goes here",
"Body goes here");
SmtpClient client = new SmtpClient(server);
client.Send(message);
The best way to send many emails would be to put something like this in forloop and send away!
Simplest is use list[i:i]
a = [1,2, 3, 4]
a[2:2] = [10]
Print a to check insertion
print a
[1, 2, 10, 3, 4]
Did you verify that the control causing the post back has CausesValidation set to tru and that it does not have a validation group assigned to it?
I'm not sure what else might cause this behavior.
Basically, you should include the class' header file in the code where you want to use the class in the shared library. Then, when you link, use the '-l' flag to link your code with the shared library. Of course, this requires the .so to be where the OS can find it. See 3.5. Installing and Using a Shared Library
Using dlsym is for when you don't know at compile time which library you want to use. That doesn't sound like it's the case here. Maybe the confusion is that Windows calls the dynamically loaded libraries whether you do the linking at compile or run-time (with analogous methods)? If so, then you can think of dlsym as the equivalent of LoadLibrary.
If you really do need to dynamically load the libraries (i.e., they're plug-ins), then this FAQ should help.
"Conflicts" mean "parallel evolutions of a same content". So if it goes "all to hell" during a merge, it means you have massive evolutions on the same set of files.
The reason why a rebase is then better than a merge is that:
I confirm that the correct workflow in that case (evolutions on common set of files) is rebase first, then merge.
However, that means that, if you push your local branch (for backup reason), that branch should not be pulled (or at least used) by anyone else (since the commit history will be rewritten by the successive rebase).
On that topic (rebase then merge workflow), barraponto mentions in the comments two interesting posts, both from randyfay.com:
Using this technique, your work always goes on top of the public branch like a patch that is up-to-date with current
HEAD
.
(a similar technique exists for bazaar)
git push --force
(instead of a git pull --rebase
for instance)Since chrome has come up with the multiple profiles you will not get it directly in C:\Users\<Your_User_Name>\AppData\Local\Google\Chrome\User Data\Default\Extensions
but you have to first type chrome://version/
in a tab and then look out for Profile path inside that and after you reach to your profile path look for Extensions folder in it and then folder with the desired extension Id
You can use the limit(n)
function:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.limit(2).withColumn('age2', df.age + 2).toPandas()
Or:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.withColumn('age2', df.age + 2).limit(2).toPandas()
Here is my regex variant of a special character:
String regExp = "^[^<>{}\"/|;:.,~!?@#$%^=&*\\]\\\\()\\[¿§«»??¤°??€¥£¢¡®©0-9_+]*$";
(Java code)
Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.
First, click Slide Show > Set Up Show.
Put a checkmark to Loop continuously until 'Esc'.
Click Ok. Now, Click Slide Show > Custom Shows. Click New.
Select the slide you are looping, click Add. Click Ok and Close.
Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.
Right click on the thumbnail of the current slide, select Hide Slide.
Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"
This has worked for me.
Python Code:
for s in myStr:
print s
OR
for i in xrange(len(myStr)):
print myStr[i]
clone: copying the remote server repository to your local machine.
pull: get new changes other have added to your local machine.
This is the difference.
Clone is generally used to get remote repo copy.
Pull is used to view other team mates added code, if you are working in teams.
While the above answer works, Romain Guy (a core Android developer) shows a better method in his blog which uses less memory by using a shader not creating a copy of the bitmap. The general gist of the functionality is here:
BitmapShader shader;
shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
RectF rect = new RectF(0.0f, 0.0f, width, height);
// rect contains the bounds of the shape
// radius is the radius in pixels of the rounded corners
// paint contains the shader that will texture the shape
canvas.drawRoundRect(rect, radius, radius, paint);
The advantages of this over other methods is that it:
I've created a RoundedImageView based off this code that wraps this logic into an ImageView and adds proper ScaleType
support and an optional rounded border.
Here are some guideline steps...
Give this a go and if you get stuck then come back and ask more specific questions relating to your problems
Here is an option with only a single comparison.
// return true if in range, otherwise false
function inRange(x, min, max) {
return ((x-min)*(x-max) <= 0);
}
console.log(inRange(5, 1, 10)); // true
console.log(inRange(-5, 1, 10)); // false
console.log(inRange(20, 1, 10)); // false
If you use this syntax:
<div ng-attr-id="{{ 'object-' + myScopeObject.index }}"></div>
Angular will render something like:
<div ng-id="object-1"></div>
However this syntax:
<div id="{{ 'object-' + $index }}"></div>
will generate something like:
<div id="object-1"></div>
JSONB is a "better" version of JSON.
Let's look at an example:
SELECT '{"c":0, "a":2,"a":1}'::json, '{"c":0, "a":2,"a":1}'::jsonb;
json | jsonb
------------------------+---------------------
{"c":0, "a":2,"a":1} | {"a": 1, "c": 0}
(1 row)
In general, one should prefer JSONB , unless there are specialized needs, such as legacy assumptions about ordering of object keys.
This is what you need in 1 line of code.
Route::get('/groups/{groupId}', 'GroupsController@getShow');
Suggestion: Use CamelCase as opposed to underscores, try & follow PSR-* guidelines.
Hope it helps.
For UUID4 I make it that there are approximately as many IDs as there are grains of sand in a cube-shaped box with sides 360,000km long. That's a box with sides ~2 1/2 times longer than Jupiter's diameter.
Working so someone can tell me if I've messed up units:
The hibernate.*
properties are useless, they should be spring.jpa.*
properties. Not to mention that you are trying to override those already set by using the spring.jpa.*
properties. (For the explanation of each property I strongly suggest a read of the Spring Boot reference guide.
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql = true
# Hibernate
spring.jpa.hibernate.ddl-auto=update
Also the packages to scan are automatically detected based on the base package of your Application
class. If you want to specify something else use the @EntityScan
annotation. Also specifying the most toplevel package isn't really wise as it will scan the whole class path which will severely impact performance.
Here is another code for this:
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
public class AccelerometerListener implements SensorEventListener {
private SensorManager sensorManager;
private List<Sensor> sensors;
private Sensor sensor;
private long lastUpdate = -1;
private long currentTime = -1;
private Main parent;
private Timer timer;
private int shakes;
private static final Handler mHandler = new Handler();
private float last_x, last_y, last_z;
private float current_x, current_y, current_z, currenForce;
private static final int FORCE_THRESHOLD = 500;
private final int DATA_X = SensorManager.DATA_X;
private final int DATA_Y = SensorManager.DATA_Y;
private final int DATA_Z = SensorManager.DATA_Z;
public AccelerometerListener(Main parent) {
SensorManager sensorService = (SensorManager) parent
.getSystemService(Context.SENSOR_SERVICE);
this.sensorManager = sensorService;
if (sensorService == null)
return;
this.sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if (sensors.size() > 0) {
sensor = sensors.get(0);
}
this.parent = parent;
}
public void start() {
if (sensor == null)
return;
sensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_GAME);
}
public void stop() {
if (sensorManager == null)
return;
sensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor s, int valu) {
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
return;
currentTime = System.currentTimeMillis();
if ((currentTime - lastUpdate) > 50) {
long diffTime = (currentTime - lastUpdate);
lastUpdate = currentTime;
current_x = event.values[DATA_X];
current_y = event.values[DATA_Y];
current_z = event.values[DATA_Z];
currenForce = Math.abs(current_x + current_y + current_z - last_x
- last_y - last_z)
/ diffTime * 10000;
if (currenForce > FORCE_THRESHOLD) {
shakeDetected();
}
last_x = current_x;
last_y = current_y;
last_z = current_z;
}
}
private void shakeDetected() {
shakes++;
if (shakes == 1) {
if (timer != null) {
timer.cancel();
}
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (shakes > 3) {
mHandler.post(new Runnable() {
public void run() {
// shake
}
});
}
shakes = 0;
}
}, 500);
}
}
}
You can use following class as service class to run your application in background
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
private GPSTracker gpsTracker;
private Handler handler= new Handler();
private Timer timer = new Timer();
private Distance pastDistance = new Distance();
private Distance currentDistance = new Distance();
public static double DISTANCE;
boolean flag = true ;
private double totalDistance ;
@Override
@Deprecated
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
gpsTracker = new GPSTracker(HomeFragment.HOMECONTEXT);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
if(flag){
pastDistance.setLatitude(gpsTracker.getLocation().getLatitude());
pastDistance.setLongitude(gpsTracker.getLocation().getLongitude());
flag = false;
}else{
currentDistance.setLatitude(gpsTracker.getLocation().getLatitude());
currentDistance.setLongitude(gpsTracker.getLocation().getLongitude());
flag = comapre_LatitudeLongitude();
}
Toast.makeText(HomeFragment.HOMECONTEXT, "latitude:"+gpsTracker.getLocation().getLatitude(), 4000).show();
}
});
}
};
timer.schedule(timerTask,0, 5000);
}
private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("--------------------------------onDestroy -stop service ");
timer.cancel();
DISTANCE = totalDistance ;
}
public boolean comapre_LatitudeLongitude(){
if(pastDistance.getLatitude() == currentDistance.getLatitude() && pastDistance.getLongitude() == currentDistance.getLongitude()){
return false;
}else{
final double distance = distance(pastDistance.getLatitude(),pastDistance.getLongitude(),currentDistance.getLatitude(),currentDistance.getLongitude());
System.out.println("Distance in mile :"+distance);
handler.post(new Runnable() {
@Override
public void run() {
float kilometer=1.609344f;
totalDistance = totalDistance + distance * kilometer;
DISTANCE = totalDistance;
//Toast.makeText(HomeFragment.HOMECONTEXT, "distance in km:"+DISTANCE, 4000).show();
}
});
return true;
}
}
}
Add One another class to get location
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class GPSTracker implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location = null;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
private Location m_Location;
public GPSTracker(Context context) {
this.mContext = context;
m_Location = getLocation();
System.out.println("location Latitude:"+m_Location.getLatitude());
System.out.println("location Longitude:"+m_Location.getLongitude());
System.out.println("getLocation():"+getLocation());
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
}
else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
// --------------Distance.java
public class Distance {
private double latitude ;
private double longitude;
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}
First replicate the location and styling of the text and then use Jquery width() function. This will make the measurements accurate. For example you have css styling with a selector of:
.style-head span
{
//Some style set
}
You would need to do this with Jquery already included above this script:
var measuringSpan = document.createElement("span");
measuringSpan.innerText = 'text to measure';
measuringSpan.style.display = 'none'; /*so you don't show that you are measuring*/
$('.style-head')[0].appendChild(measuringSpan);
var theWidthYouWant = $(measuringSpan).width();
Needless to say
theWidthYouWant
will hold the pixel length. Then remove the created elements after you are done or you will get several if this is done a several times. Or add an ID to reference instead.
You're applying your class to the <a>
elements, which aren't siblings because they're each enclosed in an <li>
element. You need to move up the tree to the parent <li>
and find the ` elements in the siblings at that level.
$('#menu li a').on('click', function(){
$(this).addClass('current').parent().siblings().find('a').removeClass('current');
});
See this updated fiddle
I prefer to use border-spacing
as it allows more flexibility. For instance, you could do
table {
border-spacing: 0 2px;
}
Which would only collapse the vertical borders and leave the horizontal ones in tact, which is what it sounds like the OP was actually looking for.
Note that border-spacing: 0
is not the same as border-collapse: collapse
. You will need to use the latter if you want to add your own border to a tr
as seen here.
In your pom.xml you should add distributionManagement configuration to where to deploy.
In the following example I have used file system as the locations.
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Internal repo</name>
<url>file:///home/thara/testesb/in</url>
</repository>
</distributionManagement>
you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :
mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in
I had trouble with the most popular answer (overthinking). It put AFolder in the \Server\MyFolder\AFolder and I wanted the contents of AFolder and below in MyFolder. This didn't work.
Copy-Item -Verbose -Path C:\MyFolder\AFolder -Destination \\Server\MyFolder -recurse -Force
Plus I needed to Filter and only copy *.config files.
This didn't work, with "\*" because it did not recurse
Copy-Item -Verbose -Path C:\MyFolder\AFolder\* -Filter *.config -Destination \\Server\MyFolder -recurse -Force
I ended up lopping off the beginning of the path string, to get the childPath relative to where I was recursing from. This works for the use-case in question and went down many subdirectories, which some other solutions do not.
Get-Childitem -Path "$($sourcePath)/**/*.config" -Recurse |
ForEach-Object {
$childPath = "$_".substring($sourcePath.length+1)
$dest = "$($destPath)\$($childPath)" #this puts a \ between dest and child path
Copy-Item -Verbose -Path $_ -Destination $dest -Force
}
dplyr::as_data_frame(df, rownames = "your_row_name")
will give you even simpler result.
Better late than never. Here's a method that I devised (after reading this post) for returning a list of dates that includes: (a) day 1 of of the current month through today, PLUS (b) all dates for the past two months:
select (sysdate +1 - rownum) dt
from dual
connect by rownum <= (sysdate - add_months(sysdate - extract(day from sysdate),-2));
The "-2" is the number of prior full months of dates to include. For example, on July 10th, this SQL returns a list of all dates from May 1 through July 10 - i.e. two full prior months plus the current partial month.
mv
in unix-ish systems, move
in dos/windows.
e.g.
C:\> move c:\users\you\somefile.txt c:\temp\newlocation.txt
and
$ mv /home/you/somefile.txt /tmp/newlocation.txt
To pass get variables as well use $args
:
location / {
try_files $uri $uri/ /index.php?$args;
}
At a theoretical level, they are no different semantically. You can implement a mutex using semaphores or vice versa (see here for an example). In practice, the implementations are different and they offer slightly different services.
The practical difference (in terms of the system services surrounding them) is that the implementation of a mutex is aimed at being a more lightweight synchronisation mechanism. In oracle-speak, mutexes are known as latches and semaphores are known as waits.
At the lowest level, they use some sort of atomic test and set mechanism. This reads the current value of a memory location, computes some sort of conditional and writes out a value at that location in a single instruction that cannot be interrupted. This means that you can acquire a mutex and test to see if anyone else had it before you.
A typical mutex implementation has a process or thread executing the test-and-set instruction and evaluating whether anything else had set the mutex. A key point here is that there is no interaction with the scheduler, so we have no idea (and don't care) who has set the lock. Then we either give up our time slice and attempt it again when the task is re-scheduled or execute a spin-lock. A spin lock is an algorithm like:
Count down from 5000:
i. Execute the test-and-set instruction
ii. If the mutex is clear, we have acquired it in the previous instruction
so we can exit the loop
iii. When we get to zero, give up our time slice.
When we have finished executing our protected code (known as a critical section) we just set the mutex value to zero or whatever means 'clear.' If multiple tasks are attempting to acquire the mutex then the next task that happens to be scheduled after the mutex is released will get access to the resource. Typically you would use mutexes to control a synchronised resource where exclusive access is only needed for very short periods of time, normally to make an update to a shared data structure.
A semaphore is a synchronised data structure (typically using a mutex) that has a count and some system call wrappers that interact with the scheduler in a bit more depth than the mutex libraries would. Semaphores are incremented and decremented and used to block tasks until something else is ready. See Producer/Consumer Problem for a simple example of this. Semaphores are initialised to some value - a binary semaphore is just a special case where the semaphore is initialised to 1. Posting to a semaphore has the effect of waking up a waiting process.
A basic semaphore algorithm looks like:
(somewhere in the program startup)
Initialise the semaphore to its start-up value.
Acquiring a semaphore
i. (synchronised) Attempt to decrement the semaphore value
ii. If the value would be less than zero, put the task on the tail of the list of tasks waiting on the semaphore and give up the time slice.
Posting a semaphore
i. (synchronised) Increment the semaphore value
ii. If the value is greater or equal to the amount requested in the post at the front of the queue, take that task off the queue and make it runnable.
iii. Repeat (ii) for all tasks until the posted value is exhausted or there are no more tasks waiting.
In the case of a binary semaphore the main practical difference between the two is the nature of the system services surrounding the actual data structure.
EDIT: As evan has rightly pointed out, spinlocks will slow down a single processor machine. You would only use a spinlock on a multi-processor box because on a single processor the process holding the mutex will never reset it while another task is running. Spinlocks are only useful on multi-processor architectures.
In Swift:
override func viewDidLoad() {
super.viewDidLoad()
// We set the table view header.
let cellTableViewHeader = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewHeaderCustomCellIdentifier) as! UITableViewCell
cellTableViewHeader.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewHeaderCustomCellIdentifier]!)
self.tableView.tableHeaderView = cellTableViewHeader
// We set the table view footer, just know that it will also remove extra cells from tableview.
let cellTableViewFooter = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewFooterCustomCellIdentifier) as! UITableViewCell
cellTableViewFooter.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewFooterCustomCellIdentifier]!)
self.tableView.tableFooterView = cellTableViewFooter
}
I've always just subtracted zero.
num1-0 + num2-0;
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.
NOTE: HSSFDateUtil is deprecated
If you know which cell i.e. column position say 0 in each row is going to be a date, you can go for
row.getCell(0).getDateCellValue()
directly.
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCell.html#getDateCellValue()
UPDATE: Here is an example - you can apply this in your switch case code above. I am checking and printing the Numeric as well as Date value. In this case the first column in my sheet has dates, hence I use row.getCell(0).
You can use the if (HSSFDateUtil.isCellDateFormatted ..
code block directly in your switch case.
if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
System.out.println ("Row No.: " + row.getRowNum ()+ " " +
row.getCell(0).getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(row.getCell(0))) {
System.out.println ("Row No.: " + row.getRowNum ()+ " " +
row.getCell(0).getDateCellValue());
}
}
The output is
Row No.: 0 39281.0
Row No.: 0 Wed Jul 18 00:00:00 IST 2007
Row No.: 1 39491.0
Row No.: 1 Wed Feb 13 00:00:00 IST 2008
Row No.: 2 39311.0
Row No.: 2 Fri Aug 17 00:00:00 IST 2007
Anonymous ftp logins are usually the username 'anonymous' with the user's email address as the password. Some servers parse the password to ensure it looks like an email address.
User: anonymous
Password: [email protected]
I'm not sure what was wrong with The MYYN's answer.
if (yourString != null) {
//do fun stuff with yourString here
}
The above null check is quite alright.
If you are trying to check if a String reference is equal (ignoring case) to another string that you know is not a null reference, then do something like this:
String x = "this is not a null reference"
if (x.equalsIgnoreCase(yourStringReferenceThatMightBeNull) ) {
//do fun stuff
}
If there is any doubt as to whether or not you have null references for both Strings you are comparing, you'll need to check for a null reference on at least one of them to avoid the possibility of a NullPointerException.
Define it as
<return type> AnalyzeArray(ArrayList<Integer> list) {
Same solution, but just to remind you: You can define the shadow directly in the storyboard.
Ex:
I just click on latest swift convert button and set App target build setting-> Swift language version: swift 4.0,
Hope this will help.
You can set ini_set('display_errors',0);
in your script or define which errors you do want to display with error_reporting()
.
I would use it like this, its way shorter and it won't give any problems
dynamic result = null;
if (methodInfo != null)
{
ParameterInfo[] parameters = methodInfo.GetParameters();
object classInstance = Activator.CreateInstance(type, null);
result = methodInfo.Invoke(classInstance, parameters.Length == 0 ? null : parametersArray);
}
The best, non-VBA, way to do this is using the TEXT formula. It takes a string as an argument and converts it to a value.
For example, =TEXT ("0.4*A1",'##') will return the value of 0.4 * the value that's in cell A1 of that worksheet.
Dataframes have a sort_index
method which returns a copy by default. Pass inplace=True
to operate in place.
import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())
Gives me:
A
1 4
29 2
100 1
150 5
234 3
string connectionstring="DataSource=severname;InitialCatlog=databasename;Uid=; password=;"
SqlConnection con=new SqlConnection(connectionstring)
use Illuminate\Database\Eloquent\Builder;
$query = Customers::with('orders');
$query = $query->whereHas('orders', function (Builder $query) use ($request) {
$query = $query->where('orders.customer_id', 'NULL')
});
$query = $query->get();
Or if all borders have same style, just:
border:10px;
Try this
This is the simplest way to ask for permission in Marshmallow version.
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED&&ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
//TO do here if permission is granted by user
}
else
{
//ask for permission if user didnot given
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.CAMERA,Manifest.permission.ACCESS_FINE_LOCATION}, 0);
}
}
Note:- Don't forget to add this same permission in manifest file also
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Second Method Code for checking the permission is granted or not?
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA}, 1);
And override the method
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// grantResult[0] means it will check for the first postion permission which is READ_EXTERNAL_STORAGE
// grantResult[1] means it will check for the Second postion permission which is CAMERA
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this, "Permission not Granted", Toast.LENGTH_SHORT).show();
return;
}
}
}
For people arriving here looking for an answer to a more generic question, you can extend the static class concept if you want your code to look like an enum
.
The following approach works when you haven't finalised the enum names
you want and the enum values
are the string
representation of the enam name
; use nameof()
to make your refactoring simpler.
public static class Colours
{
public static string Red => nameof(Red);
public static string Green => nameof(Green);
public static string Blue => nameof(Blue);
}
This achieves the intention of an enum that has string values (such as the following pseudocode):
public enum Colours
{
"Red",
"Green",
"Blue"
}
I've wrote a small extension to do so.
Since you are creating the page using C# you may want to implement this:
https://github.com/felix-d-git/DesktopAppLink
Basically u are creating some registry entries to parse the links you click in your html page.
The browser will then ask to open the specified app.
C#:
DesktopAppLink.CreateLink("applink.sample", "\"<path to exe>\"", "");
HTML:
<a href="applink.sample:">Run Desktop App</a>
Result:
You must write onActivityResult() in your FirstActivity.Java as follows
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
This will trigger onActivityResult method of fragments on FirstActivity.java
It can also be due to "[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?"
Java 8
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
List<List<String>> stringListList = new ArrayList<>();
stringListList.add(Arrays.asList(new String[] {"(0,0)", "(0,1)"} ));
stringListList.add(Arrays.asList(new String[] {"(1,0)", "(1,1)", "(1,2)"} ));
stringListList.add(Arrays.asList(new String[] {"(2,0)", "(2,1)"} ));
int count=stringListList.stream().mapToInt(i -> i.size()).sum();
System.out.println("stringListList count: "+count);
}
}
Try this set of code to download a CSV file from the server.
byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
try with this
$ cat /tmp/topfs.txt
/dev/sda2 xfs 32G 10G 22G 32% /
awk print last column
$ cat /tmp/topfs.txt | awk '{print $NF}'
awk print before last column
$ cat /tmp/topfs.txt | awk '{print $(NF-1)}'
32%
awk - print last two columns
$ cat /tmp/topfs.txt | awk '{print $(NF-1), $NF}'
32% /
You can use .deepEqual()
const { assert } = require('chai');
assert.deepEqual([0,0], [0,0]);
How I redirect to an area is add it as a parameter
@Html.Action("Action", "Controller", new { area = "AreaName" })
for the href portion of a link I use
@Url.Action("Action", "Controller", new { area = "AreaName" })
The join()
was not helpful to me. see this sample in Kotlin:
val timeInMillis = System.currentTimeMillis()
ThreadUtils.startNewThread(Runnable {
for (i in 1..5) {
val t = Thread(Runnable {
Thread.sleep(50)
var a = i
kotlin.io.println(Thread.currentThread().name + "|" + "a=$a")
Thread.sleep(200)
for (j in 1..5) {
a *= j
Thread.sleep(100)
kotlin.io.println(Thread.currentThread().name + "|" + "$a*$j=$a")
}
kotlin.io.println(Thread.currentThread().name + "|TaskDurationInMillis = " + (System.currentTimeMillis() - timeInMillis))
})
t.start()
}
})
The result:
Thread-5|a=5
Thread-1|a=1
Thread-3|a=3
Thread-2|a=2
Thread-4|a=4
Thread-2|2*1=2
Thread-3|3*1=3
Thread-1|1*1=1
Thread-5|5*1=5
Thread-4|4*1=4
Thread-1|2*2=2
Thread-5|10*2=10
Thread-3|6*2=6
Thread-4|8*2=8
Thread-2|4*2=4
Thread-3|18*3=18
Thread-1|6*3=6
Thread-5|30*3=30
Thread-2|12*3=12
Thread-4|24*3=24
Thread-4|96*4=96
Thread-2|48*4=48
Thread-5|120*4=120
Thread-1|24*4=24
Thread-3|72*4=72
Thread-5|600*5=600
Thread-4|480*5=480
Thread-3|360*5=360
Thread-1|120*5=120
Thread-2|240*5=240
Thread-1|TaskDurationInMillis = 765
Thread-3|TaskDurationInMillis = 765
Thread-4|TaskDurationInMillis = 765
Thread-5|TaskDurationInMillis = 765
Thread-2|TaskDurationInMillis = 765
Now let me use the join()
for threads:
val timeInMillis = System.currentTimeMillis()
ThreadUtils.startNewThread(Runnable {
for (i in 1..5) {
val t = Thread(Runnable {
Thread.sleep(50)
var a = i
kotlin.io.println(Thread.currentThread().name + "|" + "a=$a")
Thread.sleep(200)
for (j in 1..5) {
a *= j
Thread.sleep(100)
kotlin.io.println(Thread.currentThread().name + "|" + "$a*$j=$a")
}
kotlin.io.println(Thread.currentThread().name + "|TaskDurationInMillis = " + (System.currentTimeMillis() - timeInMillis))
})
t.start()
t.join()
}
})
And the result:
Thread-1|a=1
Thread-1|1*1=1
Thread-1|2*2=2
Thread-1|6*3=6
Thread-1|24*4=24
Thread-1|120*5=120
Thread-1|TaskDurationInMillis = 815
Thread-2|a=2
Thread-2|2*1=2
Thread-2|4*2=4
Thread-2|12*3=12
Thread-2|48*4=48
Thread-2|240*5=240
Thread-2|TaskDurationInMillis = 1568
Thread-3|a=3
Thread-3|3*1=3
Thread-3|6*2=6
Thread-3|18*3=18
Thread-3|72*4=72
Thread-3|360*5=360
Thread-3|TaskDurationInMillis = 2323
Thread-4|a=4
Thread-4|4*1=4
Thread-4|8*2=8
Thread-4|24*3=24
Thread-4|96*4=96
Thread-4|480*5=480
Thread-4|TaskDurationInMillis = 3078
Thread-5|a=5
Thread-5|5*1=5
Thread-5|10*2=10
Thread-5|30*3=30
Thread-5|120*4=120
Thread-5|600*5=600
Thread-5|TaskDurationInMillis = 3833
As it's clear when we use the join
:
Our solution to prevent blocking other threads was creating an ArrayList:
val threads = ArrayList<Thread>()
Now when we want to start a new thread we most add it to the ArrayList:
addThreadToArray(
ThreadUtils.startNewThread(Runnable {
...
})
)
The addThreadToArray
function:
@Synchronized
fun addThreadToArray(th: Thread) {
threads.add(th)
}
The startNewThread
funstion:
fun startNewThread(runnable: Runnable) : Thread {
val th = Thread(runnable)
th.isDaemon = false
th.priority = Thread.MAX_PRIORITY
th.start()
return th
}
Check the completion of the threads as below everywhere it's needed:
val notAliveThreads = ArrayList<Thread>()
for (t in threads)
if (!t.isAlive)
notAliveThreads.add(t)
threads.removeAll(notAliveThreads)
if (threads.size == 0){
// The size is 0 -> there is no alive threads.
}
A list comprehension is likely the cleanest way:
>>> L = [0, 23, 234, 89, None, 0, 35, 9
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]
There is also a functional programming approach but it is more involved:
>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> list(filter(partial(is_not, None), L))
[0, 23, 234, 89, 0, 35, 9]
If you have a very big amount of strings (or any other type) case all doing the same thing, I recommend the use of a string list combined with the string.Contains property.
So if you have a big switch statement like so:
switch (stringValue)
{
case "cat":
case "dog":
case "string3":
...
case "+1000 more string": // Too many string to write a case for all!
// Do something;
case "a lonely case"
// Do something else;
.
.
.
}
You might want to replace it with an if
statement like this:
// Define all the similar "case" string in a List
List<string> listString = new List<string>(){ "cat", "dog", "string3", "+1000 more string"};
// Use string.Contains to find what you are looking for
if (listString.Contains(stringValue))
{
// Do something;
}
else
{
// Then go back to a switch statement inside the else for the remaining cases if you really need to
}
This scale well for any number of string cases.
You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep
, sed
, etc) that do.
What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.
Newer versions of bash do have a regular expression operator, =~
:
for x in `ls`; do
if [[ $x =~ .+\..* ]]; then
echo $x;
fi;
done
I used this way (had to check wherever is Shift + Ctrl pressed):
// create some object to save all pressed keys
var keys = {
shift: false,
ctrl: false
};
$(document.body).keydown(function(event) {
// save status of the button 'pressed' == 'true'
if (event.keyCode == 16) {
keys["shift"] = true;
} else if (event.keyCode == 17) {
keys["ctrl"] = true;
}
if (keys["shift"] && keys["ctrl"]) {
$("#convert").trigger("click"); // or do anything else
}
});
$(document.body).keyup(function(event) {
// reset status of the button 'released' == 'false'
if (event.keyCode == 16) {
keys["shift"] = false;
} else if (event.keyCode == 17) {
keys["ctrl"] = false;
}
});
SELECT @variable1 = col1, @variable2 = col2
FROM table1
Here a simple solution without any external lib:
https://www.codexworld.com/export-html-table-data-to-csv-using-javascript/
It works for me without any issue
You can use inline css :
<td style = "text-align: center;">
<div id="normal>text..</div>
<div id="small1" class="smallDiv"></div>
<div id="small2" class="smallDiv"></div>
<div id="small3" class="smallDiv"></div>
css:
.smallDiv { height: 150px; width: 150px; }
You also can do this very easily with awk
, if you're willing to consider a different tool:
echo "UPPER" | awk '{print tolower($0)}'
In C/C++ programming there are two types of strings: the C strings and the standard strings. With the <string>
header, we can use the standard strings. On the other hand, the C strings are just an array of normal chars. So, in order to convert a standard string to a C string, we use the c_str()
function.
for example
// a string to a C-style string conversion//
const char *cstr1 = str1.c_str();
cout<<"Operation: *cstr1 = str1.c_str()"<<endl;
cout<<"The C-style string c_str1 is: "<<cstr1<<endl;
cout<<"\nOperation: strlen(cstr1)"<<endl;
cout<<"The length of C-style string str1 = "<<strlen(cstr1)<<endl;
And the output will be,
Operation: *cstr1 = str1.c_str()
The C-style string c_str1 is: Testing the c_str
Operation: strlen(cstr1)
The length of C-style string str1 = 17
For a small enum like this, I find the most readable solution to be:
public enum Direction {
NORTH {
@Override
public Direction getOppositeDirection() {
return SOUTH;
}
},
SOUTH {
@Override
public Direction getOppositeDirection() {
return NORTH;
}
},
EAST {
@Override
public Direction getOppositeDirection() {
return WEST;
}
},
WEST {
@Override
public Direction getOppositeDirection() {
return EAST;
}
};
public abstract Direction getOppositeDirection();
}
Regarding the first (and great) answer from chris who proposed a solution to the situation where the class members are held as a "true composite" members (i.e.- not as pointers nor references):
The note is a bit large, so I will demonstrate it here with some sample code.
When you chose to hold the members as I mentioned, you have to keep in mind also these two things:
For every "composed object" that does not have a default constructor - you must initialize it in the initialization list of all the constructor's of the "father" class (i.e.- BigMommaClass
or MyClass
in the original examples and MyClass
in the code below), in case there are several (see InnerClass1
in the example below). Meaning, you can "comment out" the m_innerClass1(a)
and m_innerClass1(15)
only if you enable the InnerClass1
default constructor.
For every "composed object" that does have a default constructor - you may initialize it within the initialization list, but it will work also if you chose not to (see InnerClass2
in the example below).
See sample code (compiled under Ubuntu 18.04 (Bionic Beaver) with g++
version 7.3.0):
#include <iostream>
using namespace std;
class InnerClass1
{
public:
InnerClass1(int a) : m_a(a)
{
cout << "InnerClass1::InnerClass1 - set m_a:" << m_a << endl;
}
/* No default constructor
InnerClass1() : m_a(15)
{
cout << "InnerClass1::InnerClass1() - set m_a:" << m_a << endl;
}
*/
~InnerClass1()
{
cout << "InnerClass1::~InnerClass1" << endl;
}
private:
int m_a;
};
class InnerClass2
{
public:
InnerClass2(int a) : m_a(a)
{
cout << "InnerClass2::InnerClass2 - set m_a:" << m_a << endl;
}
InnerClass2() : m_a(15)
{
cout << "InnerClass2::InnerClass2() - set m_a:" << m_a << endl;
}
~InnerClass2()
{
cout << "InnerClass2::~InnerClass2" << endl;
}
private:
int m_a;
};
class MyClass
{
public:
MyClass(int a, int b) : m_innerClass1(a), /* m_innerClass2(a),*/ m_b(b)
{
cout << "MyClass::MyClass(int b) - set m_b to:" << m_b << endl;
}
MyClass() : m_innerClass1(15), /*m_innerClass2(15),*/ m_b(17)
{
cout << "MyClass::MyClass() - m_b:" << m_b << endl;
}
~MyClass()
{
cout << "MyClass::~MyClass" << endl;
}
private:
InnerClass1 m_innerClass1;
InnerClass2 m_innerClass2;
int m_b;
};
int main(int argc, char** argv)
{
cout << "main - start" << endl;
MyClass obj;
cout << "main - end" << endl;
return 0;
}
You are creating a set
via set(...)
call, and set
needs hashable items. You can't have set of lists. Because list's arent hashable.
[[(a,b) for a in range(3)] for b in range(3)]
is a list. It's not a hashable type. The __hash__
you saw in dir(...) isn't a method, it's just None.
A list comprehension returns a list, you don't need to explicitly use list there, just use:
>>> [[(a,b) for a in range(3)] for b in range(3)]
[[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]
Try those:
>>> a = {1, 2, 3}
>>> b= [1, 2, 3]
>>> type(a)
<class 'set'>
>>> type(b)
<class 'list'>
>>> {1, 2, []}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> print([].__hash__)
None
>>> [[],[],[]] #list of lists
[[], [], []]
>>> {[], [], []} #set of lists
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
I ran into this same issue, but I think I know what's causing the confusion. If you use MySql Query Analyzer, you can do this just fine:
SELECT myvalue
INTO @myvar
FROM mytable
WHERE anothervalue = 1;
However, if you put that same query in MySql Workbench, it will throw a syntax error. I don't know why they would be different, but they are. To work around the problem in MySql Workbench, you can rewrite the query like this:
SELECT @myvar:=myvalue
FROM mytable
WHERE anothervalue = 1;
I accomplished something similar using jQuery Waypoints.
There's a lot of moving parts, and quite a bit of logic (that I hope to get on GitHub some day soon), but essentially what you could do is...
fixed
.table.fixed
that make it invisible.sticky
to table.fixed
table.sticky.fixed
that position it just below the navbar and also make just the thead
content visible. This also has a z-index
so it is laid above the rest of the content..sticky
from the table.fixed
You have to duplicate the entire table DOM in order to ensure column widths line up appropriately.
If that sounds really complicated, you might want to try playing around with the DataTables plugin and the FixedHeader extension: https://datatables.net/extensions/fixedheader/
mylist = ['Mixed Case One', 'Mixed Case Two', 'Mixed Three']
print(list(map(lambda x: x.lower(), mylist)))
print(list(map(lambda x: x.upper(), mylist)))
If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.
EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character
The JavaScript Object()
constructor makes an Object that you can assign members to.
myObj = new Object()
myObj.key = value;
myObj[key2] = value2; // Alternative
OOP Style : At first connection with database.
<?php
class database
{
public $host = "localhost";
public $user = "root";
public $pass = "";
public $db = "db";
public $link;
public function __construct()
{
$this->connect();
}
private function connect()
{
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->db);
return $this->link;
}
public function select($query)
{
$result = $this->link->query($query) or die($this->link->error.__LINE__);
if($result->num_rows>0)
{
return $result;
}
else
{
return false;
}
}
?>
Then :
<?php
$db = new database();
$query = "select * from data";
$result = $db->select($query);
echo "<table>";
echo "<tr>";
echo "<th>Name </th>";
echo "<th>Roll </th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> $row[name]</td>";
echo "<td> $row[roll]</td>";
echo "</tr>";
}
echo "</table>";
?>
It's hard for us to bind a specific USB device to a docker container which is also specific. As you can see, the recommended way to achieve is:
docker run -t -i --privileged -v /dev/bus/usb:/dev/bus/usb ubuntu bash
It will bind all the devices to this container. It's unsafe. Every containers were granted to operate all of them.
Another way is binding devices by devpath. It may looks like:
docker run -t -i --privileged -v /dev/bus/usb/001/002:/dev/bus/usb/001/002 ubuntu bash
or --device
(better, no privileged
):
docker run -t -i --device /dev/bus/usb/001/002 ubuntu bash
Much safer. But actually it is hard to know what the devpath of a specific device is.
I have wrote this repo to solve this problem.
https://github.com/williamfzc/usb2container
After deploying this server, you can easily get all the connected devices' information via HTTP request:
curl 127.0.0.1:9410/api/device
and get:
{
"/devices/pci0000:00/0000:00:14.0/usb1/1-13": {
"ACTION": "add",
"DEVPATH": "/devices/pci0000:00/0000:00:14.0/usb1/1-13",
"DEVTYPE": "usb_device",
"DRIVER": "usb",
"ID_BUS": "usb",
"ID_FOR_SEAT": "xxxxx",
"ID_MODEL": "xxxxx",
"ID_MODEL_ID": "xxxxx",
"ID_PATH": "xxxxx",
"ID_PATH_TAG": "xxxxx",
"ID_REVISION": "xxxxx",
"ID_SERIAL": "xxxxx",
"ID_SERIAL_SHORT": "xxxxx",
"ID_USB_INTERFACES": "xxxxx",
"ID_VENDOR": "xxxxx",
"ID_VENDOR_ENC": "xxxxx",
"ID_VENDOR_FROM_DATABASE": "",
"ID_VENDOR_ID": "xxxxx",
"INTERFACE": "",
"MAJOR": "189",
"MINOR": "119",
"MODALIAS": "",
"PRODUCT": "xxxxx",
"SEQNUM": "xxxxx",
"SUBSYSTEM": "usb",
"TAGS": "",
"TYPE": "0/0/0",
"USEC_INITIALIZED": "xxxxx",
"adb_user": "",
"_empty": false,
"DEVNAME": "/dev/bus/usb/001/120",
"BUSNUM": "001",
"DEVNUM": "120",
"ID_MODEL_ENC": "xxxxx"
},
...
}
and bind them to your containers. For example, you can see the DEVNAME of this device is /dev/bus/usb/001/120
:
docker run -t -i --device /dev/bus/usb/001/120 ubuntu bash
Maybe it will help.
Make sure the function is in the same DB schema as the table.
Facebook.com og:image is 325x325 (1:1 aspect ratio, square)
I find this simple T-SQL query useful for returning valid e-mail addresses
SELECT email
FROM People
WHERE email LIKE '%_@__%.__%'
AND PATINDEX('%[^a-z,0-9,@,.,_]%', REPLACE(email, '-', 'a')) = 0
The PATINDEX bit eliminates all e-mail addresses containing characters that are not in the allowed a-z, 0-9, '@', '.', '_' & '-' set of characters.
It can be reversed to do what you want like this:
SELECT email
FROM People
WHERE NOT (email LIKE '%_@__%.__%'
AND PATINDEX('%[^a-z,0-9,@,.,_]%', REPLACE(email, '-', 'a')) = 0)
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
Look at the example:
<select class="element select small" id="account_name" name="account_name">
<option value="" selected="selected">Please Select</option>
<option value="paypal" >Paypal</option>
<option value="webmoney" >Webmoney</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$('#account_name').change(function(){
alert($(this).val());
});
});
</script>
I was having this issue and found that within ~/.ssh/config
I had a line that read:
UserKnownHostsFile=/home/.ssh-agent/known_hosts
I just modified this line to read:
UserKnownHostsFile=~/.ssh/known_hosts
That fixed the problem for me.
For me it was the http://localhost instead of https://localhost.
You can use [[UINavigationBar appearance] setTintColor:myColor];
Since iOS 7 you need to set [[UINavigationBar appearance] setBarTintColor:myColor];
and also [[UINavigationBar appearance] setTranslucent:NO]
.
[[UINavigationBar appearance] setBarTintColor:myColor];
[[UINavigationBar appearance] setTranslucent:NO];
You can just use the TimeOfDay property of date time, which is TimeSpan type:
DateTime.TimeOfDay
This property has been around since .NET 1.1
More information: http://msdn.microsoft.com/en-us/library/system.datetime.timeofday(v=vs.110).aspx
Issue is with the Json.parse of empty array - scatterSeries , as you doing console log of scatterSeries before pushing ch
var data = { "results":[ _x000D_
[ _x000D_
{ _x000D_
"b":"0.110547334",_x000D_
"cost":"0.000000",_x000D_
"w":"1.998889"_x000D_
}_x000D_
],_x000D_
[ _x000D_
{ _x000D_
"x":0,_x000D_
"y":0_x000D_
},_x000D_
{ _x000D_
"x":1,_x000D_
"y":2_x000D_
},_x000D_
{ _x000D_
"x":2,_x000D_
"y":4_x000D_
},_x000D_
{ _x000D_
"x":3,_x000D_
"y":6_x000D_
},_x000D_
{ _x000D_
"x":4,_x000D_
"y":8_x000D_
},_x000D_
{ _x000D_
"x":5,_x000D_
"y":10_x000D_
},_x000D_
{ _x000D_
"x":6,_x000D_
"y":12_x000D_
},_x000D_
{ _x000D_
"x":7,_x000D_
"y":14_x000D_
},_x000D_
{ _x000D_
"x":8,_x000D_
"y":16_x000D_
},_x000D_
{ _x000D_
"x":9,_x000D_
"y":18_x000D_
},_x000D_
{ _x000D_
"x":10,_x000D_
"y":20_x000D_
},_x000D_
{ _x000D_
"x":11,_x000D_
"y":22_x000D_
},_x000D_
{ _x000D_
"x":12,_x000D_
"y":24_x000D_
},_x000D_
{ _x000D_
"x":13,_x000D_
"y":26_x000D_
},_x000D_
{ _x000D_
"x":14,_x000D_
"y":28_x000D_
},_x000D_
{ _x000D_
"x":15,_x000D_
"y":30_x000D_
},_x000D_
{ _x000D_
"x":16,_x000D_
"y":32_x000D_
},_x000D_
{ _x000D_
"x":17,_x000D_
"y":34_x000D_
},_x000D_
{ _x000D_
"x":18,_x000D_
"y":36_x000D_
},_x000D_
{ _x000D_
"x":19,_x000D_
"y":38_x000D_
},_x000D_
{ _x000D_
"x":20,_x000D_
"y":40_x000D_
},_x000D_
{ _x000D_
"x":21,_x000D_
"y":42_x000D_
},_x000D_
{ _x000D_
"x":22,_x000D_
"y":44_x000D_
},_x000D_
{ _x000D_
"x":23,_x000D_
"y":46_x000D_
},_x000D_
{ _x000D_
"x":24,_x000D_
"y":48_x000D_
},_x000D_
{ _x000D_
"x":25,_x000D_
"y":50_x000D_
},_x000D_
{ _x000D_
"x":26,_x000D_
"y":52_x000D_
},_x000D_
{ _x000D_
"x":27,_x000D_
"y":54_x000D_
},_x000D_
{ _x000D_
"x":28,_x000D_
"y":56_x000D_
},_x000D_
{ _x000D_
"x":29,_x000D_
"y":58_x000D_
},_x000D_
{ _x000D_
"x":30,_x000D_
"y":60_x000D_
},_x000D_
{ _x000D_
"x":31,_x000D_
"y":62_x000D_
},_x000D_
{ _x000D_
"x":32,_x000D_
"y":64_x000D_
},_x000D_
{ _x000D_
"x":33,_x000D_
"y":66_x000D_
},_x000D_
{ _x000D_
"x":34,_x000D_
"y":68_x000D_
},_x000D_
{ _x000D_
"x":35,_x000D_
"y":70_x000D_
},_x000D_
{ _x000D_
"x":36,_x000D_
"y":72_x000D_
},_x000D_
{ _x000D_
"x":37,_x000D_
"y":74_x000D_
},_x000D_
{ _x000D_
"x":38,_x000D_
"y":76_x000D_
},_x000D_
{ _x000D_
"x":39,_x000D_
"y":78_x000D_
},_x000D_
{ _x000D_
"x":40,_x000D_
"y":80_x000D_
},_x000D_
{ _x000D_
"x":41,_x000D_
"y":82_x000D_
},_x000D_
{ _x000D_
"x":42,_x000D_
"y":84_x000D_
},_x000D_
{ _x000D_
"x":43,_x000D_
"y":86_x000D_
},_x000D_
{ _x000D_
"x":44,_x000D_
"y":88_x000D_
},_x000D_
{ _x000D_
"x":45,_x000D_
"y":90_x000D_
},_x000D_
{ _x000D_
"x":46,_x000D_
"y":92_x000D_
},_x000D_
{ _x000D_
"x":47,_x000D_
"y":94_x000D_
},_x000D_
{ _x000D_
"x":48,_x000D_
"y":96_x000D_
},_x000D_
{ _x000D_
"x":49,_x000D_
"y":98_x000D_
},_x000D_
{ _x000D_
"x":50,_x000D_
"y":100_x000D_
},_x000D_
{ _x000D_
"x":51,_x000D_
"y":102_x000D_
},_x000D_
{ _x000D_
"x":52,_x000D_
"y":104_x000D_
},_x000D_
{ _x000D_
"x":53,_x000D_
"y":106_x000D_
},_x000D_
{ _x000D_
"x":54,_x000D_
"y":108_x000D_
},_x000D_
{ _x000D_
"x":55,_x000D_
"y":110_x000D_
},_x000D_
{ _x000D_
"x":56,_x000D_
"y":112_x000D_
},_x000D_
{ _x000D_
"x":57,_x000D_
"y":114_x000D_
},_x000D_
{ _x000D_
"x":58,_x000D_
"y":116_x000D_
},_x000D_
{ _x000D_
"x":59,_x000D_
"y":118_x000D_
},_x000D_
{ _x000D_
"x":60,_x000D_
"y":120_x000D_
},_x000D_
{ _x000D_
"x":61,_x000D_
"y":122_x000D_
},_x000D_
{ _x000D_
"x":62,_x000D_
"y":124_x000D_
},_x000D_
{ _x000D_
"x":63,_x000D_
"y":126_x000D_
},_x000D_
{ _x000D_
"x":64,_x000D_
"y":128_x000D_
},_x000D_
{ _x000D_
"x":65,_x000D_
"y":130_x000D_
},_x000D_
{ _x000D_
"x":66,_x000D_
"y":132_x000D_
},_x000D_
{ _x000D_
"x":67,_x000D_
"y":134_x000D_
},_x000D_
{ _x000D_
"x":68,_x000D_
"y":136_x000D_
},_x000D_
{ _x000D_
"x":69,_x000D_
"y":138_x000D_
},_x000D_
{ _x000D_
"x":70,_x000D_
"y":140_x000D_
},_x000D_
{ _x000D_
"x":71,_x000D_
"y":142_x000D_
},_x000D_
{ _x000D_
"x":72,_x000D_
"y":144_x000D_
},_x000D_
{ _x000D_
"x":73,_x000D_
"y":146_x000D_
},_x000D_
{ _x000D_
"x":74,_x000D_
"y":148_x000D_
},_x000D_
{ _x000D_
"x":75,_x000D_
"y":150_x000D_
},_x000D_
{ _x000D_
"x":76,_x000D_
"y":152_x000D_
},_x000D_
{ _x000D_
"x":77,_x000D_
"y":154_x000D_
},_x000D_
{ _x000D_
"x":78,_x000D_
"y":156_x000D_
},_x000D_
{ _x000D_
"x":79,_x000D_
"y":158_x000D_
},_x000D_
{ _x000D_
"x":80,_x000D_
"y":160_x000D_
},_x000D_
{ _x000D_
"x":81,_x000D_
"y":162_x000D_
},_x000D_
{ _x000D_
"x":82,_x000D_
"y":164_x000D_
},_x000D_
{ _x000D_
"x":83,_x000D_
"y":166_x000D_
},_x000D_
{ _x000D_
"x":84,_x000D_
"y":168_x000D_
},_x000D_
{ _x000D_
"x":85,_x000D_
"y":170_x000D_
},_x000D_
{ _x000D_
"x":86,_x000D_
"y":172_x000D_
},_x000D_
{ _x000D_
"x":87,_x000D_
"y":174_x000D_
},_x000D_
{ _x000D_
"x":88,_x000D_
"y":176_x000D_
},_x000D_
{ _x000D_
"x":89,_x000D_
"y":178_x000D_
},_x000D_
{ _x000D_
"x":90,_x000D_
"y":180_x000D_
},_x000D_
{ _x000D_
"x":91,_x000D_
"y":182_x000D_
},_x000D_
{ _x000D_
"x":92,_x000D_
"y":184_x000D_
},_x000D_
{ _x000D_
"x":93,_x000D_
"y":186_x000D_
},_x000D_
{ _x000D_
"x":94,_x000D_
"y":188_x000D_
},_x000D_
{ _x000D_
"x":95,_x000D_
"y":190_x000D_
},_x000D_
{ _x000D_
"x":96,_x000D_
"y":192_x000D_
},_x000D_
{ _x000D_
"x":97,_x000D_
"y":194_x000D_
},_x000D_
{ _x000D_
"x":98,_x000D_
"y":196_x000D_
},_x000D_
{ _x000D_
"x":99,_x000D_
"y":198_x000D_
}_x000D_
]]};_x000D_
_x000D_
var scatterSeries = []; _x000D_
_x000D_
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';_x000D_
console.info(ch);_x000D_
_x000D_
scatterSeries.push(JSON.parse(ch));_x000D_
console.info(scatterSeries);
_x000D_
code sample - https://codepen.io/nagasai/pen/GGzZVB
if you are in a activity, assume there is only one root view,you can get it like this.
ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
you can then cast it to your real class
or you could using
getWindow().getDecorView();
notice this will include the actionbar view, your view is below the actionbar view
If all you want to do is store some static values in a lookup table, you can use an Object Literal (the same format used by JSON) to do it compactly:
var table = { one: [1,10,5], two: [2], three: [3, 30, 300] }
And then access them using JavaScript's associative array syntax:
alert(table['one']); // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10
Check out the contents of your array with
echo '<pre>' . print_r( $arr, TRUE ) . '</pre>';
Replace Null Values as Empty: ISNULL('Value','')
Replace Null Values as 0: ISNULL('Value',0)
Eileen: No, it is not var nameVal = form.inputname.val();
. It should be either...
in jQuery:
// you can use IDs (easier)
var nameVal = $(form).find('#id').val();
// or use the [name=Fieldname] to search for the field
var nameVal = $(form).find('[name=Fieldname]').val();
Or in JavaScript:
var nameVal = this.form.FieldName.value;
Or a combination:
var nameVal = $(this.form.FieldName).val();
With jQuery, you could even loop through all of the inputs in the form:
$(form).find('input, select, textarea').each(function(){
var name = this.name;
// OR
var name = $(this).attr('name');
var value = this.value;
// OR
var value = $(this).val();
....
});
Or if you need it in a loop
foreach ($array as $key => $value)
{
echo $key . ':' . $value . "\n";
}
//Result:
//one:value
//two:value2
This doesn't seem to be a problem on a Core 2 Duo running Windows XP and JRE 1.5.0_06.
In a test with three threads I don't see System.nanoTime() going backwards. The processors are both busy, and threads go to sleep occasionally to provoke moving threads around.
[EDIT] I would guess that it only happens on physically separate processors, i.e. that the counters are synchronized for multiple cores on the same die.
I ran into this scenario recently (well over 7 million rows) and eneded up using sqlcmd via powershell (after parsing raw data into SQL insert statements) in segments of 5,000 at a time (SQL can't handle 7 million lines in one lump job or even 500,000 lines for that matter unless its broken down into smaller 5K pieces. You can then run each 5K script one after the other.) as I needed to leverage the new sequence command in SQL Server 2012 Enterprise. I couldn't find a programatic way to insert seven million rows of data quickly and efficiently with said sequence command.
Secondly, one of the things to look out for when inserting a million rows or more of data in one sitting is the CPU and memory consumption (mostly memory) during the insert process. SQL will eat up memory/CPU with a job of this magnitude without releasing said processes. Needless to say if you don't have enough processing power or memory on your server you can crash it pretty easily in a short time (which I found out the hard way). If you get to the point to where your memory consumption is over 70-75% just reboot the server and the processes will be released back to normal.
I had to run a bunch of trial and error tests to see what the limits for my server was (given the limited CPU/Memory resources to work with) before I could actually have a final execution plan. I would suggest you do the same in a test environment before rolling this out into production.
One-line version of the accepted answer:
$out=explode("/", $mystring, 2)[0];
Should work in php 5.4+
"setRequestHeader" method of XMLHttpRequest object should be used
To create HTML in email template that is emailer/newsletter, padding/margin is not supporting on email clients. You can take 1x1 size of blank gif image and use it.
<tr>
<td align="left" valign="top" style="background-color:#7d9aaa;">
<table width="640" cellspacing="0" cellpadding="0" border="0">
<tr>
<td align="left" valign="top" colspan="5"><img style="display:block;" src="images/spacer.gif" width="1" height="10" alt="" /></td>
</tr>
<tr>
<td align="left" valign="top"><img style="display:block;" src="images/spacer.gif" width="20" height="1" alt="" /></td>
<td align="right" valign="top"><font face="arial" color="#ffffff" style="font-size:14px;"><a href="#" style="color:#ffffff; text-decoration:none; cursor:pointer;" target="_blank">Order Confirmation</a></font></td>
<td align="left" valign="top" width="200"><img style="display:block;" src="images/spacer.gif" width="200" height="1" alt="" /></td>
<td align="left" valign="top"><font face="arial" color="#ffffff" style="font-size:14px;">Your Confirmation Number is 260556</font></td>
<td align="left" valign="top"><img style="display:block;" src="images/spacer.gif" width="20" height="1" alt="" /></td>
</tr>
<tr>
<td align="left" valign="top" colspan="5"><img style="display:block;" src="images/spacer.gif" width="1" height="10" alt="" /></td>
</tr>
</table>
</td>
</tr>
If you are a GUI guy and just want to find it in PhpMyAdmin, than pick the table of your choice and head over the Operations
tab >> Table options
>> Storage Engine
.
You can even change it from there using the drop-down options list.
PS: This guide is based on version 4.8 of PhpMyAdmin. Can't guarantee the same path for very older versions.
Here is a more comprehensive method that can also accept full month names
def month_string_to_number(string):
m = {
'jan': 1,
'feb': 2,
'mar': 3,
'apr':4,
'may':5,
'jun':6,
'jul':7,
'aug':8,
'sep':9,
'oct':10,
'nov':11,
'dec':12
}
s = string.strip()[:3].lower()
try:
out = m[s]
return out
except:
raise ValueError('Not a month')
example:
>>> month_string_to_number("October")
10
>>> month_string_to_number("oct")
10
This is how you do it using ASP.NET:
add .Format("{0:dd/MM/yyyy HH:mm:ss}");
@(Html.Kendo().Grid<AlphaStatic.Domain.ViewModels.AttributeHistoryViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.AttributeName);
columns.Bound(c => c.UpdatedDate).Format("{0:dd/MM/yyyy HH:mm:ss}");
})
.HtmlAttributes(new { @class = ".big-grid" })
.Resizable(x => x.Columns(true))
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(c => c.Id);
})
.Read(read => read.Action("Read_AttributeHistory", "Attribute", new { attributeId = attributeId })))
)
Try this all four way to take input with space :)
#include<iostream>
#include<stdio.h>
using namespace std;
void dinput(char *a)
{
for(int i=0;; i++)
{
cin >> noskipws >> a[i];
if(a[i]=='\n')
{
a[i]='\0';
break;
}
}
}
void input(char *a)
{
//cout<<"\nInput string: ";
for(int i=0;; i++)
{
*(a+i*sizeof(char))=getchar();
if(*(a+i*sizeof(char))=='\n')
{
*(a+i*sizeof(char))='\0';
break;
}
}
}
int main()
{
char a[20];
cout<<"\n1st method\n";
input(a);
cout<<a;
cout<<"\n2nd method\n";
cin.get(a,10);
cout<<a;
cout<<"\n3rd method\n";
cin.sync();
cin.getline(a,sizeof(a));
cout<<a;
cout<<"\n4th method\n";
dinput(a);
cout<<a;
return 0;
}
I used SSH.Net in a project a while ago and was very happy with it. It also comes with a good documentation with lots of samples on how to use it.
The original package website can be still found here, including the documentation (which currently isn't available on GitHub).
For your case the code would be something like this.
using (var client = new SshClient("hostnameOrIp", "username", "password"))
{
client.Connect();
client.RunCommand("etc/init.d/networking restart");
client.Disconnect();
}
The proper test is:
if (capital != null && capital.length < 1) {
This ensures that capital
is always non null, when you perform the length check.
Also, as the comments suggest, capital
is null
because you never initialize it.
With -Raw
you should get what you expect
Here is my cover fill solution (similar to background-size: cover, but it supports old IE browser)
<div class="imgContainer" style="height:100px; width:500px; overflow:hidden; background-color: black">
<img src="http://dev.isaacsonwebdevelopment.com/sites/development/files/views-slideshow-settings-jquery-cycle-custom-options-message.png" id="imgCat">
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script>
$(window).load(function() {
var heightRate =$("#imgCat").height() / $("#imgCat").parent(".imgContainer").height();
var widthRate = $("#imgCat").width() / $("#imgCat").parent(".imgContainer").width();
if (window.console) {
console.log($("#imgCat").height());
console.log(heightRate);
console.log(widthRate);
console.log(heightRate > widthRate);
}
if (heightRate <= widthRate) {
$("#imgCat").height($("#imgCat").parent(".imgContainer").height());
} else {
$("#imgCat").width($("#imgCat").parent(".imgContainer").width());
}
});
</script>
In VB.NET, you need to use the GetType
method to retrieve the type of an instance of an object, and the GetType()
operator to retrieve the type of another known type.
Once you have the two types, you can simply compare them using the Is
operator.
So your code should actually be written like this:
Sub FillCategories(ByVal Obj As Object)
Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
cmd.CommandType = CommandType.StoredProcedure
Obj.DataSource = cmd.ExecuteReader
If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then
End If
Obj.DataBind()
End Sub
You can also use the TypeOf
operator instead of the GetType
method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:
If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then
End If
Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.
For languages not specifying a memory model, you are writing code for the language and the memory model specified by the processor architecture. The processor may choose to re-order memory accesses for performance. So, if your program has data races (a data race is when it's possible for multiple cores / hyper-threads to access the same memory concurrently) then your program is not cross platform because of its dependence on the processor memory model. You may refer to the Intel or AMD software manuals to find out how the processors may re-order memory accesses.
Very importantly, locks (and concurrency semantics with locking) are typically implemented in a cross platform way... So if you are using standard locks in a multithreaded program with no data races then you don't have to worry about cross platform memory models.
Interestingly, Microsoft compilers for C++ have acquire / release semantics for volatile which is a C++ extension to deal with the lack of a memory model in C++ http://msdn.microsoft.com/en-us/library/12a04hfd(v=vs.80).aspx. However, given that Windows runs on x86 / x64 only, that's not saying much (Intel and AMD memory models make it easy and efficient to implement acquire / release semantics in a language).
If the image is a piece of semantic data (like a profile picture, for example), then use an <img>
element inside your <button>
and use CSS to resize the <img>
. If the image is just a way to make a button visually pleasing, use CSS background-image
to style the <button>
(and don't use an <img>
).
Demo: http://jsfiddle.net/ThinkingStiff/V5Xqr/
HTML:
<button id="close-image"><img src="http://thinkingstiff.com/images/matt.jpg"></button>
<button id="close-CSS"></button>
CSS:
button {
display: inline-block;
height: 134px;
padding: 0;
margin: 0;
vertical-align: top;
width: 104px;
}
#close-image img {
display: block;
height: 130px;
width: 100px;
}
#close-CSS {
background-image: url( 'http://thinkingstiff.com/images/matt.jpg' );
background-size: 100px 130px;
height: 134px;
width: 104px;
}
Output:
TimeSpan span = end-start;
double totalMinutes = span.TotalMinutes;
please try with setting margin and padding to 0 on body.
<body style="margin: 0 0 0 0; padding: 0 0 0 0;">
SQL is the actual language that as defined by the ISO and ANSI. Here is a link to the Wikipedia article. MySQL is a specific implementation of this standard. I believe Oracle bought the company that originally developed MySQL. Other companies also have their own implementations of the SQL standard.
This happened to me because I was using:
app.datasource.url=jdbc:mysql://localhost/test
When I replaced url by jdbc-url
then it worked:
app.datasource.jdbc-url=jdbc:mysql://localhost/test
since python 3.5 you can use *
iterable unpacking operator:
user_list = [*your_iterator]
but the pythonic way to do it is:
user_list = list(your_iterator)
So there might be a few things wrong here.
First start by reading how to use XMLHttpRequest.open()
because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send()
. Here's an example from MDN:
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "http://www.mozilla.org/", true);
oXHR.onreadystatechange = function (oEvent) {
if (oXHR.readyState === 4) {
if (oXHR.status === 200) {
console.log(oXHR.responseText)
} else {
console.log("Error", oXHR.statusText);
}
}
};
oXHR.send(null);
Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml
file.
You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:
var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false);
request.send(null);
if (request.status == 0)
console.log(request.responseText);
Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.
The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:
<StackPanel>
<Label Foreground="Red">Red text</Label>
<Label Foreground="Blue">Blue text</Label>
</StackPanel>
In summary, No, there was nothing wrong with your snippet.
There are many good answers here but you should avoid at all cost to pass untrusted variables to subprocess using shell=True
as this is a security risk. The variables can escape to the shell and run arbitrary commands! If you just can't avoid it at least use python3's shlex.quote()
to escape the string (if you have multiple space-separated arguments, quote each split instead of the full string).
shell=False
is always the default where you pass an argument array.
Now the safe solutions...
Change your own process's environment - the new environment will apply to python itself and all subprocesses.
os.environ['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)
Make a copy of the environment and pass is to the childen. You have total control over the children environment and won't affect python's own environment.
myenv = os.environ.copy()
myenv['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command, env=myenv)
Unix only: Execute env
to set the environment variable. More cumbersome if you have many variables to modify and not portabe, but like #2 you retain full control over python and children environments.
command = ['env', 'LD_LIBRARY_PATH=my_path', 'sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)
Of course if var1
contain multiple space-separated argument they will now be passed as a single argument with spaces. To retain original behavior with shell=True
you must compose a command array that contain the splitted string:
command = ['sqsub', '-np'] + var1.split() + ['/homedir/anotherdir/executable']
If you want to add a scroll bar using jquery the following will work. If your div had a id of 'mydiv' you could us the following jquery id selector with css property:
jQuery('#mydiv').css("overflow-y", "scroll");
In this code you access to root
directory project:
string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
then:
StreamReader r = new StreamReader(_filePath + "/cities2.json"))
The JTable constructor accepts two arguments 2dimension Object Array for the data, and String Array for the column names.
eg:
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Test6 extends JFrame {
public Test6(){
this.setSize(300,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Mpanel m = new Mpanel();
this.add(m,BorderLayout.CENTER);
}
class Mpanel extends JPanel {
JTable mTable;
private Object[][] cells = {{"Vivek",10.00},{"Vishal",20.00}};
private String[] columnNames = { "Planet", "Radius" };
JScrollPane mScroll;
public Mpanel(){
this.setSize(150,150);
this.setComponent();
}
public void setComponent(){
mTable = new JTable(cells,columnNames);
mTable.setAutoCreateRowSorter(true);
mScroll = new JScrollPane(mTable);
this.add(mScroll);
}
}
public static void main(String[] args){
new Test6().setVisible(true);
}
}
simply create two list in adapter one orignal and one temp and implements Filterable.
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<T> results = new ArrayList<>();
if (origList == null)
origList = new ArrayList<>(itemList);
if (constraint != null && constraint.length() > 0) {
if (origList != null && origList.size() > 0) {
for (final T cd : origList) {
if (cd.getAttributeToSearch().toLowerCase()
.contains(constraint.toString().toLowerCase()))
results.add(cd);
}
}
oReturn.values = results;
oReturn.count = results.size();//newly Aded by ZA
} else {
oReturn.values = origList;
oReturn.count = origList.size();//newly added by ZA
}
return oReturn;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(final CharSequence constraint,
FilterResults results) {
itemList = new ArrayList<>((ArrayList<T>) results.values);
// FIXME: 8/16/2017 implement Comparable with sort below
///Collections.sort(itemList);
notifyDataSetChanged();
}
};
}
where
public GenericBaseAdapter(Context mContext, List<T> itemList) {
this.mContext = mContext;
this.itemList = itemList;
this.origList = itemList;
}
Try like Below
var Boolify = require('node-boolify').Boolify;
if (!Boolify(val)) {
//your instruction
}
Refer node-boolify
Another method that can be used to copy tables from the source database to the destination one is the SQL Server Export and Import wizard, which is available in SQL Server Management Studio.
You have the choice to export from the source database or import from the destination one in order to transfer the data.
This method is a quick way to copy tables from the source database to the destination one, if you arrange to copy tables having no concern with the tables’ relationships and orders.
When using this method, the tables’ indexes and keys will not be transferred. If you are interested in copying it, you need to generate scripts for these database objects.
If these are Foreign Keys, connecting these tables together, you need to export the data in the correct order, otherwise the export wizard will fail.
Feel free to read more about this method, as well as about some more methods (including generate scripts, SELECT INTO and third party tools) in this article: https://www.sqlshack.com/how-to-copy-tables-from-one-database-to-another-in-sql-server/
For xlsx I like the solution posted earlier as https://web.archive.org/web/20180216070531/https://stackoverflow.com/questions/4371163/reading-xlsx-files-using-python. I uses modules from the standard library only.
def xlsx(fname):
import zipfile
from xml.etree.ElementTree import iterparse
z = zipfile.ZipFile(fname)
strings = [el.text for e, el in iterparse(z.open('xl/sharedStrings.xml')) if el.tag.endswith('}t')]
rows = []
row = {}
value = ''
for e, el in iterparse(z.open('xl/worksheets/sheet1.xml')):
if el.tag.endswith('}v'): # Example: <v>84</v>
value = el.text
if el.tag.endswith('}c'): # Example: <c r="A3" t="s"><v>84</v></c>
if el.attrib.get('t') == 's':
value = strings[int(value)]
letter = el.attrib['r'] # Example: AZ22
while letter[-1].isdigit():
letter = letter[:-1]
row[letter] = value
value = ''
if el.tag.endswith('}row'):
rows.append(row)
row = {}
return rows
Improvements added are fetching content by sheet name, using re to get the column and checking if sharedstrings are used.
def xlsx(fname,sheet):
import zipfile
from xml.etree.ElementTree import iterparse
import re
z = zipfile.ZipFile(fname)
if 'xl/sharedStrings.xml' in z.namelist():
# Get shared strings
strings = [element.text for event, element
in iterparse(z.open('xl/sharedStrings.xml'))
if element.tag.endswith('}t')]
sheetdict = { element.attrib['name']:element.attrib['sheetId'] for event,element in iterparse(z.open('xl/workbook.xml'))
if element.tag.endswith('}sheet') }
rows = []
row = {}
value = ''
if sheet in sheets:
sheetfile = 'xl/worksheets/sheet'+sheets[sheet]+'.xml'
#print(sheet,sheetfile)
for event, element in iterparse(z.open(sheetfile)):
# get value or index to shared strings
if element.tag.endswith('}v') or element.tag.endswith('}t'):
value = element.text
# If value is a shared string, use value as an index
if element.tag.endswith('}c'):
if element.attrib.get('t') == 's':
value = strings[int(value)]
# split the row/col information so that the row leter(s) can be separate
letter = re.sub('\d','',element.attrib['r'])
row[letter] = value
value = ''
if element.tag.endswith('}row'):
rows.append(row)
row = {}
return rows
You're very close. Use same type on both sides, and include ()
.
ArrayList<Class> myArray = new ArrayList<Class>();
Call:
((App)App.Current).ChangeScreen(new Map());
Create this method inside App.xaml.cs:
public void ChangeScreen(Page page)
{
MainPage = page;
}
I'd use the Continue
statement instead:
For Each I As Item In Items
If I = x Then
Continue For
End If
' Do something
Next
Note that this is slightly different to moving the iterator itself on - anything before the If
will be executed again. Usually this is what you want, but if not you'll have to use GetEnumerator()
and then MoveNext()
/Current
explicitly rather than using a For Each
loop.
Including the fb:app_id
tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.
The fb:admins
tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.
You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins
is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.
fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>
and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>