In my case, my problem was environmental. Meaning, I did something wrong in my bash session. After attempting nearly everything in this thread, I opened a new bash session and everything was back to normal.
I think the problem happened when you use rbenv. Try the below commands to fix it.
rbenv shell {rb_version}
rbenv global {rb_version}
or
rbenv local {rb_version}
I'll go into differences at the hardware level, on x86. This is mostly irrelevant unless you're writing a compiler or using assembly language. But it's nice to know.
Firstly, x86 has native support for the two's complement representation of signed numbers. You can use other representations but this would require more instructions and generally be a waste of processor time.
What do I mean by "native support"? Basically I mean that there are a set of instructions you use for unsigned numbers and another set that you use for signed numbers. Unsigned numbers can sit in the same registers as signed numbers, and indeed you can mix signed and unsigned instructions without worrying the processor. It's up to the compiler (or assembly programmer) to keep track of whether a number is signed or not, and use the appropriate instructions.
Firstly, two's complement numbers have the property that addition and subtraction is just the same as for unsigned numbers. It makes no difference whether the numbers are positive or negative. (So you just go ahead and ADD
and SUB
your numbers without a worry.)
The differences start to show when it comes to comparisons. x86 has a simple way of differentiating them: above/below indicates an unsigned comparison and greater/less than indicates a signed comparison. (E.g. JAE
means "Jump if above or equal" and is unsigned.)
There are also two sets of multiplication and division instructions to deal with signed and unsigned integers.
Lastly: if you want to check for, say, overflow, you would do it differently for signed and for unsigned numbers.
If you declare an empty object literal and then assign values later on, then you can consider those values optional (may or may not be there), so just type them as optional with a question mark:
type User = {
Username?: string;
Email?: string;
}
To add to the accepted answer iptables
solution, I had to run two more commands on the host to open it to the outside world.
HOST> iptables -t nat -A DOCKER -p tcp --dport 443 -j DNAT --to-destination 172.17.0.2:443
HOST> iptables -t nat -A POSTROUTING -j MASQUERADE -p tcp --source 172.17.0.2 --destination 172.17.0.2 --dport https
HOST> iptables -A DOCKER -j ACCEPT -p tcp --destination 172.17.0.2 --dport https
Note: I was opening port https (443), my docker internal IP was 172.17.0.2
Note 2: These rules and temporrary and will only last until the container is restarted
A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.
Check the success field for true or false
private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
JsonObject jsonObject = null;
URLConnection connection = null;
InputStream is = null;
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String url = "https://www.google.com/recaptcha/api/siteverify";
try {
String query = String.format("secret=%s&response=%s&remoteip=%s",
URLEncoder.encode(secret, charset),
URLEncoder.encode(response, charset),
URLEncoder.encode(remoteip, charset));
connection = new URL(url + "?" + query).openConnection();
is = connection.getInputStream();
JsonReader rdr = Json.createReader(is);
jsonObject = rdr.readObject();
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return jsonObject;
}
CREATE FUNCTION DBO.GET_AGE
(
@DATE AS DATETIME
)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @YEAR AS VARCHAR(50) = ''
DECLARE @MONTH AS VARCHAR(50) = ''
DECLARE @DAYS AS VARCHAR(50) = ''
DECLARE @RESULT AS VARCHAR(MAX) = ''
SET @YEAR = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) / 12 ))
SET @MONTH = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) % 12 ))
SET @DAYS = DATEDIFF(DD,DATEADD(MM,CONVERT(INT,CONVERT(INT,@YEAR)*12 + CONVERT(INT,@MONTH)),@DATE),GETDATE())
SET @RESULT = (RIGHT('00' + @YEAR, 2) + ' YEARS ' + RIGHT('00' + @MONTH, 2) + ' MONTHS ' + RIGHT('00' + @DAYS, 2) + ' DAYS')
RETURN @RESULT
END
SELECT DBO.GET_AGE('04/12/1986')
You can not use DATEDIFF
but you can use this (if columns are not date type):
SELECT
to_date('2008-08-05','YYYY-MM-DD')-to_date('2008-06-05','YYYY-MM-DD')
AS DiffDate from dual
require_once 'lib/Zend/Loader/StandardAutoloader.php';
$loader = new Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));
$loader->registerNamespace('Http\PhpEnvironment', 'lib/Zend/Http');
// Register with spl_autoload:
$loader->register();
$a = new Zend\Http\PhpEnvironment\Request();
print_r($a->getQuery()->get()); exit;
Since you don't state if the form can resize or not there is an easy way if you don't care about resizing (if you do care, go with Mitch Wheats solution):
Select the control -> Format (menu option) -> Center in Window -> Horizontally or Vertically
Add this before calling curl_exec($curl_handle)
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'GET');
One way to achieve it, is by map your welcome-file to your controller request path in the web.xml
file:
[web.xml]
<web-app ...
<!-- Index -->
<welcome-file-list>
<welcome-file>home</welcome-file>
</welcome-file-list>
</web-app>
[LoginController.java]
@Controller("loginController")
public class LoginController{
@RequestMapping("/home")
public String homepage2(ModelMap model, HttpServletRequest request, HttpServletResponse response){
System.out.println("blablabla2");
model.addAttribute("sigh", "lesigh");
return "index";
}
There's now an easy way to do this using dplyr
.
dplyr::pull(aframe, a2)
The term "forward declaration" in C++ is mostly only used for class declarations. See (the end of) this answer for why a "forward declaration" of a class really is just a simple class declaration with a fancy name.
In other words, the "forward" just adds ballast to the term, as any declaration can be seen as being forward in so far as it declares some identifier before it is used.
(As to what is a declaration as opposed to a definition, again see What is the difference between a definition and a declaration?)
protected override bool ProcessCmdKey(ref Message msg, Keys dataKey)
{
if (dataKey == Keys.Escape)
{
this.Close();
//this.Visible = false;
//Plus clear values from form, if Visible false.
}
return base.ProcessCmdKey(ref msg, dataKey);
}
The brackets can be used when column names are reserved words.
If you are programatically generating the SQL statement from a collection of column names you don't control, then you can avoid problems by always using the brackets.
Not so exact but simpler solution:
$limit = str_replace(array('G', 'M', 'K'), array('000000000', '000000', '000'), ini_get('memory_limit'));
if($limit < 500000000) ini_set('memory_limit', '500M');
You might want to run bash -v
to see what's being sourced.
I would do the following instead of playing with symlinks:
RUN echo "source /usr/local/bin/virtualenvwrapper.sh" >> /etc/bash.bashrc
Here is a short example of applying a function to each row of a matrix. (Here, the function applied normalizes every row to 1.)
Note: The result from the apply()
had to be transposed using t()
to get the same layout as the input matrix A
.
A <- matrix(c(
0, 1, 1, 2,
0, 0, 1, 3,
0, 0, 1, 3
), nrow = 3, byrow = TRUE)
t(apply(A, 1, function(x) x / sum(x) ))
Result:
[,1] [,2] [,3] [,4]
[1,] 0 0.25 0.25 0.50
[2,] 0 0.00 0.25 0.75
[3,] 0 0.00 0.25 0.75
You need to commit or destroy any unsaved changes before you switch branch.
Git won't let you switch branch if it means unsaved changes would be removed.
Never mind,
I am converting my audio files to mp2 by using the command:
ffmpeg -i input.wav -f mp2 output.mp3
This command works perfectly.
I know that this actually converts the files to mp2 format, but then the resulting file sizes are the same..
Based on Don W's solution, with fewer variables.
void process_mem_usage(double& vm_usage, double& resident_set)
{
vm_usage = 0.0;
resident_set = 0.0;
// the two fields we want
unsigned long vsize;
long rss;
{
std::string ignore;
std::ifstream ifs("/proc/self/stat", std::ios_base::in);
ifs >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore
>> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore
>> ignore >> ignore >> vsize >> rss;
}
long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
vm_usage = vsize / 1024.0;
resident_set = rss * page_size_kb;
}
GNU parallel
I was making a synthetic compilation benchmark and couldn't be bothered to write a Makefile, so I used:
sudo apt-get install parallel
ls | grep -E '\.c$' | parallel -t --will-cite "gcc -c -o '{.}.o' '{}'"
Explanation:
{.}
takes the input argument and removes its extension-t
prints out the commands being run to give us an idea of progress--will-cite
removes the request to cite the software if you publish results using it...parallel
is so convenient that I could even do a timestamp check myself:
ls | grep -E '\.c$' | parallel -t --will-cite "\
if ! [ -f '{.}.o' ] || [ '{}' -nt '{.}.o' ]; then
gcc -c -o '{.}.o' '{}'
fi
"
xargs -P
can also run jobs in parallel, but it is a bit less convenient to do the extension manipulation or run multiple commands with it: Calling multiple commands through xargs
Parallel linking was asked at: Can gcc use multiple cores when linking?
TODO: I think I read somewhere that compilation can be reduced to matrix multiplication, so maybe it is also possible to speed up single file compilation for large files. But I can't find a reference now.
Tested in Ubuntu 18.10.
Try this
export class Collection{
public more (): Observable<Response> {
if (this.hasMore()) {
return this.fetch();
}
else{
return this.returnEmpty();
}
}
public returnEmpty(): any {
let subscription = source.subscribe(
function (x) {
console.log('Next: %s', x);
},
function (err) {
console.log('Error: %s', err);
},
function () {
console.log('Completed');
});
}
}
let source = Observable.empty();
if my understanding of your initial JSON is correct, either of these solutions might help you loop through all ip ids & assign each one, a new object.
// initial JSON
var ips = {ipId1: {}, ipId2: {}};
// Solution1
Object.keys(ips).forEach(function(key) {
ips[key] = {name: 'value', anotherName: 'another value'};
});
// Solution 2
Object.keys(ips).forEach(function(key) {
Object.assign(ips[key],{name: 'value', anotherName: 'another value'});
});
To confirm:
console.log(JSON.stringify(ips, null, 2));
The above statement spits:
{
"ipId1": {
"name":"value",
"anotherName":"another value"
},
"ipId2": {
"name":"value",
"anotherName":"another value"
}
}
Depending on what you want you might be interested in the SPL Object Storage class.
http://php.net/manual/en/class.splobjectstorage.php
It lets you use objects as keys, has an interface to count, get the hash and other goodies.
$s = new SplObjectStorage;
$o1 = new stdClass;
$o2 = new stdClass;
$o2->foo = 'bar';
$s[$o1] = 'baz';
$s[$o2] = 'bingo';
echo $s[$o1]; // 'baz'
echo $s[$o2]; // 'bingo'
The man
page has very detailed descriptions of all of the various options (the status bar is highly configurable). Your best bet is to read through man tmux
and pay particular attention to those options that begin with status-
.
So, for example, status-bg red
would set the background colour of the bar.
The three components of the bar, the left and right sections and the window-list in the middle, can all be configured to suit your preferences. status-left
and status-right
, in addition to having their own variables (like #S
to list the session name) can also call custom scripts to display, for example, system information like load average or battery time.
The option to rename windows or panes based on what is currently running in them is automatic-rename
. You can set, or disable it globally with:
setw -g automatic-rename [on | off]
The most straightforward way to become comfortable with building your own status bar is to start with a vanilla one and then add changes incrementally, reloading the config as you go.1
You might also want to have a look around on github or bitbucket for other people's conf files to provide some inspiration. You can see mine here2.
1 You can automate this by including this line in your .tmux.conf
:
bind R source-file ~/.tmux.conf \; display-message "Config reloaded..."
You can then test your new functionality with Ctrlb,Shiftr. tmux
will print a helpful error message—including a line number of the offending snippet—if you misconfigure an option.
2 Note: I call a different status bar depending on whether I am in X or the console - I find this quite useful.
I think you simply have a double conversion of the character type there :D
It may be, because you opened an html document within a html document. So you have something that looks like this in the end
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test</title>.......
The use of mb_detect_encoding
therefore may lead you to other issues.
The Android Developer Guide has a section called Building Custom Components. Unfortunately, the discussion of XML attributes only covers declaring the control inside the layout file and not actually handling the values inside the class initialisation. The steps are as follows:
values\attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
<attr name="android:text"/>
<attr name="android:textColor"/>
<attr name="extraInformation" format="string" />
</declare-styleable>
</resources>
Notice the use of an unqualified name in the declare-styleable
tag. Non-standard android attributes like extraInformation
need to have their type declared. Tags declared in the superclass will be available in subclasses without having to be redeclared.
Since there are two constructors that use an AttributeSet
for initialisation, it is convenient to create a separate initialisation method for the constructors to call.
private void init(AttributeSet attrs) {
TypedArray a=getContext().obtainStyledAttributes(
attrs,
R.styleable.MyCustomView);
//Use a
Log.i("test",a.getString(
R.styleable.MyCustomView_android_text));
Log.i("test",""+a.getColor(
R.styleable.MyCustomView_android_textColor, Color.BLACK));
Log.i("test",a.getString(
R.styleable.MyCustomView_extraInformation));
//Don't forget this
a.recycle();
}
R.styleable.MyCustomView
is an autogenerated int[]
resource where each element is the ID of an attribute. Attributes are generated for each property in the XML by appending the attribute name to the element name. For example, R.styleable.MyCustomView_android_text
contains the android_text
attribute for MyCustomView
. Attributes can then be retrieved from the TypedArray
using various get
functions. If the attribute is not defined in the defined in the XML, then null
is returned. Except, of course, if the return type is a primitive, in which case the second argument is returned.
If you don't want to retrieve all of the attributes, it is possible to create this array manually.The ID for standard android attributes are included in android.R.attr
, while attributes for this project are in R.attr
.
int attrsWanted[]=new int[]{android.R.attr.text, R.attr.textColor};
Please note that you should not use anything in android.R.styleable
, as per this thread it may change in the future. It is still in the documentation as being to view all these constants in the one place is useful.
layout\main.xml
Include the namespace declaration xmlns:app="http://schemas.android.com/apk/res-auto"
in the top level xml element. Namespaces provide a method to avoid the conflicts that sometimes occur when different schemas use the same element names (see this article for more info). The URL is simply a manner of uniquely identifying schemas - nothing actually needs to be hosted at that URL. If this doesn't appear to be doing anything, it is because you don't actually need to add the namespace prefix unless you need to resolve a conflict.
<com.mycompany.projectname.MyCustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:text="Test text"
android:textColor="#FFFFFF"
app:extraInformation="My extra information"
/>
Reference the custom view using the fully qualified name.
If you want a complete example, look at the android label view sample.
TypedArray a=context.obtainStyledAttributes(attrs, R.styleable.LabelView);
CharSequences=a.getString(R.styleable.LabelView_text);
<declare-styleable name="LabelView">
<attr name="text"format="string"/>
<attr name="textColor"format="color"/>
<attr name="textSize"format="dimension"/>
</declare-styleable>
<com.example.android.apis.view.LabelView
android:background="@drawable/blue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
app:text="Blue" app:textSize="20dp"/>
This is contained in a LinearLayout
with a namespace attribute: xmlns:app="http://schemas.android.com/apk/res-auto"
The Best and easy way to load Image via Url is by this Code:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
dispatch_async(dispatch_get_main_queue(), ^{
imgView.image= [UIImage imageWithData:data];
});
});
Replace imgUrl
by your ImageURL
Replace imgView
by your UIImageView
.
It will load the Image in another Thread, so It will not slow down your App load.
// Shifting bytes is more efficient // You can use this one too
public static String getHexString (String s)
{
byte[] buf = s.getBytes();
StringBuffer sb = new StringBuffer();
for (byte b:buf)
{
sb.append(String.format("%x", b));
}
return sb.toString();
}
Select all text in the document and press Ctrl + E + D.
The getChars
string method does not return a value, instead it dumps its result into your buffer (or destination) array. The index parameter describes the start offset in your destination array.
Try this link for a more verbose description of the getChars
method.
I agree with the others on this, I think substring would be a better way to handle what you're trying to accomplish.
You did not supply the file handling code, but I assume you made the same mistake everyone does when first writing such a thing: the filewatcher event will be raised as soon as the file is created. However, it will take some time for the file to be finished. Take a file size of 1 GB for example. The file may be created by another program (Explorer.exe copying it from somewhere) but it will take minutes to finish that process. The event is raised at creation time and you need to wait for the file to be ready to be copied.
You can wait for a file to be ready by using this function in a loop.
sp_spaceused can get you information on the disk space used by a table, indexed view, or the whole database.
For example:
USE MyDatabase; GO
EXEC sp_spaceused N'User.ContactInfo'; GO
This reports the disk usage information for the ContactInfo table.
To use this for all tables at once:
USE MyDatabase; GO
sp_msforeachtable 'EXEC sp_spaceused [?]' GO
You can also get disk usage from within the right-click Standard Reports functionality of SQL Server. To get to this report, navigate from the server object in Object Explorer, move down to the Databases object, and then right-click any database. From the menu that appears, select Reports, then Standard Reports, and then "Disk Usage by Partition: [DatabaseName]".
In my case I didn't needed start adb.exe. I only started the BlueStacks before android studio.
After that when I press "Run" in android studio, bluestacks is detected as a new emulator.
Regards.
There's a KVC Object Operator that offers a more elegant solution uniquearray = [yourarray valueForKeyPath:@"@distinctUnionOfObjects.self"];
Here's an NSArray category.
In your PRIMARY KEY definition you've used (id(11))
, which defines a prefix key - i.e. the first 11 characters only should be used to create an index. Prefix keys are only valid for CHAR
, VARCHAR
, BINARY
and VARBINARY
types and your id
field is an int
, hence the error.
Use PRIMARY KEY (id)
instead and you should be fine.
MySQL reference here and read from paragraph 4.
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
Try $(this).load("/file_name.html");
. This method targets a local file.
You can also target remote files (on another domain) take a look at: http://en.wikipedia.org/wiki/Same_origin_policy
If you will later know the length of the array you can create the initial array like this:
String[] array;
And later when you know the length you can finish initializing it like this
array = new String[42];
There is actually a way to get this using an index search on the AdapterArray and all this can be done with reflection. I even went one step further as I had 10 Spinners and wanted to set them dynamically from my database and the database holds the value only not the text as the Spinner actually changes week to week so the value is my id number from the database.
// Get the JSON object from db that was saved, 10 spinner values already selected by user
JSONObject json = new JSONObject(string);
JSONArray jsonArray = json.getJSONArray("answer");
// get the current class that Spinner is called in
Class<? extends MyActivity> cls = this.getClass();
// loop through all 10 spinners and set the values with reflection
for (int j=1; j< 11; j++) {
JSONObject obj = jsonArray.getJSONObject(j-1);
String movieid = obj.getString("id");
// spinners variable names are s1,s2,s3...
Field field = cls.getDeclaredField("s"+ j);
// find the actual position of value in the list
int datapos = indexedExactSearch(Arrays.asList(Arrays.asList(this.data).toArray()), "value", movieid) ;
// find the position in the array adapter
int pos = this.adapter.getPosition(this.data[datapos]);
// the position in the array adapter
((Spinner)field.get(this)).setSelection(pos);
}
Here is the indexed search you can use on almost any list as long as the fields are on top level of object.
/**
* Searches for exact match of the specified class field (key) value within the specified list.
* This uses a sequential search through each object in the list until a match is found or end
* of the list reached. It may be necessary to convert a list of specific objects into generics,
* ie: LinkedList<Device> needs to be passed as a List<Object> or Object[ ] by using
* Arrays.asList(device.toArray( )).
*
* @param list - list of objects to search through
* @param key - the class field containing the value
* @param value - the value to search for
* @return index of the list object with an exact match (-1 if not found)
*/
public static <T> int indexedExactSearch(List<Object> list, String key, String value) {
int low = 0;
int high = list.size()-1;
int index = low;
String val = "";
while (index <= high) {
try {
//Field[] c = list.get(index).getClass().getDeclaredFields();
val = cast(list.get(index).getClass().getDeclaredField(key).get(list.get(index)) , "NONE");
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (val.equalsIgnoreCase(value))
return index; // key found
index = index + 1;
}
return -(low + 1); // key not found return -1
}
Cast method which can be create for all primitives here is one for string and int.
/**
* Base String cast, return the value or default
* @param object - generic Object
* @param defaultValue - default value to give if Object is null
* @return - returns type String
*/
public static String cast(Object object, String defaultValue) {
return (object!=null) ? object.toString() : defaultValue;
}
/**
* Base integer cast, return the value or default
* @param object - generic Object
* @param defaultValue - default value to give if Object is null
* @return - returns type integer
*/
public static int cast(Object object, int defaultValue) {
return castImpl(object, defaultValue).intValue();
}
/**
* Base cast, return either the value or the default
* @param object - generic Object
* @param defaultValue - default value to give if Object is null
* @return - returns type Object
*/
public static Object castImpl(Object object, Object defaultValue) {
return object!=null ? object : defaultValue;
}
The OVER clause when combined with PARTITION BY state that the preceding function call must be done analytically by evaluating the returned rows of the query. Think of it as an inline GROUP BY statement.
OVER (PARTITION BY SalesOrderID)
is stating that for SUM, AVG, etc... function, return the value OVER a subset of the returned records from the query, and PARTITION that subset BY the foreign key SalesOrderID.
So we will SUM every OrderQty record for EACH UNIQUE SalesOrderID, and that column name will be called 'Total'.
It is a MUCH more efficient means than using multiple inline views to find out the same information. You can put this query within an inline view and filter on Total then.
SELECT ...,
FROM (your query) inlineview
WHERE Total < 200
You can add this to onCreate
and it will hide the keyboard every time the Activity
starts.
You can also programmatically change the focus to another item.
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
You're looking for the OpenFileDialog
class.
For example:
Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
Using dialog As New OpenFileDialog
If dialog.ShowDialog() <> DialogResult.OK Then Return
File.Copy(dialog.FileName, newPath)
End Using
End Sub
Call JObject's ToString(Formatting.None)
method.
Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.
Documentation: Write JSON text with JToken.ToString
Using the sh module (pip install sh):
from sh import tail
# runs forever
for line in tail("-f", "/var/log/some_log_file.log", _iter=True):
print(line)
[update]
Since sh.tail with _iter
=True is a generator, you can:
import sh
tail = sh.tail("-f", "/var/log/some_log_file.log", _iter=True)
Then you can "getNewData" with:
new_data = tail.next()
Note that if the tail buffer is empty, it will block until there is more data (from your question it is not clear what you want to do in this case).
[update]
This works if you replace -f with -F, but in Python it would be locking. I'd be more interested in having a function I could call to get new data when I want it, if that's possible. – Eli
A container generator placing the tail call inside a while True loop and catching eventual I/O exceptions will have almost the same effect of -F.
def tail_F(some_file):
while True:
try:
for line in sh.tail("-f", some_file, _iter=True):
yield line
except sh.ErrorReturnCode_1:
yield None
If the file becomes inaccessible, the generator will return None. However it still blocks until there is new data if the file is accessible. It remains unclear for me what you want to do in this case.
Raymond Hettinger approach seems pretty good:
def tail_F(some_file):
first_call = True
while True:
try:
with open(some_file) as input:
if first_call:
input.seek(0, 2)
first_call = False
latest_data = input.read()
while True:
if '\n' not in latest_data:
latest_data += input.read()
if '\n' not in latest_data:
yield ''
if not os.path.isfile(some_file):
break
continue
latest_lines = latest_data.split('\n')
if latest_data[-1] != '\n':
latest_data = latest_lines[-1]
else:
latest_data = input.read()
for line in latest_lines[:-1]:
yield line + '\n'
except IOError:
yield ''
This generator will return '' if the file becomes inaccessible or if there is no new data.
[update]
The second to last answer circles around to the top of the file it seems whenever it runs out of data. – Eli
I think the second will output the last ten lines whenever the tail process ends, which with -f
is whenever there is an I/O error. The tail --follow --retry
behavior is not far from this for most cases I can think of in unix-like environments.
Perhaps if you update your question to explain what is your real goal (the reason why you want to mimic tail --retry), you will get a better answer.
The last answer does not actually follow the tail and merely reads what's available at run time. – Eli
Of course, tail will display the last 10 lines by default... You can position the file pointer at the end of the file using file.seek, I will left a proper implementation as an exercise to the reader.
IMHO the file.read() approach is far more elegant than a subprocess based solution.
Right click in the query pane, select Query Options...
and in the Execution->General section (the default when you first open it) there is an Execution time-out
setting.
If you are using the AUFS storage driver, you can use my docker-layer script to find any container's filesystem root (mnt) and readwrite layer :
# docker-layer musing_wiles
rw layer : /var/lib/docker/aufs/diff/c83338693ff190945b2374dea210974b7213bc0916163cc30e16f6ccf1e4b03f
mnt : /var/lib/docker/aufs/mnt/c83338693ff190945b2374dea210974b7213bc0916163cc30e16f6ccf1e4b03f
Edit 2018-03-28 :
docker-layer has been replaced by docker-backup
Annotate your field (or getter) with @Temporal(TemporalType.TIMESTAMP)
, like this:
public class MyEntity {
...
@Temporal(TemporalType.TIMESTAMP)
private java.util.Date myDate;
...
}
That should do the trick.
I had a similar issue, namely I was interested in generating unique numbers, which can be used as identifiers, but doesn't have to. I came up with the following solution. First to initialize the collection:
fun create(mongo: MongoTemplate) {
mongo.db.getCollection("sequence")
.insertOne(Document(mapOf("_id" to "globalCounter", "sequenceValue" to 0L)))
}
An then a service that return unique (and ascending) numbers:
@Service
class IdCounter(val mongoTemplate: MongoTemplate) {
companion object {
const val collection = "sequence"
}
private val idField = "_id"
private val idValue = "globalCounter"
private val sequence = "sequenceValue"
fun nextValue(): Long {
val filter = Document(mapOf(idField to idValue))
val update = Document("\$inc", Document(mapOf(sequence to 1)))
val updated: Document = mongoTemplate.db.getCollection(collection).findOneAndUpdate(filter, update)!!
return updated[sequence] as Long
}
}
I believe that id doesn't have the weaknesses related to concurrent environment that some of the other solutions may suffer from.
It's easy, if your mailx
command supports the -a
(append header) option:
$ mailx -a 'Content-Type: text/html' -s "my subject" [email protected] < email.html
If it doesn't, try using sendmail
:
# create a header file
$ cat mailheader
To: [email protected]
Subject: my subject
Content-Type: text/html
# send
$ cat mailheader email.html | sendmail -t
Try this :
$i = 0;
while($row = mysqli_fetch_array($result)) {
$posts['post_id'] = $row[$i]['post_id'];
$posts['post_title'] = $row[$i]['post_title'];
$posts['type'] = $row[$i]['type'];
$posts['author'] = $row[$i]['author'];
}
$i++;
}
print_r($posts);
I know that two threads can not enter in Synchronize block at the same time
Two thread cannot enter a synchronized block on the same object twice. This means that two threads can enter the same block on different objects. This confusion can lead to code like this.
private Integer i = 0;
synchronized(i) {
i++;
}
This will not behave as expected as it could be locking on a different object each time.
if this is true than How this atomic.incrementAndGet() works without Synchronize ?? and is thread safe ??
yes. It doesn't use locking to achieve thread safety.
If you want to know how they work in more detail, you can read the code for them.
And what is difference between internal reading and writing to Volatile Variable / Atomic Variable ??
Atomic class uses volatile fields. There is no difference in the field. The difference is the operations performed. The Atomic classes use CompareAndSwap or CAS operations.
i read in some article that thread has local copy of variables what is that ??
I can only assume that it referring to the fact that each CPU has its own cached view of memory which can be different from every other CPU. To ensure that your CPU has a consistent view of data, you need to use thread safety techniques.
This is only an issue when memory is shared at least one thread updates it.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
_x000D_
<input type="number" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"><input type="submit">
_x000D_
If someone still needs it (like I do).
The specified role_name must be a role that the current session user is a member of. https://www.postgresql.org/docs/10/sql-set-role.html
We need to make the current session user a member of the role:
create role myrole;
set role myrole;
grant myrole to myuser;
set role myrole;
produces:
Role ROLE created.
Error starting at line : 4 in command -
set role myrole
Error report -
ERROR: permission denied to set role "myrole"
Grant succeeded.
Role SET succeeded.
You use class media.FaceDetector in android to detect face for free.
This is an example of face detection: https://github.com/betri28/FaceDetectCamera
You can use this:
Dictionary<object,object> mydic = ((IEnumerable)obj).Cast<object>().ToList().ToDictionary(px => px.GetType().GetProperty("Key").GetValue(px), pv => pv.GetType().GetProperty("Value").GetValue(pv));
Just use negative margins, in the second div say:
<div style="margin-top: -25px;">
And make sure to set the z-index property to get the layering you want.
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
Although it's not safest, but you can change in the source code. navigate to Python/2.7/site-packages/django/conf/urls/static.py
Then edit like following:
if settings.DEBUG or (prefix and '://' in prefix):
So then if settings.debug==False
it won't effect on the code, also after running try python manage.py runserver --runserver
to run static files.
NOTE: Information should only be used for testing only
Update 19 March 2019
A new experience someone has just faced recently even though he/she did add a library module in app module, and include in Setting gradle as described below. One more thing worth trying is to make sure your app module and your library module have the same compileSdkVersion (which is in each its gradle)!
Please follow this link for more details.
Ref: Imported module in Android Studio can't find imported class
Original answer
Sometimes you use import module function, then the module does appear in Project mode but not in Android mode
So the thing works for me is to go to Setting gradle, add my module manually, and sync a gradle again:
I have a same problem with google/google-api-php-client v2.0.0-RC7 and after search for 1 hours, i solved this problem using json_encode like this:
if ($client->isAccessTokenExpired()) {
$newToken = json_decode(json_encode($client->getAccessToken()));
$client->refreshToken($newToken->refresh_token);
file_put_contents(storage_path('app/client_id.txt'), json_encode($client->getAccessToken()));
}
I came here searching solution for Ranorex Studio 9.0.1. There is no contains() there yet. Instead we can use regex like:
div[@class~'atag']
For questions regarding how to embed your viewController to a navigationController in the storyboard:
You can use
import re
s = re.search(r"\[.*?]", string)
if s:
print(s.group(0))
Having trouble wrapping my head around this.
Have a rewrite rule with four conditions.
The first three conditions A, B, C are to be AND which is then OR with D
RewriteCond A true
RewriteCond B false
RewriteCond C [OR] true
RewriteCond D true
RewriteRule ...
But that seems to be an expression of A and B and (C or D) = false (don't rewrite)
How can I get to the desired expression? (A and B and C) or D = true (rewrite)
Preferably without using the additional steps of setting environment variables.
HELP!!!
Also make sure you using the ssh github url and not the https
With multiple return and multi parameter
string ConnectionString = CommonFunctions.GetConnectionString();
using (IDbConnection conn = new SqlConnection(ConnectionString))
{
IEnumerable<dynamic> results = conn.Query(sql: "ProductSearch",
param: new { CategoryID = 1, SubCategoryID="", PageNumber=1 },
commandType: CommandType.StoredProcedure);. // single result
var reader = conn.QueryMultiple("ProductSearch",
param: new { CategoryID = 1, SubCategoryID = "", PageNumber = 1 },
commandType: CommandType.StoredProcedure); // multiple result
var userdetails = reader.Read<dynamic>().ToList(); // instead of dynamic, you can use your objects
var salarydetails = reader.Read<dynamic>().ToList();
}
public static string GetConnectionString()
{
// Put the name the Sqlconnection from WebConfig..
return ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
Here is a complete function:
public function get_number_of_days_in_month($month, $year) {
// Using first day of the month, it doesn't really matter
$date = $year."-".$month."-1";
return date("t", strtotime($date));
}
This would output following:
echo get_number_of_days_in_month(2,2014);
Output: 28
I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .
It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .
... and a lot of other examples as well ...
A really easy way is to simply call post()
on your layout. This will run your code the next step, after your view has already been created.
YOUR_LAYOUT.post( new Runnable() {
@Override
public void run() {
int width = YOUR_LAYOUT.getMeasuredWidth();
int height = YOUR_LAYOUT.getMeasuredHeight();
}
});
To provide one answer that will work for all Windows-users:
Add the following to your sbtconfig.txt (C:\Program Files (x86)\sbt\conf)
-Dhttp.proxyHost=XXXXXXX -Dhttp.proxyPort=YYYY -Dhttp.proxySet=true -Dhttps.proxyHost=XXXXXXX -Dhttps.proxyPort=YYYY -Dhttps.proxySet=true
Replace both XXXXXXX with your proxyHost, and both YYYY with your proxyPort.
If you get the error "Could not find or load main class" you need to set your JAVA_HOME:
set JAVA_HOME=C:\Progra~1\Java\jdkxxxxxx
When on 64-bit windows, use:
Progra~1 = 'Program Files'
Progra~2 = 'Program Files(x86)'
Something like this might help (taken from a working app).
#include <memory>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
struct thread_pool {
typedef std::unique_ptr<boost::asio::io_service::work> asio_worker;
thread_pool(int threads) :service(), service_worker(new asio_worker::element_type(service)) {
for (int i = 0; i < threads; ++i) {
auto worker = [this] { return service.run(); };
grp.add_thread(new boost::thread(worker));
}
}
template<class F>
void enqueue(F f) {
service.post(f);
}
~thread_pool() {
service_worker.reset();
grp.join_all();
service.stop();
}
private:
boost::asio::io_service service;
asio_worker service_worker;
boost::thread_group grp;
};
You can use it like this:
thread_pool pool(2);
pool.enqueue([] {
std::cout << "Hello from Task 1\n";
});
pool.enqueue([] {
std::cout << "Hello from Task 2\n";
});
Keep in mind that reinventing an efficient asynchronous queuing mechanism is not trivial.
Boost::asio::io_service is a very efficient implementation, or actually is a collection of platform-specific wrappers (e.g. it wraps I/O completion ports on Windows).
You can also use inline assembly like this:
int i;
__asm {
mov eax, 00000000000000000000000000000000b
mov i, eax
}
std::cout << i;
Okay, it might be somewhat overkill, but it works.
bool GetList (const std::string& src, std::vector<int>& res)
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
bool success = true;
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sepa(",");
tokenizer tokens(src, sepa);
for (tokenizer::iterator tok_iter = tokens.begin();
tok_iter != tokens.end(); ++tok_iter) {
try {
res.push_back(lexical_cast<int>(*tok_iter));
}
catch (bad_lexical_cast &) {
success = false;
}
}
return success;
}
There is a simple way using Linq GroupBy Method.
var duplicateValues = dt.AsEnumerable()
.GroupBy(row => row[0])
.Where(group => (group.Count() == 1 || group.Count() > 1))
.Select(g => g.Key);
foreach (var d in duplicateValues)
Console.WriteLine(d);
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
Mongoose is built untop of mongodb driver, the mongodb driver is more low level. Mongoose provides that easy abstraction to easily define a schema and query. But on the perfomance side Mongdb Driver is best.
you gave the following example in your question:
colnames(merger)[,1]<-"Date"
the problem is the comma: colnames() returns a vector, not a matrix, so the solution is:
colnames(merger)[1]<-"Date"
The AngularJS way of calling $http would look like:
$http({
url: "http://example.appspot.com/rest/app",
method: "POST",
data: {"foo":"bar"}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.data = response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.error = response.statusText;
});
or could be written even simpler using shortcut methods:
$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.then(successCallback, errorCallback);
There are number of things to notice:
success
and error
respectively (also please note parameters of each callback) - Deprecated in angular v1.5then
function instead. then
usage can be found here The above is just a quick example and some pointers, be sure to check AngularJS documentation for more: http://docs.angularjs.org/api/ng.$http
The more efficient (less obtrusive) way of doing this is through custom formatting.
Note that this does not actually change the value of the cell. It only displays the leading zeroes in the worksheet.
Try
set expandtab
for soft tabs.
To fix pre-existing tabs:
:%s/\t/ /g
I used two spaces since you already set your tabstop to 2 spaces.
Had essentially the same problem, solved in my case by adding:
<modules runAllManagedModulesForAllRequests="true" />
to the
<system.webServer>
</system.webServer>
section of web.config
I know this is pretty late but its to help anyone else that had to spend 6 hours trying to figure this out. (thats what I did):
This works flawlessly: (checks if any letter is in the input/checks if input is either integer or float)
a=(raw_input("Amount:"))
try:
int(a)
except ValueError:
try:
float(a)
except ValueError:
print "This is not a number"
a=0
if a==0:
a=0
else:
print a
#Do stuff
It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:
mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
| |
+------------+
1 row in set (0.00 sec)
mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
As per the official documentation of the jquery sortable UI: http://api.jqueryui.com/sortable/#method-toArray
In update event. use:
var sortedIDs = $( ".selector" ).sortable( "toArray" );
and if you alert or console this var (sortedIDs). You'll get your sequence. Please choose as the "Right Answer" if it is a right one.
User float:left
property in child div class
check for div structure in detail : http://www.dzone.com/links/r/div_table.html
You can use "group by" + "orderby". See LINQ 101 for details
var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = from x in list
group x by x into g
let count = g.Count()
orderby count descending
select new {Value = g.Key, Count = count};
foreach (var x in q)
{
Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}
In response to this post (now deleted):
If you have a list of some custom objects then you need to use custom comparer or group by specific property.
Also query can't display result. Show us complete code to get a better help.
Based on your latest update:
You have this line of code:
group xx by xx into g
Since xx is a custom object system doesn't know how to compare one item against another. As I already wrote, you need to guide compiler and provide some property that will be used in objects comparison or provide custom comparer. Here is an example:
Note that I use Foo.Name as a key - i.e. objects will be grouped based on value of Name property.
There is one catch - you treat 2 objects to be duplicate based on their names, but what about Id ? In my example I just take Id of the first object in a group. If your objects have different Ids it can be a problem.
//Using extension methods
var q = list.GroupBy(x => x.Name)
.Select(x => new {Count = x.Count(),
Name = x.Key,
ID = x.First().ID})
.OrderByDescending(x => x.Count);
//Using LINQ
var q = from x in list
group x by x.Name into g
let count = g.Count()
orderby count descending
select new {Name = g.Key, Count = count, ID = g.First().ID};
foreach (var x in q)
{
Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID);
}
AsyncTask
is designed to perform not more than few seconds operation to be done in background (not recommended for megabytes of file downloading from server or compute cpu intensive task such as file IO operations ). If you need to execute a long running operation, you have been strongly advised to use java native threads. Java gives you various thread related classes to do what you need. Use Handler
to update the UI Thread.
This worked for me in my application:
def get_celery_queue_active_jobs(queue_name):
connection = <CELERY_APP_INSTANCE>.connection()
try:
channel = connection.channel()
name, jobs, consumers = channel.queue_declare(queue=queue_name, passive=True)
active_jobs = []
def dump_message(message):
active_jobs.append(message.properties['application_headers']['task'])
channel.basic_consume(queue=queue_name, callback=dump_message)
for job in range(jobs):
connection.drain_events()
return active_jobs
finally:
connection.close()
active_jobs
will be a list of strings that correspond to tasks in the queue.
Don't forget to swap out CELERY_APP_INSTANCE with your own.
Thanks to @ashish for pointing me in the right direction with his answer here: https://stackoverflow.com/a/19465670/9843399
In my case I was doing show / hide elements of a form according to whether an input element was empty or not, so that when hiding the elements the element following the hidden ones was repositioned occupying its space it was necessary to do a float: left of the element of such an element. Even using a plugin as dependsOn it was necessary to use float.
You can't create arrays with a generic component type.
Create an array of an explicit type, like Object[]
, instead. You can then cast this to PCB[]
if you want, but I don't recommend it in most cases.
PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */
If you want type safety, use a collection like java.util.List<PCB>
instead of an array.
By the way, if list
is already a java.util.List
, you should use one of its toArray()
methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.
setTimeout( function ( ) { alert( "moo" ); }, 10000 ); //displays msg in 10 seconds
In addition to the above answers ; After executing the below command
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'
If you get an error as :
[ERROR] Column count of mysql.user is wrong. Expected 42, found 44. The table is probably corrupted
Then try in the cmd as admin; set the path to MySQL server bin folder in the cmd
set path=%PATH%;D:\xampp\mysql\bin;
and then run the command :
mysql_upgrade --force -uroot -p
This should update the server and the system tables.
Then you should be able to successfully run the below commands in a Query in the Workbench :
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'
then remember to execute the following command:
flush privileges;
After all these steps should be able to successfully connect to your MySQL database. Hope this helps...
Actually you can still have a Map
with the original keys after converting to array with Array.from
. That's possible by returning an array, where the first item is the key
, and the second is the transformed value
.
const originalMap = new Map([
["thing1", 1], ["thing2", 2], ["thing3", 3]
]);
const arrayMap = Array.from(originalMap, ([key, value]) => {
return [key, value + 1]; // return an array
});
const alteredMap = new Map(arrayMap);
console.log(originalMap); // Map { 'thing1' => 1, 'thing2' => 2, 'thing3' => 3 }
console.log(alteredMap); // Map { 'thing1' => 2, 'thing2' => 3, 'thing3' => 4 }
If you don't return that key as the first array item, you loose your Map
keys.
Update:
Guido van Rossum announced on the mailing list that as of Python 3.7 dict
s in all Python implementations must preserve insertion order.
This is possible with useState
or useReducer
, since useState
uses useReducer
internally:
const [, updateState] = React.useState();
const forceUpdate = React.useCallback(() => updateState({}), []);
forceUpdate
isn't intended to be used under normal circumstances, only in testing or other outstanding cases. This situation may be addressed in a more conventional way.
setCount
is an example of improperly used forceUpdate
, setState
is asynchronous for performance reasons and shouldn't be forced to be synchronous just because state updates weren't performed correctly. If a state relies on previously set state, this should be done with updater function,
If you need to set the state based on the previous state, read about the updater argument below.
<...>
Both state and props received by the updater function are guaranteed to be up-to-date. The output of the updater is shallowly merged with state.
setCount
may not be an illustrative example because its purpose is unclear but this is the case for updater function:
setCount(){
this.setState(({count}) => ({ count: count + 1 }));
this.setState(({count2}) => ({ count2: count + 1 }));
this.setState(({count}) => ({ count2: count + 1 }));
}
This is translated 1:1 to hooks, with the exception that functions that are used as callbacks should better be memoized:
const [state, setState] = useState({ count: 0, count2: 100 });
const setCount = useCallback(() => {
setState(({count}) => ({ count: count + 1 }));
setState(({count2}) => ({ count2: count + 1 }));
setState(({count}) => ({ count2: count + 1 }));
}, []);
This example is for Spring 4, but you can find the classpath scanner in earlier versions as well.
// create scanner and disable default filters (that is the 'false' argument)
final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
// add include filters which matches all the classes (or use your own)
provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));
// get matching classes defined in the package
final Set<BeanDefinition> classes = provider.findCandidateComponents("my.package.name");
// this is how you can load the class type from BeanDefinition instance
for (BeanDefinition bean: classes) {
Class<?> clazz = Class.forName(bean.getBeanClassName());
// ... do your magic with the class ...
}
Note: In version 14, the API is still marked as @Beta, so beware in production code.
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
for (final ClassPath.ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) {
if (info.getName().startsWith("my.package.")) {
final Class<?> clazz = info.load();
// do something with your clazz
}
}
foreach (var p in model.GetType().GetProperties())
{
var valueOfDisplay =
p.GetCustomAttributesData()
.Any(a => a.AttributeType.Name == "DisplayNameAttribute") ?
p.GetCustomAttribute<DisplayNameAttribute>().DisplayName :
p.Name;
}
In this example I used DisplayName instead of Author because it has a field named 'DisplayName' to be shown with a value.
JavaScript
var myObj = {
id: "c001",
name: "Hello Test"
}
Result(JSON)
{
"id": "c001",
"name": "Hello Test"
}
My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type.
You are sort of correct. You are allowed to initialize static const integrals in the class declaration but that is not a definition.
Interestingly, if I comment out the call to std::min, the code compiles and links just fine (even though test::N is also referenced on the previous line).
Any idea as to what's going on?
std::min takes its parameters by const reference. If it took them by value you'd not have this problem but since you need a reference you also need a definition.
Here's chapter/verse:
9.4.2/4 - If a static
data member is of const
integral or const
enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.
See Chu's answer for a possible workaround.
Here is one solution:
function factorial(number) {
total = 1
while (number > 0) {
total *= number
number = number - 1
}
return total
}
There is an issue discussed here which talks about using ca files, but it's a bit beyond my understanding and I'm unsure what to do about it.
This isn't too difficult once you know how! For Windows:
Using Chrome go to the root URL NPM is complaining about (so https://raw.githubusercontent.com in your case). Open up dev tools and go to Security-> View Certificate. Check Certification path and make sure your at the top level certificate, if not open that one. Now go to "Details" and export the cert with "Copy to File...".
You need to convert this from DER to PEM. There are several ways to do this, but the easiest way I found was an online tool which should be easy to find with relevant keywords.
Now if you open the key with your favorite text editor you should see
-----BEGIN CERTIFICATE-----
yourkey
-----END CERTIFICATE-----
This is the format you need. You can do this for as many keys as you need, and combine them all into one file. I had to do github and the npm registry keys in my case.
Now just edit your .npmrc to point to the file containing your keys like so
cafile=C:\workspace\rootCerts.crt
I have personally found this to perform significantly better behind our corporate proxy as opposed to the strict-ssl option. YMMV.
Using &
is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.
FOR /r %%X IN (*.txt) DO (
ECHO %%X
DEL %%X
)
Placement of (
and )
matters. The round brackets after DO
must be placed on the same line, otherwise the batch file will be incorrect.
See if /?|find /V ""
for details.
:g/xxxx/d
This will delete all the lines with pattern, and report how many deleted. Undo to get them back after.
You have to be careful while changing factors to numeric. Here is a line of code that would change a set of columns from factor to numeric. I am assuming here that the columns to be changed to numeric are 1, 3, 4 and 5 respectively. You could change it accordingly
cols = c(1, 3, 4, 5);
df[,cols] = apply(df[,cols], 2, function(x) as.numeric(as.character(x)));
You can check the android VLC it can stream and play video, if you want to indagate more, you can check their GIT to analyze what their do. Good luck!
Coming rather late, but seeing that this is one of the top results on Google search for the topic I'll share another way:
Use a one-liner with Googles utility class SphericalUtil
SphericalUtil.computeDistanceBetween(latLngFrom, latLngTo)
You will need the utility classes.
You can simply include them in your project using gradle:
implementation 'com.google.maps.android:android-maps-utils:0.5+'
A couple of changes mean that only an R
or r
will roll. Any other character will quit
import random
while True:
print('Your score so far is {}.'.format(myScore))
print("Would you like to roll or quit?")
ans = input("Roll...")
if ans.lower() == 'r':
R = np.random.randint(1, 8)
print("You rolled a {}.".format(R))
myScore = R + myScore
else:
print("Now I'll see if I can break your score...")
break
official Link of DB 2 JDBC Driver from IBM
In my case, I wanted to check out
a new branch
that has cut recently
but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network
so I copped the previous branch
that I already checked in
I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help
)
svn switch ^/branches/newBranchName
go check svn info
again you can see it is becoming the newBranchName go ahead and svn up
and this how I got the new branch easily, quickly with minimum data transmitting over the internet
hope sharing my case helps and speeds up your work
The bin/XXX.apk
file can be built automatically as soon as you save any source file:
Window/Preferences, Android/Build, uncheck "skip packaging and indexing..."
Add this one to your html if you only have access to the html:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
You can easily write the method to do that :
public static String toCamelCase(final String init) {
if (init == null)
return null;
final StringBuilder ret = new StringBuilder(init.length());
for (final String word : init.split(" ")) {
if (!word.isEmpty()) {
ret.append(Character.toUpperCase(word.charAt(0)));
ret.append(word.substring(1).toLowerCase());
}
if (!(ret.length() == init.length()))
ret.append(" ");
}
return ret.toString();
}
You will either have to specify a DEFAULT, or add the column with NULLs allowed, update all the values, and then change the column to NOT NULL.
ALTER TABLE <YourTable>
ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>
You can always use Unicode character, for me personally this is the most clear solution:
var space = "\u0020"
A character might appear multiple times in a string. For example in a string sentence
, position of e
is 1, 4, 7
(because indexing usually starts from zero). but what I find is both of the functions find()
and index()
returns first position of a character. So, this can be solved doing this:
def charposition(string, char):
pos = [] #list to store positions for each 'char' in 'string'
for n in range(len(string)):
if string[n] == char:
pos.append(n)
return pos
s = "sentence"
print(charposition(s, 'e'))
#Output: [1, 4, 7]
Use a normalised colour histogram. (Read the section on applications here), they are commonly used in image retrieval/matching systems and are a standard way of matching images that is very reliable, relatively fast and very easy to implement.
Essentially a colour histogram will capture the colour distribution of the image. This can then be compared with another image to see if the colour distributions match.
This type of matching is pretty resiliant to scaling (once the histogram is normalised), and rotation/shifting/movement etc.
Avoid pixel-by-pixel comparisons as if the image is rotated/shifted slightly it may lead to a large difference being reported.
Histograms would be straightforward to generate yourself (assuming you can get access to pixel values), but if you don't feel like it, the OpenCV library is a great resource for doing this kind of stuff. Here is a powerpoint presentation that shows you how to create a histogram using OpenCV.
If you are like me and you somehow have full file paths (I did some glob() pattern matching on required photos so I do pretty much end up with full file paths), and your storage setup is well linked (i.e. such that your paths have the string storage/app/public/
), then you can use my little dirty hack below :p)
public static function hackoutFileFromStorageFolder($fullfilePath) {
if (strpos($fullfilePath, 'storage/app/public/')) {
$fileParts = explode('storage/app/public/', $fullfilePath);
if( count($fileParts) > 1){
return $fileParts[1];
}
}
return '';
}
text= re.sub('[0-9\n]',' ',text)
install regex in python which is re then do the following code.
<style type="text/css">
div {
text-align: center;
}
.img1{
width: 150px;
height: 150px;
border-radius: 50%;
}
span{
display: block;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
<span class='dif'></span>
<br>
<button>ADD</button>
</div>
<script type="text/javascript">
$('button').click(function() {
$('.dif').html("<img/>");
})
...and don't forget "$region" for the code to work:
$address = "Salzburg";
$address = str_replace(" ", "+", $address);
$region = "Austria";
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=$region");
$json = json_decode($json);
$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
echo $lat."</br>".$long;
There are many ways to convert an int to ASCII (depending on your needs) but here is a way to convert each integer byte to an ASCII character:
private static String toASCII(int value) {
int length = 4;
StringBuilder builder = new StringBuilder(length);
for (int i = length - 1; i >= 0; i--) {
builder.append((char) ((value >> (8 * i)) & 0xFF));
}
return builder.toString();
}
For example, the ASCII text for "TEST" can be represented as the byte array:
byte[] test = new byte[] { (byte) 0x54, (byte) 0x45, (byte) 0x53, (byte) 0x54 };
Then you could do the following:
int value = ByteBuffer.wrap(test).getInt(); // 1413829460
System.out.println(toASCII(value)); // outputs "TEST"
...so this essentially converts the 4 bytes in a 32-bit integer to 4 separate ASCII characters (one character per byte).
From Hmisc::spss.get
:
all(floor(x) == x, na.rm = TRUE)
much safer option, IMHO, since it "bypasses" the machine precision issue. If you try is.integer(floor(1))
, you'll get FALSE
. BTW, your integer will not be saved as integer if it's bigger than .Machine$integer.max
value, which is, by default 2147483647, so either change the integer.max
value, or do the alternative checks...
Use git merge-base <commit> <commit>
.
This command finds best common ancestor(s) between two commits. And if the common ancestor is identical to the last commit of a "branch" ,then we can safely assume that that a "branch" has been already merged into the master.
Here are the steps
git merge-base <commit-hash-step1> <commit-hash-step2>
. More info on git merge-base https://git-scm.com/docs/git-merge-base.
in my.cnf file , please change the following
## Instead of skip-networking the default is now to listen only on ## localhost which is more compatible and is not less secure. ## bind-address = 127.0.0.1
While ASP.NET MVC will allow you to have two actions with the same name, .NET won't allow you to have two methods with the same signature - i.e. the same name and parameters.
You will need to name the methods differently use the ActionName attribute to tell ASP.NET MVC that they're actually the same action.
That said, if you're talking about a GET and a POST, this problem will likely go away, as the POST action will take more parameters than the GET and therefore be distinguishable.
So, you need either:
[HttpGet]
public ActionResult ActionName() {...}
[HttpPost, ActionName("ActionName")]
public ActionResult ActionNamePost() {...}
Or,
[HttpGet]
public ActionResult ActionName() {...}
[HttpPost]
public ActionResult ActionName(string aParameter) {...}
You can use ngHide (or ngShow) directive. It doesn't create child scope as ngIf does.
<div ng-hide="testa">
Choose which DI to inject stuff into Jersey:
Spring 4:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring4</artifactId>
</dependency>
Spring 3:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
HK2:
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
It's been a lot of times and there are lots of valid answers, but the following code block seems to work:
my_object = SqlAlchemyModel()
my_serializable_obj = my_object.__dict__
del my_serializable_obj["_sa_instance_state"]
print(jsonify(my_serializable_object))
I'm aware that this is not a perfect solution, nor as elegant as the others, however for those who want o quick fix, they might try this.
The Key Differences Between Classification and Clustering are: Classification is the process of classifying the data with the help of class labels. On the other hand, Clustering is similar to classification but there are no predefined class labels. Classification is geared with supervised learning. As against, clustering is also known as unsupervised learning. Training sample is provided in the classification method while in the case of clustering training data is not provided.
Hope this will help!
I uninstalled previous version. It worked for me.
you can try this:
adb install -r -d -f your_Apk_path
In js you can change zoom by
document.body.style.zoom="90%"
But it doesn't work in FF http://caniuse.com/#search=zoom
For ff you can try
-moz-transform: scale(0.9);
And check next topic How can I zoom an HTML element in Firefox and Opera?
In WebApi 2 you can add this to global.asax
protected void Application_PostAuthorizeRequest()
{
System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
Then you could access the session through:
HttpContext.Current.Session
Note that if you're not using the full jquery UI library, this can be triggered if you're missing Widget, Menu, Position, or Core. There might be different dependencies depending on your version of jQuery UI
Due to windows encoding issue for me
I experienced this "Could not open input file" error. Then I obtained the file using wget
from another linux system, and the error did not occur.
The error ws only occurring for me when the file transited through windows.
Comment out these two lines in php.ini
;extension=imagick.so
;extension="ixed.5.6.lin"
it should fix the issue.
The proper function is int fileno(FILE *stream)
. It can be found in <stdio.h>
, and is a POSIX standard but not standard C.
Wrap an ArrayAdapter
around your List<ScanResult>
. Override getView()
to populate your rows with the ScanResult
data. Here is a free excerpt from one of my books that covers how to create custom ArrayAdapters
like this.
a good site, with good explanations:
http://www.wpf-tutorial.com/basic-controls/the-textblock-control-inline-formatting/
here the author gives you good examples for what you are looking for! Overal the site is great for research material plus it covers a great deal of options you have in WPF
Edit
There are different methods to format the text. for a basic formatting (the easiest in my opinion):
<TextBlock Margin="10" TextWrapping="Wrap">
TextBlock with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> text.
</TextBlock>
Example 1 shows basic formatting with Bold Itallic and underscored text.
Following includes the SPAN method, with this you van highlight text:
<TextBlock Margin="10" TextWrapping="Wrap">
This <Span FontWeight="Bold">is</Span> a
<Span Background="Silver" Foreground="Maroon">TextBlock</Span>
with <Span TextDecorations="Underline">several</Span>
<Span FontStyle="Italic">Span</Span> elements,
<Span Foreground="Blue">
using a <Bold>variety</Bold> of <Italic>styles</Italic>
</Span>.
</TextBlock>
Example 2 shows the span function and the different possibilities with it.
For a detailed explanation check the site!
how about the one liner for creating a key value pair?
let result = { ["foo"]: "some value" };
and some iterator function like reduce
to dynamically convert an array to a dictionary
var options = [_x000D_
{ key: "foo", value: 1 },_x000D_
{ key: "bar", value: {id: 2, name: "two"} },_x000D_
{ key: "baz", value: {["active"]: true} },_x000D_
];_x000D_
_x000D_
var result = options.reduce((accumulator, current) => {_x000D_
accumulator[current.key] = current.value;_x000D_
return accumulator;_x000D_
}, {});_x000D_
_x000D_
console.log(result);
_x000D_
Another quick test for a string to have something in it but space.
if [[ -n "${str// /}" ]]; then
echo "It is not empty!"
fi
"-n" means non-zero length string.
Then the first two slashes mean match all of the following, in our case space(s). Then the third slash is followed with the replacement (empty) string and closed with "}". Note the difference from the usual regular expression syntax.
You can read more about string manipulation in bash shell scripting here.
You may translate canvas by half-pixel distance.
ctx.translate(0.5, 0.5);
Initially the canvas positioning point between the physical pixels.
OS: Windows 7
Steps which worked for me:
npm config get proxy
npm config get https-proxy
Comments: I executed this command to know my proxy settings
npm config rm proxy
npm config rm https-proxy
npm config set registry=http://registry.npmjs.org/
npm install
Structure in C can be declared and initialized like this:
typedef struct book
{
char title[10];
char author[10];
float price;
} book;
int main() {
book b1={"DS", "Ajay", 250.0};
printf("%s \t %s \t %f", b1.title, b1.author, b1.price);
return 0;
}
You can achieve that by using positioning.
Try
position: absolute;
to get the 100% height.
I'd use a regular expression:
function someFunction(site)
{
// if site has an end slash (like: www.example.com/),
// then remove it and return the site without the end slash
return site.replace(/\/$/, '') // Match a forward slash / at the end of the string ($)
}
You'll want to make sure that the variable site
is a string, though.
You can use a data trigger (with a view model) on the button to enable a wait cursor.
<Button x:Name="NextButton"
Content="Go"
Command="{Binding GoCommand }">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Cursor" Value="Arrow"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsWorking}" Value="True">
<Setter Property="Cursor" Value="Wait"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Here is the code from the view-model:
public class MainViewModel : ViewModelBase
{
// most code removed for this example
public MainViewModel()
{
GoCommand = new DelegateCommand<object>(OnGoCommand, CanGoCommand);
}
// flag used by data binding trigger
private bool _isWorking = false;
public bool IsWorking
{
get { return _isWorking; }
set
{
_isWorking = value;
OnPropertyChanged("IsWorking");
}
}
// button click event gets processed here
public ICommand GoCommand { get; private set; }
private void OnGoCommand(object obj)
{
if ( _selectedCustomer != null )
{
// wait cursor ON
IsWorking = true;
_ds = OrdersManager.LoadToDataSet(_selectedCustomer.ID);
OnPropertyChanged("GridData");
// wait cursor off
IsWorking = false;
}
}
}
When your program has more open descriptors than the open files ulimit (ulimit -a will list this), the kernel will refuse to open any more file descriptors. Make sure you don't have any file descriptor leaks - for example, by running it for a while, then stopping and seeing if any extra fds are still open when it's idle - and if it's still a problem, change the nofile ulimit for your user in /etc/security/limits.conf
You no longer have to convert the contents to binary before writing to the file in S3. The following example creates a new text file (called newfile.txt) in an S3 bucket with string contents:
import boto3
s3 = boto3.resource(
's3',
region_name='us-east-1',
aws_access_key_id=KEY_ID,
aws_secret_access_key=ACCESS_KEY
)
content="String content to write to a new S3 file"
s3.Object('my-bucket-name', 'newfile.txt').put(Body=content)
I'm using Portable Git on WinXP (works a treat!), and needed to resolve a conflict that came up in branching. Of all the gui's I checked, KDiff3 proved to be the most transparent to use.
But I found the instructions I needed to get it working in Windows in this blog post, instructions which differ slightly from the other approaches listed here. It basically amounted to adding these lines to my .gitconfig
file:
[merge]
tool = kdiff3
[mergetool "kdiff3"]
path = C:/YourPathToBinaryHere/KDiff3/kdiff3.exe
keepBackup = false
trustExitCode = false
Working nicely now!
The default behavior is:
If the parameter is a primitive type (int
, bool
, double
, ...), Web API tries to get the value from the URI of the HTTP request.
For complex types (your own object, for example: Person
), Web API tries to read the value from the body of the HTTP request.
So, if you have:
...then you don't have to add any attributes (neither [FromBody]
nor [FromUri]
).
But, if you have a primitive type in the body, then you have to add [FromBody]
in front of your primitive type parameter in your WebAPI controller method. (Because, by default, WebAPI is looking for primitive types in the URI of the HTTP request.)
Or, if you have a complex type in your URI, then you must add [FromUri]
. (Because, by default, WebAPI is looking for complex types in the body of the HTTP request by default.)
Primitive types:
public class UsersController : ApiController
{
// api/users
public HttpResponseMessage Post([FromBody]int id)
{
}
// api/users/id
public HttpResponseMessage Post(int id)
{
}
}
Complex types:
public class UsersController : ApiController
{
// api/users
public HttpResponseMessage Post(User user)
{
}
// api/users/user
public HttpResponseMessage Post([FromUri]User user)
{
}
}
This works as long as you send only one parameter in your HTTP request. When sending multiple, you need to create a custom model which has all your parameters like this:
public class MyModel
{
public string MyProperty { get; set; }
public string MyProperty2 { get; set; }
}
[Route("search")]
[HttpPost]
public async Task<dynamic> Search([FromBody] MyModel model)
{
// model.MyProperty;
// model.MyProperty2;
}
From Microsoft's documentation for parameter binding in ASP.NET Web API:
When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.
This should work:
public HttpResponseMessage Post([FromBody] string name) { ... }
This will not work:
// Caution: This won't work! public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.
If you want to replace multiple values in a data frame, looping through all columns might help.
Say you want to replace ""
and 100
:
na_codes <- c(100, "")
for (i in seq_along(df)) {
df[[i]][df[[i]] %in% na_codes] <- NA
}
If you want all packages in that repository, use ...
to signify that, like:
go get code.google.com/p/go.text/...
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
The live
function is registering a click event handler. It'll do so every time you click the object. So if you click it twice, you're assigning two click handlers to the object. You're also assigning a click handler here:
onclick="feedback('the message html')";
And then that click handler is assigning another click handler via live()
.
Really what I think you want to do is this:
function feedback(message)
{
$('#feedback').remove();
$('.answers').append('<div id="feedback">'+message+'</div>');
}
Ok, per your comment, try taking out the onclick
part of the <a>
element and instead, putting this in a document.ready()
handler.
$('#answer').live('click',function(){
$('#feedback').remove();
$('.answers').append('<div id="feedback">'+message+'</div>');
});
If you use brew to install maven, then the settings file should be in
/usr/local/Cellar/maven/<version>/libexec/conf
M refers to the first non-ambiguous character in "decimal". If you don't add it the number will be treated as a double.
D is double.
Here's how I did it...
public static ElementDefinitionImpl[] RemoveElementDefAt(
ElementDefinition[] oldList,
int removeIndex
)
{
ElementDefinitionImpl[] newElementDefList = new ElementDefinitionImpl[ oldList.Length - 1 ];
int offset = 0;
for ( int index = 0; index < oldList.Length; index++ )
{
ElementDefinitionImpl elementDef = oldList[ index ] as ElementDefinitionImpl;
if ( index == removeIndex )
{
// This is the one we want to remove, so we won't copy it. But
// every subsequent elementDef will by shifted down by one.
offset = -1;
}
else
{
newElementDefList[ index + offset ] = elementDef;
}
}
return newElementDefList;
}
ADB Connect to wifi with credentials :
You can use the following ADB command to connect to wifi and enter password as well :
adb wait-for-device shell am start -n com.android.settingstest/.wifi.WifiSettings -e WIFI 1 -e AccessPointName "enter_user_name" -e Password "enter_password"
This is a mistake:
m.check(side);
That code has to go inside a function. Your class definition can only contain declarations and functions.
Classes don't "run", they provide a blueprint for how to make an object.
The line Message m;
means that an Orderbook
will contain Message
called m
, if you later create an Orderbook
.
In case you're an extension developer who googled your way here trying to stop causing this error:
The issue isn't CORB (as another answer here states) as blocked CORs manifest as warnings like -
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://www.example.com/example.html with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.
The issue is most likely a mishandled async response to runtime.sendMessage. As MDN says:
To send an asynchronous response, there are two options:
- return true from the event listener. This keeps the sendResponse function valid after the listener returns, so you can call it later.
- return a Promise from the event listener, and resolve when you have the response (or reject it in case of an error).
When you send an async response but fail to use either of these mechanisms, the supplied sendResponse
argument to sendMessage
goes out of scope and the result is exactly as the error message says: your message port (the message-passing apparatus) is closed before the response was received.
Webextension-polyfill authors have already written about it in June 2018.
So bottom line, if you see your extension causing these errors - inspect closely all your onMessage listeners. Some of them probably need to start returning promises (marking them as async should be enough). [Thanks @vdegenne]
Use putty. Put install directory path in environment values (PATH), and restart your PC if required.
Open cmd (command prompt) and type
C:/> pscp "C:\Users/gsjha/Desktop/example.txt" user@host:/home/
It'll be copied to the system.
You should use JSON.parse
, take a look at https://www.w3schools.com/js/js_json_parse.asp
const obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}')
console.log(obj.name)
console.log(obj.age)
If your viewController is under UINavigationController.
Subclass UINavigationController and add
override var preferredStatusBarStyle: UIStatusBarStyle {
return topViewController?.preferredStatusBarStyle ?? .default
}
ViewController's preferredStatusBarStyle
will be called.
try:
doSomething()
except:
pass
or
try:
doSomething()
except Exception:
pass
The difference is that the first one will also catch KeyboardInterrupt
, SystemExit
and stuff like that, which are derived directly from exceptions.BaseException
, not exceptions.Exception
.
See documentation for details:
I am not writing anything same here. Just a changelog note from PHP manual.
Changelog for continue
Version Description
7.0.0 - continue outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR.
5.4.0 continue 0; is no longer valid. In previous versions it was interpreted the same as continue 1;.
5.4.0 Removed the ability to pass in variables (e.g., $num = 2; continue $num;) as the numerical argument.
Changelog for break
Version Description
7.0.0 break outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR.
5.4.0 break 0; is no longer valid. In previous versions it was interpreted the same as break 1;.
5.4.0 Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument.
public class DayFlipper extends ViewPager {
private Flipperadapter adapter;
public class FlipperAdapter extends PagerAdapter {
@Override
public int getCount() {
return DayFlipper.DAY_HISTORY;
}
@Override
public void startUpdate(View container) {
}
@Override
public Object instantiateItem(View container, int position) {
Log.d(TAG, "instantiateItem(): " + position);
Date d = DateHelper.getBot();
for (int i = 0; i < position; i++) {
d = DateHelper.getTomorrow(d);
}
d = DateHelper.normalize(d);
CubbiesView cv = new CubbiesView(mContext);
cv.setLifeDate(d);
((ViewPager) container).addView(cv, 0);
// add map
cv.setCubbieMap(mMap);
cv.initEntries(d);
adpter = FlipperAdapter.this;
return cv;
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((CubbiesView) object);
}
@Override
public void finishUpdate(View container) {
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((CubbiesView) object);
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
}
...
public void refresh() {
adapter().notifyDataSetChanged();
}
}
try this.
One way you could accomplish this (in a hackish way) is to create a wrapper class for the List
. Like this:
class ListWrapper {
List<String> myList;
// getters and setters
}
Then your controller method signature would look like this:
public String controllerMethod(ListWrapper wrapper) {
....
}
No need to use the @RequestParam
or @ModelAttribute
annotation if the collection name you pass in the request matches the collection field name of the wrapper class, in my example your request parameters should look like this:
myList[0] : 'myValue1'
myList[1] : 'myValue2'
myList[2] : 'myValue3'
otherParam : 'otherValue'
anotherParam : 'anotherValue'
This is the correct way to do it
In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild
and pointing ndkBuild
path argument at an Android.mk
or change ndkBuild
to cmake
and point the path argument at a CMakeLists.txt
build script.
android {
compileSdkVersion 19
buildToolsVersion "25.0.2"
defaultConfig {
minSdkVersion 19
targetSdkVersion 19
ndk {
abiFilters 'armeabi', 'armeabi-v7a', 'x86'
}
externalNativeBuild {
cmake {
cppFlags '-std=c++11'
arguments '-DANDROID_TOOLCHAIN=clang',
'-DANDROID_PLATFORM=android-19',
'-DANDROID_STL=gnustl_static',
'-DANDROID_ARM_NEON=TRUE',
'-DANDROID_CPP_FEATURES=exceptions rtti'
}
}
}
externalNativeBuild {
cmake {
path 'src/main/jni/CMakeLists.txt'
}
//ndkBuild {
// path 'src/main/jni/Android.mk'
//}
}
}
For much more detail check Google's page on adding native code.
After this is setup correctly you can ./gradlew installDebug
and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.
The distribute
package provides a Python 3-compatible version of setuptools
: http://pypi.python.org/pypi/distribute
Also, use pip
to install the modules. It automatically finds dependencies and installs them for you.
It works just fine for me with your package:
[~] pip --version
pip 1.2.1 from /usr/lib/python3.3/site-packages (python 3.3)
[~] sudo pip install ansicolors
Downloading/unpacking ansicolors
Downloading ansicolors-1.0.2.tar.gz
Running setup.py egg_info for package ansicolors
Installing collected packages: ansicolors
Running setup.py install for ansicolors
Successfully installed ansicolors
Cleaning up...
[~]
After I installed Visual Studio 2013 Update 2, Visual Studio notified me about a Windows Phone emulator update, which I installed (it was really a new component, not an update). It turned out this enabled Hyper-V, which broke HAXM.
The solution was to uninstall the emulator from Programs and Features and to turn off Hyper-V from Windows Features (search for "Windows Features" and click "Turn Windows features on or off").
I had a situation where I was passing a variable to a method and wasn't sure if it was going to be an interface or an object.
The goals were:
I achieved this with the following:
if(!typeof(T).IsClass)
{
// If your constructor needs arguments...
object[] args = new object[] { my_constructor_param };
return (T)Activator.CreateInstance(typeof(T), args, null);
}
else
return default(T);
Methods can only declare local variables. That is why the compiler reports an error when you try to declare it as public.
In the case of local variables you can not use any kind of accessor (public, protected or private).
You should also know what the static keyword means. In method checkYourself
, you use the Integer array locations
.
The static keyword distinct the elements that are accessible with object creation. Therefore they are not part of the object itself.
public class Test { //Capitalized name for classes are used in Java
private final init[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later.
public Test(int[] locations) {
this.locations = locations;//To access to class member, when method argument has the same name use `this` key word.
}
public boolean checkYourSelf(int value) { //This method is accessed only from a object.
for(int location : locations) {
if(location == value) {
return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method.
}
}
return false; //Method should be simple and perform one task. So you can get more flexibility.
}
public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it.
public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place.
Test test = new Test(Test.locations); //We declare variable test, and create new instance (object) of class Test.
String result;
if(test.checkYourSelf(2)) {//We moved outside the string
result = "Hurray";
} else {
result = "Try again"
}
System.out.println(result); //We have only one place where write is done. Easy to change in future.
}
}
You Can try This To Run Command Then cmd
Exits
Process.Start("cmd", "/c YourCode")
You Can try This To Run The Command And Let cmd
Wait For More Commands
Process.Start("cmd", "/k YourCode")
For folks who find this posting through the search engines, another possible cause of this problem is from importing the wrong package version of @Transient
. Make sure that you import javax.persistence.transient
and not some other package.
Almost all of the python files should live in their respective folders (C:\Python26
and C:\Python27
). Some installers (ActiveState) will also associate .py*
files and add the python path to %PATH%
with an install if you tick the "use this as the default installation" box.
Using setup
from distutils.core
instead of setuptools
in setup.py worked for me, too:
#from setuptools import setup
from distutils.core import setup
I love the answer from @Bert F but this is the way my brain sees it.
I have an X in my hand. If I want to write my X into a List, that List needs to be either a List of X or a List of things that my X can be upcast to as I write them in i.e. any superclass of X...
List<? super X>
If I get a List and I want to read an X out of that List, that better be a List of X or a List of things that can be upcast to X as I read them out, i.e. anything that extends X
List<? extends X>
Hope this helps.
Although it does not seem to be the case for your situation, sometimes a connection refused error can also indicate that there is an ip address conflict on your network. You can search for possible ip conflicts by running:
arp-scan -I eth0 -l | grep <ipaddress>
and
arping <ipaddress>
This AskUbuntu question has some more information also.
You can use cut with a delimiter like this:
with space delim:
cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv
with tab delim:
cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv
I gave you the version of cut in which you can extract a list of intervals...
Hope it helps!
The absolute easiest way to stream a file into browser using ASP.NET MVC is this:
public ActionResult DownloadFile() {
return File(@"c:\path\to\somefile.pdf", "application/pdf", "Your Filename.pdf");
}
This is easier than the method suggested by @azarc3 since you don't even need to read the bytes.
Credit goes to: http://prideparrot.com/blog/archive/2012/8/uploading_and_returning_files#how_to_return_a_file_as_response
** Edit **
Apparently my 'answer' is the same as the OP's question. But I am not facing the problem he is having. Probably this was an issue with older version of ASP.NET MVC?
Version 2.6 and above:
PyCharm (far left menu) -> Preferences... -> Editor (bottom left section) -> General -> Appearance -> Show line numbers checkbox
Version 2.5 and below:
Settings -> Editor -> General -> Appearance -> Show line numbers checkbox
I needed to replace white space in a string with spaces, but not duplicate spaces. e.g., I needed to convert something like the following:
"a b c\r\n d\t\t\t e"
to
"a b c d e"
I used the following method
private static string RemoveWhiteSpace(string value)
{
if (value == null) { return null; }
var sb = new StringBuilder();
var lastCharWs = false;
foreach (var c in value)
{
if (char.IsWhiteSpace(c))
{
if (lastCharWs) { continue; }
sb.Append(' ');
lastCharWs = true;
}
else
{
sb.Append(c);
lastCharWs = false;
}
}
return sb.ToString();
}
Used font-size:0
in parent TD
which has the image.
_CodeSigned
folderembedded.mobileprovision
file with the new provision profileExecute the below mentioned command:
/usr/bin/codesign -f -s "iPhone Distribution: Certificate Name" --resource-rules "Payload/Application.app/ResourceRules.plist" "Payload/Application.app"
Now zip the Payload folder again and change the .zip extension with .ipa
Hope this helpful.
For reference follow below mentioned link: http://www.modelmetrics.com/tomgersic/codesign-re-signing-an-ipa-between-apple-accounts/
Another reason why you should avoid converting the column to varchar(max) is because you cannot create an index on a varchar(max) column.
You can do that using animate
like in the following link:
http://blog.freelancer-id.com/index.php/2009/03/26/scroll-window-smoothly-in-jquery
If you want to do it using scrollTo
plugin, then take a look the following:
They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.
This code will let you have a variable number of rows (with a variable number of DIVs on each row) and it will make all of the DIVs on each row match the height of its tallest neighbour:
If we assumed all the DIVs, that are floating, are inside a container with the id "divContainer", then you could use the following:
$(document).ready(function() {
var currentTallest = 0;
var currentRowStart = 0;
var rowDivs = new Array();
$('div#divContainer div').each(function(index) {
if(currentRowStart != $(this).position().top) {
// we just came to a new row. Set all the heights on the completed row
for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);
// set the variables for the new row
rowDivs.length = 0; // empty the array
currentRowStart = $(this).position().top;
currentTallest = $(this).height();
rowDivs.push($(this));
} else {
// another div on the current row. Add it to the list and check if it's taller
rowDivs.push($(this));
currentTallest = (currentTallest < $(this).height()) ? ($(this).height()) : (currentTallest);
}
// do the last row
for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);
});
});
Better to find cells from gridview instead of static/fix index so it will not generate any problem whenever you will add/remove any columns on gridview.
ASPX:
<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField HeaderText="Date" DataField="CreatedDate" />
</Columns>
</asp:GridView>
CS:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
if (string.Compare(e.Row.Cells[i].Text, "Date", true) == 0)
{
e.Row.Cells[i].Text = "Created Date";
}
}
}
}
With jQuery :
jQuery("#btn").on("click",function(event){
event.preventDefault();
pay();
cls();
});
What you want to do is put the console into "raw" mode (line editing bypassed and no enter key required) as opposed to "cooked" mode (line editing with enter key required.) On UNIX systems, the 'stty' command can change modes.
Now, with respect to Java... see Non blocking console input in Python and Java. Excerpt:
If your program must be console based, you have to switch your terminal out of line mode into character mode, and remember to restore it before your program quits. There is no portable way to do this across operating systems.
One of the suggestions is to use JNI. Again, that's not very portable. Another suggestion at the end of the thread, and in common with the post above, is to look at using jCurses.
HTML
<div class="relative"><!--used as a container-->
<!-- add content here to to make some height and width
example:<img src="" alt=""> -->
<div class="absolute">
<div class="table">
<div class="table-cell">
Vertical contents goes here
</div>
</div>
</div>
</div>
CSS
.relative {
position: relative;
}
.absolute {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
}
.table {
display: table;
height: 100%;
width: 100%;
text-align: center;
color: #fff;
}
.table-cell {
display: table-cell;
vertical-align: middle;
}
jQuery is just a set of helpers/libraries written in Javascript. You can still use all Javascript features, so you can call whatever functions, also from inside jQuery callbacks. So both possibilities should be okay.
From the Differences Between DTDs and Schema section of the Converting a DTD into a Schema article:
The critical difference between DTDs and XML Schema is that XML Schema utilize an XML-based syntax, whereas DTDs have a unique syntax held over from SGML DTDs. Although DTDs are often criticized because of this need to learn a new syntax, the syntax itself is quite terse. The opposite is true for XML Schema, which are verbose, but also make use of tags and XML so that authors of XML should find the syntax of XML Schema less intimidating.
The goal of DTDs was to retain a level of compatibility with SGML for applications that might want to convert SGML DTDs into XML DTDs. However, in keeping with one of the goals of XML, "terseness in XML markup is of minimal importance," there is no real concern with keeping the syntax brief.
[...]
So what are some of the other differences which might be especially important when we are converting a DTD? Let's take a look.
Typing
The most significant difference between DTDs and XML Schema is the capability to create and use datatypes in Schema in conjunction with element and attribute declarations. In fact, it's such an important difference that one half of the XML Schema Recommendation is devoted to datatyping and XML Schema. We cover datatypes in detail in Part III of this book, "XML Schema Datatypes."
[...]
Occurrence Constraints
Another area where DTDs and Schema differ significantly is with occurrence constraints. If you recall from our previous examples in Chapter 2, "Schema Structure" (or your own work with DTDs), there are three symbols that you can use to limit the number of occurrences of an element: *, + and ?.
[...]
Enumerations
So, let's say we had a element, and we wanted to be able to define a size attribute for the shirt, which allowed users to choose a size: small, medium, or large. Our DTD would look like this:
<!ELEMENT item (shirt)> <!ELEMENT shirt (#PCDATA)> <!ATTLIST shirt size_value (small | medium | large)>
[...]
But what if we wanted
size
to be an element? We can't do that with a DTD. DTDs do not provide for enumerations in an element's text content. However, because of datatypes with Schema, when we declared the enumeration in the preceding example, we actually created asimpleType
calledsize_values
which we can now use with an element:<xs:element name="size" type="size_value">
[...]
Resolved the problem using Jackson library. Prints are called out of Main class and all POJO classes are created. Here is the code snippets.
MainClass.java
public class MainClass {
public static void main(String[] args) throws JsonParseException,
JsonMappingException, IOException {
String jsonStr = "{\r\n" + " \"id\": 2,\r\n" + " \"socket\": \"0c317829-69bf-
43d6-b598-7c0c550635bb\",\r\n"
+ " \"type\": \"getDashboard\",\r\n" + " \"data\": {\r\n"
+ " \"workstationUuid\": \"ddec1caa-a97f-4922-833f-
632da07ffc11\"\r\n" + " },\r\n"
+ " \"reply\": true\r\n" + "}";
ObjectMapper mapper = new ObjectMapper();
MyPojo details = mapper.readValue(jsonStr, MyPojo.class);
System.out.println("Value for getFirstName is: " + details.getId());
System.out.println("Value for getLastName is: " + details.getSocket());
System.out.println("Value for getChildren is: " +
details.getData().getWorkstationUuid());
System.out.println("Value for getChildren is: " + details.getReply());
}
MyPojo.java
public class MyPojo {
private String id;
private Data data;
private String reply;
private String socket;
private String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getReply() {
return reply;
}
public void setReply(String reply) {
this.reply = reply;
}
public String getSocket() {
return socket;
}
public void setSocket(String socket) {
this.socket = socket;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Data.java
public class Data {
private String workstationUuid;
public String getWorkstationUuid() {
return workstationUuid;
}
public void setWorkstationUuid(String workstationUuid) {
this.workstationUuid = workstationUuid;
}
}
RESULTS:
Value for getFirstName is: 2 Value for getLastName is: 0c317829-69bf-43d6-b598-7c0c550635bb Value for getChildren is: ddec1caa-a97f-4922-833f-632da07ffc11 Value for getChildren is: true
I'm was facing the same problem with exactly the same error log.
In my case onProgress()
of the AsyncTask adds the values to the adapter using mAdapter.add(newEntry)
. To avoid the UI becoming less responsive I set mAdapter.setNotifyOnChange(false)
and call mAdapter.notifyDataSetChanged()
4 times the second. Once per second the array is sorted.
This work well and looks very addictive, but unfortunately it is possible to crash it by touching the shown list items often enough.
But it seems I have found an acceptable workaround.
My guess it that even if you just work on the ui thread the adapter does not accept many changes to it's data without calling notifyDataSetChanged()
, because of this I created a queue that is storing all the new items until the mentioned 300ms are over. If this moment is reached I add all the stored items in one shot and call notifyDataSetChanged()
.
Until now I was not able to crash the list anymore.