You need to use parentheses: myList.insert([1, 2, 3])
. When you leave out the parentheses, python thinks you are trying to access myList.insert
at position 1, 2, 3
, because that's what brackets are used for when they are right next to a variable.
You have two objects both named bank_holiday
-- one a list and one a function. Disambiguate the two.
bank_holiday[month]
is raising an error because Python thinks bank_holiday
refers to the function (the last object bound to the name bank_holiday
), whereas you probably intend it to mean the list.
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))
for i,price in enumerate(PriceList):
PriceList[i] = PizzaChange + 3*int(i>=7)
list1 = ["name1", "info1", 10]
list2 = ["name2", "info2", 30]
list3 = ["name3", "info3", 50]
def printer(*lists):
for _list in lists:
for ele in _list:
print(ele, end = ", ")
print()
printer(list1, list2, list3)
in general put a __iter__
method in your class and iterate through the object attributes or put this mixin class in your class.
class IterMixin(object):
def __iter__(self):
for attr, value in self.__dict__.iteritems():
yield attr, value
Your class:
>>> class YourClass(IterMixin): pass
...
>>> yc = YourClass()
>>> yc.one = range(15)
>>> yc.two = 'test'
>>> dict(yc)
{'one': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 'two': 'test'}
The get_ddl procedure for a PACKAGE will return both spec AND body, so it will be better to change the query on the all_objects so the package bodies are not returned on the select.
So far I changed the query to this:
SELECT DBMS_METADATA.GET_DDL(REPLACE(object_type, ' ', '_'), object_name, owner)
FROM all_OBJECTS
WHERE (OWNER = 'OWNER1')
and object_type not like '%PARTITION'
and object_type not like '%BODY'
order by object_type, object_name;
Although other changes might be needed depending on the object types you are getting...
What is a
when you call Ancestors('A',a)
? If a['A']
is None, or if a['A'][0]
is None, you'd receive that exception.
lista = list.sort(lista)
This should be
lista.sort()
The .sort()
method is in-place, and returns None. If you want something not in-place, which returns a value, you could use
sorted_list = sorted(lista)
Aside #1: please don't call your lists list
. That clobbers the builtin list type.
Aside #2: I'm not sure what this line is meant to do:
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
is it simply
print "value 1a + value 2 = value 3a value 4"
? In other words, I don't know why you're calling str on things which are already str.
Aside #3: sometimes you use print("something")
(Python 3 syntax) and sometimes you use print "something"
(Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..
The exception TypeError: 'NoneType' object is not subscriptable
happens because the value of lista
is actually None
. You can reproduce TypeError
that you get in your code if you try this at the Python command line:
None[0]
The reason that lista
gets set to None is because the return value of list.sort()
is None
... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).
If you do not want to alter the original version you can use
other_list = sorted(lista)
Try this instead:
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumall = str(sumall) # add this line
sumln = (int(sumall[0])+int(sumall[1]))
print "Your lucky number is", sumln
sumall
is a number, and you can't access its digits using the subscript notation (sumall[0]
, sumall[1]
). For that to work, you'll need to transform it back to a string.
This error arises when you don't use brackets with pop
operation. Write the code in this manner.
listb.pop(0)
This is a valid python expression.
You need to convert age1 into int first, so it can do the minus. After that turn the result back to string for display:
name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
twentyone = str(21 - int(age1))
print "Hi, " + name1+ " you will be 21 in: " + twentyone + " years."
In Python 3, map
returns an iterable object of type map
, and not a subscriptible list, which would allow you to write map[i]
. To force a list result, write
payIntList = list(map(int,payList))
However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:
payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
print(pi)
Complete snippet would look like the following. It expands @mouad's answer to asserting on error's message (or generally str
representation of its args
), which may be useful.
from unittest import TestCase
class TestNoneTypeError(TestCase):
def setUp(self):
self.testListNone = None
def testListSlicing(self):
with self.assertRaises(TypeError) as ctx:
self.testListNone[:1]
self.assertEqual("'NoneType' object is not subscriptable", str(ctx.exception))
You have also this 2006 article which lists different options for FTP clients.
commons-net is good, but FTP-GO can give you some of the more advanced features you are looking for.
The meaning of subscript in computing is: "a symbol (notionally written as a subscript but in practice usually not) used in a program, alone or with others, to specify one of the elements of an array."
Now, in the simple example given by @user2194711 we can see that the appending element is not able to be a part of the list because of two reasons:-
1) We are not really calling the method append; because it needs ()
to call it.
2) The error is indicating that the function or method is not subscriptable; means they are not indexable like a list or sequence.
Now see this:-
>>> var = "myString"
>>> def foo(): return 0
...
>>> var[3]
't'
>>> foo[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'function' object is not subscriptable
That means there are no subscripts or say elements in function
like they occur in sequences; and we cannot access them like we do, with the help of []
.
Also; as mipadi said in his answer; It basically means that the object implements the __getitem__()
method. (if it is subscriptable).
Thus the error produced:
arr.append["HI"]
TypeError: 'builtin_function_or_method' object is not subscriptable
Seeing from your G++ version, you need to update it badly. C++11 has only been available since G++ 4.3. The most recent version is 4.7.
In versions pre-G++ 4.7, you'll have to use -std=c++0x
, for more recent versions you can use -std=c++11
.
You aren't assigning the result of the replace method back to your variable. When you call replace, it returns a new string without modifying the old one.
For example, load this into your favorite browser:
<html><head></head><body>
<script type="text/javascript">
var str1 = "a,d,k";
str1.replace(/\,/g,"");
var str2 = str1.replace(/\,/g,"");
alert (str1);
alert (str2);
</script>
</body></html>
In this case, str1
will still be "a,d,k"
and str2
will be "adk"
.
If you want to change str1
, you should be doing:
var str1 = "a,d,k";
str1 = str1.replace (/,/g, "");
It will kill not only all plot windows, but all processes that are called python3, except the current script you run. It works for python3. So, if you are running any other python3 script it will be terminated. As I only run one script at once, it does the job for me.
import os
import subprocess
subprocess.call(["bash","-c",'pyIDs=($(pgrep python3));for x in "${pyIDs[@]}"; do if [ "$x" -ne '+str(os.getpid())+' ];then kill -9 "$x"; fi done'])
Here is an example of custom combobox in android:
package myWidgets;
import android.content.Context;
import android.database.Cursor;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
public class ComboBox extends LinearLayout {
private AutoCompleteTextView _text;
private ImageButton _button;
public ComboBox(Context context) {
super(context);
this.createChildControls(context);
}
public ComboBox(Context context, AttributeSet attrs) {
super(context, attrs);
this.createChildControls(context);
}
private void createChildControls(Context context) {
this.setOrientation(HORIZONTAL);
this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
_text = new AutoCompleteTextView(context);
_text.setSingleLine();
_text.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_NORMAL
| InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
| InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE
| InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
_text.setRawInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
this.addView(_text, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1));
_button = new ImageButton(context);
_button.setImageResource(android.R.drawable.arrow_down_float);
_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
_text.showDropDown();
}
});
this.addView(_button, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
}
/**
* Sets the source for DDLB suggestions.
* Cursor MUST be managed by supplier!!
* @param source Source of suggestions.
* @param column Which column from source to show.
*/
public void setSuggestionSource(Cursor source, String column) {
String[] from = new String[] { column };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this.getContext(),
android.R.layout.simple_dropdown_item_1line, source, from, to);
// this is to ensure that when suggestion is selected
// it provides the value to the textbox
cursorAdapter.setStringConversionColumn(source.getColumnIndex(column));
_text.setAdapter(cursorAdapter);
}
/**
* Gets the text in the combo box.
*
* @return Text.
*/
public String getText() {
return _text.getText().toString();
}
/**
* Sets the text in combo box.
*/
public void setText(String text) {
_text.setText(text);
}
}
Hope it helps!!
JSON.stringify(data).length return string length not Object length, you can use Object.keys.
<% for(var i=0; i < Object.keys(data).length ; i++) {%>
Auto-incrementing the index in a loop:
myArr[(len(myArr)+1)]={"key":"val"}
- Another Update -
Since Twitter Bootstrap version 2.0 - which saw the removal of the .container-fluid
class - it has not been possible to implement a two column fixed-fluid layout using just the bootstrap classes - however I have updated my answer to include some small CSS changes that can be made in your own CSS code that will make this possible
It is possible to implement a fixed-fluid structure using the CSS found below and slightly modified HTML code taken from the Twitter Bootstrap Scaffolding : layouts documentation page:
<div class="container-fluid fill">
<div class="row-fluid">
<div class="fixed"> <!-- we want this div to be fixed width -->
...
</div>
<div class="hero-unit filler"> <!-- we have removed spanX class -->
...
</div>
</div>
</div>
/* CSS for fixed-fluid layout */
.fixed {
width: 150px; /* the fixed width required */
float: left;
}
.fixed + div {
margin-left: 150px; /* must match the fixed width in the .fixed class */
overflow: hidden;
}
/* CSS to ensure sidebar and content are same height (optional) */
html, body {
height: 100%;
}
.fill {
min-height: 100%;
position: relative;
}
.filler:after{
background-color:inherit;
bottom: 0;
content: "";
height: auto;
min-height: 100%;
left: 0;
margin:inherit;
right: 0;
position: absolute;
top: 0;
width: inherit;
z-index: -1;
}
I have kept the answer below - even though the edit to support 2.0 made it a fluid-fluid solution - as it explains the concepts behind making the sidebar and content the same height (a significant part of the askers question as identified in the comments)
Update As pointed out by @JasonCapriotti in the comments, the original answer to this question (created for v1.0) did not work in Bootstrap 2.0. For this reason, I have updated the answer to support Bootstrap 2.0
To ensure that the main content fills at least 100% of the screen height, we need to set the height of the html
and body
to 100% and create a new css class called .fill
which has a minimum-height of 100%:
html, body {
height: 100%;
}
.fill {
min-height: 100%;
}
We can then add the .fill
class to any element that we need to take up 100% of the sceen height. In this case we add it to the first div:
<div class="container-fluid fill">
...
</div>
To ensure that the Sidebar and the Content columns have the same height is very difficult and unnecessary. Instead we can use the ::after
pseudo selector to add a filler
element that will give the illusion that the two columns have the same height:
.filler::after {
background-color: inherit;
bottom: 0;
content: "";
right: 0;
position: absolute;
top: 0;
width: inherit;
z-index: -1;
}
To make sure that the .filler
element is positioned relatively to the .fill
element we need to add position: relative
to .fill
:
.fill {
min-height: 100%;
position: relative;
}
And finally add the .filler
style to the HTML:
HTML
<div class="container-fluid fill">
<div class="row-fluid">
<div class="span3">
...
</div>
<div class="span9 hero-unit filler">
...
</div>
</div>
</div>
Notes
right: 0
to left: 0
.If you use MVC, tables, it works like this:
<td>@(((DateTime)detalle.fec).ToString("dd'/'MM'/'yyyy"))</td>
The else-clause is executed when the while-condition evaluates to false.
From the documentation:
The while statement is used for repeated execution as long as an expression is true:
while_stmt ::= "while" expression ":" suite ["else" ":" suite]
This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the
else
clause, if present, is executed and the loop terminates.A
break
statement executed in the first suite terminates the loop without executing theelse
clause’s suite. Acontinue
statement executed in the first suite skips the rest of the suite and goes back to testing the expression.
Your DOS command 2> nul
Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.
gcc will typically use logical shifts on unsigned variables and for left-shifts on signed variables. The arithmetic right shift is the truly important one because it will sign extend the variable.
gcc will will use this when applicable, as other compilers are likely to do.
The first 2 examples act very differently if you are REPLACING them by something. If you match on this:
str = str.replace(/^(7|8|9)/ig,'');
you would replace 7 or 8 or 9 by the empty string.
If you match on this
str = str.replace(/^[7|8|9]/ig,'');
you will replace 7
or 8
or 9
OR THE VERTICAL BAR!!!! by the empty string.
I just found this out the hard way.
For those who still don't get the accepted solution :
Add
import React from 'react'
import ReactDOM from 'react-dom'
at the top of the file.
As a general rule, pop up blockers target windows that launch without user interaction. Usually a click event can open a window without it being blocked. (unless it's a really bad popup blocker)
Try launching after a click event
If you are using angular5 and above, please include the below method in your ts file.
async delay(ms: number) {
await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}
then call this delay() method wherever you want.
e.g:
validateInputValues() {
if (null == this.id|| this.id== "") {
this.messageService.add(
{severity: 'error', summary: 'ID is Required.'});
this.delay(3000).then(any => {
this.messageService.clear();
});
}
}
This will disappear message growl after 3 seconds.
Another approach (especially useful if you need to make a decision to exclude a field at runtime) is to register a TypeAdapter with your gson instance. Example below:
Gson gson = new GsonBuilder()
.registerTypeAdapter(BloodPressurePost.class, new BloodPressurePostSerializer())
In the case below, the server would expect one of two values but since they were both ints then gson would serialize them both. My goal was to omit any value that is zero (or less) from the json that is posted to the server.
public class BloodPressurePostSerializer implements JsonSerializer<BloodPressurePost> {
@Override
public JsonElement serialize(BloodPressurePost src, Type typeOfSrc, JsonSerializationContext context) {
final JsonObject jsonObject = new JsonObject();
if (src.systolic > 0) {
jsonObject.addProperty("systolic", src.systolic);
}
if (src.diastolic > 0) {
jsonObject.addProperty("diastolic", src.diastolic);
}
jsonObject.addProperty("units", src.units);
return jsonObject;
}
}
You must have imported multiple stylesheets. try to remove one and try again
Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit
<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
{{$index}} - {{day.iso}} - {{day.name}}
Temperature: {{f.temperature}}<br>
Humidity: {{f.humidity}}<br>
...
</div>
Example: http://jsfiddle.net/coma/UV4qF/
It is necessary to take into consideration, that Regex IsMatch gives true with XYZ, when checking match with Y*. To avoid it, I use "^" anchor
isMatch(str1, "^" + str2.Replace("*", ".*?"));
So, full code to solve your problem is
bool isMatchStr(string str1, string str2)
{
string s1 = str1.Replace("*", ".*?");
string s2 = str2.Replace("*", ".*?");
bool r1 = Regex.IsMatch(s1, "^" + s2);
bool r2 = Regex.IsMatch(s2, "^" + s1);
return r1 || r2;
}
Fixed
I just placed it in a different folder and it worked.
Classes in the default package cannot be imported by classes in packages. This is why you should not use the default package.
$myvar = if ($env:variable) { $env:variable } else { "default_value" }
First, in Python, if your code is CPU-bound, multithreading won't help, because only one thread can hold the Global Interpreter Lock, and therefore run Python code, at a time. So, you need to use processes, not threads.
This is not true if your operation "takes forever to return" because it's IO-bound—that is, waiting on the network or disk copies or the like. I'll come back to that later.
Next, the way to process 5 or 10 or 100 items at once is to create a pool of 5 or 10 or 100 workers, and put the items into a queue that the workers service. Fortunately, the stdlib multiprocessing
and concurrent.futures
libraries both wraps up most of the details for you.
The former is more powerful and flexible for traditional programming; the latter is simpler if you need to compose future-waiting; for trivial cases, it really doesn't matter which you choose. (In this case, the most obvious implementation with each takes 3 lines with futures
, 4 lines with multiprocessing
.)
If you're using 2.6-2.7 or 3.0-3.1, futures
isn't built in, but you can install it from PyPI (pip install futures
).
Finally, it's usually a lot simpler to parallelize things if you can turn the entire loop iteration into a function call (something you could, e.g., pass to map
), so let's do that first:
def try_my_operation(item):
try:
api.my_operation(item)
except:
print('error with item')
Putting it all together:
executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_my_operation, item) for item in items]
concurrent.futures.wait(futures)
If you have lots of relatively small jobs, the overhead of multiprocessing might swamp the gains. The way to solve that is to batch up the work into larger jobs. For example (using grouper
from the itertools
recipes, which you can copy and paste into your code, or get from the more-itertools
project on PyPI):
def try_multiple_operations(items):
for item in items:
try:
api.my_operation(item)
except:
print('error with item')
executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_multiple_operations, group)
for group in grouper(5, items)]
concurrent.futures.wait(futures)
Finally, what if your code is IO bound? Then threads are just as good as processes, and with less overhead (and fewer limitations, but those limitations usually won't affect you in cases like this). Sometimes that "less overhead" is enough to mean you don't need batching with threads, but you do with processes, which is a nice win.
So, how do you use threads instead of processes? Just change ProcessPoolExecutor
to ThreadPoolExecutor
.
If you're not sure whether your code is CPU-bound or IO-bound, just try it both ways.
Can I do this for multiple functions in my python script? For example, if I had another for loop elsewhere in the code that I wanted to parallelize. Is it possible to do two multi threaded functions in the same script?
Yes. In fact, there are two different ways to do it.
First, you can share the same (thread or process) executor and use it from multiple places with no problem. The whole point of tasks and futures is that they're self-contained; you don't care where they run, just that you queue them up and eventually get the answer back.
Alternatively, you can have two executors in the same program with no problem. This has a performance cost—if you're using both executors at the same time, you'll end up trying to run (for example) 16 busy threads on 8 cores, which means there's going to be some context switching. But sometimes it's worth doing because, say, the two executors are rarely busy at the same time, and it makes your code a lot simpler. Or maybe one executor is running very large tasks that can take a while to complete, and the other is running very small tasks that need to complete as quickly as possible, because responsiveness is more important than throughput for part of your program.
If you don't know which is appropriate for your program, usually it's the first.
Yes, __attribute__((packed))
is potentially unsafe on some systems. The symptom probably won't show up on an x86, which just makes the problem more insidious; testing on x86 systems won't reveal the problem. (On the x86, misaligned accesses are handled in hardware; if you dereference an int*
pointer that points to an odd address, it will be a little slower than if it were properly aligned, but you'll get the correct result.)
On some other systems, such as SPARC, attempting to access a misaligned int
object causes a bus error, crashing the program.
There have also been systems where a misaligned access quietly ignores the low-order bits of the address, causing it to access the wrong chunk of memory.
Consider the following program:
#include <stdio.h>
#include <stddef.h>
int main(void)
{
struct foo {
char c;
int x;
} __attribute__((packed));
struct foo arr[2] = { { 'a', 10 }, {'b', 20 } };
int *p0 = &arr[0].x;
int *p1 = &arr[1].x;
printf("sizeof(struct foo) = %d\n", (int)sizeof(struct foo));
printf("offsetof(struct foo, c) = %d\n", (int)offsetof(struct foo, c));
printf("offsetof(struct foo, x) = %d\n", (int)offsetof(struct foo, x));
printf("arr[0].x = %d\n", arr[0].x);
printf("arr[1].x = %d\n", arr[1].x);
printf("p0 = %p\n", (void*)p0);
printf("p1 = %p\n", (void*)p1);
printf("*p0 = %d\n", *p0);
printf("*p1 = %d\n", *p1);
return 0;
}
On x86 Ubuntu with gcc 4.5.2, it produces the following output:
sizeof(struct foo) = 5
offsetof(struct foo, c) = 0
offsetof(struct foo, x) = 1
arr[0].x = 10
arr[1].x = 20
p0 = 0xbffc104f
p1 = 0xbffc1054
*p0 = 10
*p1 = 20
On SPARC Solaris 9 with gcc 4.5.1, it produces the following:
sizeof(struct foo) = 5
offsetof(struct foo, c) = 0
offsetof(struct foo, x) = 1
arr[0].x = 10
arr[1].x = 20
p0 = ffbff317
p1 = ffbff31c
Bus error
In both cases, the program is compiled with no extra options, just gcc packed.c -o packed
.
(A program that uses a single struct rather than array doesn't reliably exhibit the problem, since the compiler can allocate the struct on an odd address so the x
member is properly aligned. With an array of two struct foo
objects, at least one or the other will have a misaligned x
member.)
(In this case, p0
points to a misaligned address, because it points to a packed int
member following a char
member. p1
happens to be correctly aligned, since it points to the same member in the second element of the array, so there are two char
objects preceding it -- and on SPARC Solaris the array arr
appears to be allocated at an address that is even, but not a multiple of 4.)
When referring to the member x
of a struct foo
by name, the compiler knows that x
is potentially misaligned, and will generate additional code to access it correctly.
Once the address of arr[0].x
or arr[1].x
has been stored in a pointer object, neither the compiler nor the running program knows that it points to a misaligned int
object. It just assumes that it's properly aligned, resulting (on some systems) in a bus error or similar other failure.
Fixing this in gcc would, I believe, be impractical. A general solution would require, for each attempt to dereference a pointer to any type with non-trivial alignment requirements either (a) proving at compile time that the pointer doesn't point to a misaligned member of a packed struct, or (b) generating bulkier and slower code that can handle either aligned or misaligned objects.
I've submitted a gcc bug report. As I said, I don't believe it's practical to fix it, but the documentation should mention it (it currently doesn't).
UPDATE: As of 2018-12-20, this bug is marked as FIXED. The patch will appear in gcc 9 with the addition of a new -Waddress-of-packed-member
option, enabled by default.
When address of packed member of struct or union is taken, it may result in an unaligned pointer value. This patch adds -Waddress-of-packed-member to check alignment at pointer assignment and warn unaligned address as well as unaligned pointer
I've just built that version of gcc from source. For the above program, it produces these diagnostics:
c.c: In function ‘main’:
c.c:10:15: warning: taking address of packed member of ‘struct foo’ may result in an unaligned pointer value [-Waddress-of-packed-member]
10 | int *p0 = &arr[0].x;
| ^~~~~~~~~
c.c:11:15: warning: taking address of packed member of ‘struct foo’ may result in an unaligned pointer value [-Waddress-of-packed-member]
11 | int *p1 = &arr[1].x;
| ^~~~~~~~~
Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically:
The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.
When the user changes the UI, Angular will automatically update the associated elements on the page.
ng-class accepts an "expression" that must evaluate to one of the following:
Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete
class:
<div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
... HTML to display the item ...
<input type="checkbox" ng-model="item.checked">
</div>
Above, we used ng-class expression type #3 - a map/object of class names to boolean values.
ng-style accepts an "expression" that must evaluate to:
For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer):
<div class="main-body" ng-style="{color: myColor}">
...
<input type="text" ng-model="myColor" placeholder="enter a color name">
The fiddle also contains an example of ng-show and ng-hide. If a checkbox is checked, in addition to the background-color turning pink, some text is shown. If 'red' is entered in the textbox, a div becomes hidden.
I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:
from time import strftime
from time import gmtime
strftime("%H:%M:%S", gmtime(666))
'00:11:06'
strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'
gmtime is used to convert seconds to special tuple format that strftime()
requires.
Note: Truncates after 23:59:59
or if you don't want anything fancy like animation etc. you can create a label and dock it to form then change it's z-index from document outline window to 0 and give it a background color so other controls wont be visible than run Application.DoEvents()
once in form load event and do all your coding in form shown event and at the and of shown event set your label visible property to false then run Application.DoEvents()
again.
It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.
@Request/View/Flow/Session/ApplicationScoped
A @RequestScoped
bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped
bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null
/void
without any navigation/redirect. A @FlowScoped
bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped
bean lives as long as the established HTTP session. An @ApplicationScoped
bean lives as long as the web application runs. Note that the CDI @Model
is basically a stereotype for @Named @RequestScoped
, so same rules apply.
Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped
for simple and non-ajax forms/presentations. Use @ViewScoped
for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped
for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped
for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped
for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.
Abusing an @ApplicationScoped
bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped
bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped
bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped
bean for request, session or application scoped data, and abusing a @SessionScoped
bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.
Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped
beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty
in case of JSF managed beans or @Inject
in case of CDI managed beans.
@CustomScoped/NoneScoped/Dependent
It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped
and @NoneScoped
, which are rarely used in real world. The @CustomScoped
must refer a custom Map<K, Bean>
implementation in some broader scope which has overridden Map#put()
and/or Map#get()
in order to have more fine grained control over bean creation and/or destroy.
The JSF @NoneScoped
and CDI @Dependent
basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped
or @Dependent
is injected in a @SessionScoped
, then it will live as long as the @SessionScoped
bean.
As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.
This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped
. The flash scope is only available as a map via ExternalContext#getFlash()
in managed beans and #{flash}
in EL.
apparently this problem got solved just by increasing queue size on my 3rd party smtp server. but the answer by Nip sounds like it is fairly usefull too
LinearLayout : A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.It means you can align views one by one (vertically/ horizontally).
RelativeLayout : This enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). It is based on relation of views from its parents and other views.
WebView : to load html, static or dynamic pages.
For more information refer this link:http://developer.android.com/guide/topics/ui/layout-objects.html
In your R script, called test.R
:
args <- commandArgs(trailingOnly = F)
myargument <- args[length(args)]
myargument <- sub("-","",myargument)
print(myargument)
q(save="no")
From the command line run:
R CMD BATCH -4 test.R
Your output file, test.Rout, will show that the argument 4
has been successfully passed to R:
cat test.Rout
> args <- commandArgs(trailingOnly = F)
> myargument <- args[length(args)]
> myargument <- sub("-","",myargument)
> print(myargument)
[1] "4"
> q(save="no")
> proc.time()
user system elapsed
0.222 0.022 0.236
For me it only started working after I rebooted device (Motorola-Nexus-6).
(I also tried to clean, disable "instant run", reopen Android Studio, verified installed applications to be sure there are no clashes, disable and reenable Debug mode in phone, reconnect USB cable)
As an option, you can use a type casting. If you have this error from typescript that means that some variable has type or is undefined:
let a: string[] | undefined;
let b: number = a.length; // [ts] Object is possibly 'undefined'
let c: number = (a as string[]).length; // ok
Be sure that a
really exist in your code.
I know this is old but this is what worked for me
Order by Isnull(Date,'12/31/9999')
after release of android studio v 3.0(stable), It will show popup, If gradle update is available
OR
Manually, just change version of gradle in top-level(project-level) build.gradle
file to latest,
buildscript {
...
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
}
}
check below chart
The Android Gradle Plugin and Gradle Android Gradle Plugin Requires Gradle 1.0.0 - 1.1.3 2.2.1 - 2.3 1.2.0 - 1.3.1 2.2.1 - 2.9 1.5.0 2.2.1+ 2.2.1 - 2.13 2.0.0 - 2.1.2 2.10 - 2.13 2.1.3 - 2.2.3 2.14.1+ 2.3.0+ 3.3+ 3.0.0+ 4.1+ 3.1.0+ 4.4+ 3.2.0 - 3.2.1 4.6+ 3.3.0 - 3.3.1 4.10.1+ 3.4.0 - 3.4.1 5.1.1+ 3.5.0 5.4.1+
check gradle revisions
<a href="page.html" onclick="return false" style="cursor:default;">page link</a>
Python isn't preprocessed. You can just create a file myconstants.py
:
MY_CONSTANT = 50
And importing them will just work:
import myconstants
print myconstants.MY_CONSTANT * 2
No, java.lang.Object#finalize
is the closest you can get.
However, when (and if) it is called, is not guaranteed.
See: java.lang.Runtime#runFinalizersOnExit(boolean)
It's probably because your SSH key has been removed/revoked. Make a new one and add it to your GitHub account.
Performing CRUD operations using Dapper is an easy task. I have mentioned the below examples that should help you in CRUD operations.
Code for CRUD:
Method #1: This method is used when you are inserting values from different entities.
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string insertQuery = @"INSERT INTO [dbo].[Customer]([FirstName], [LastName], [State], [City], [IsActive], [CreatedOn]) VALUES (@FirstName, @LastName, @State, @City, @IsActive, @CreatedOn)";
var result = db.Execute(insertQuery, new
{
customerModel.FirstName,
customerModel.LastName,
StateModel.State,
CityModel.City,
isActive,
CreatedOn = DateTime.Now
});
}
Method #2: This method is used when your entity properties have the same names as the SQL columns. So, Dapper being an ORM maps entity properties with the matching SQL columns.
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string insertQuery = @"INSERT INTO [dbo].[Customer]([FirstName], [LastName], [State], [City], [IsActive], [CreatedOn]) VALUES (@FirstName, @LastName, @State, @City, @IsActive, @CreatedOn)";
var result = db.Execute(insertQuery, customerViewModel);
}
Code for CRUD:
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string selectQuery = @"SELECT * FROM [dbo].[Customer] WHERE FirstName = @FirstName";
var result = db.Query(selectQuery, new
{
customerModel.FirstName
});
}
Code for CRUD:
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string updateQuery = @"UPDATE [dbo].[Customer] SET IsActive = @IsActive WHERE FirstName = @FirstName AND LastName = @LastName";
var result = db.Execute(updateQuery, new
{
isActive,
customerModel.FirstName,
customerModel.LastName
});
}
Code for CRUD:
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string deleteQuery = @"DELETE FROM [dbo].[Customer] WHERE FirstName = @FirstName AND LastName = @LastName";
var result = db.Execute(deleteQuery, new
{
customerModel.FirstName,
customerModel.LastName
});
}
JsonNode node = mapper.readValue("[{\"id\":\"value11\",\"name\": \"value12\",\"qty\":\"value13\"},"
System.out.println("id : "+node.findValues("id").get(0).asText());
this also done the trick.
Lets say your data is -
data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }
You can use the data.items()
method to get the dictionary elements. Note, in django templates we do NOT put ()
. Also some users mentioned values[0]
does not work, if that is the case then try values.items
.
<table>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
{% for key, values in data.items %}
<tr>
<td>{{key}}</td>
{% for v in values[0] %}
<td>{{v}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Am pretty sure you can extend this logic to your specific dict.
To iterate over dict keys in a sorted order - First we sort in python then iterate & render in django template.
return render_to_response('some_page.html', {'data': sorted(data.items())})
In template file:
{% for key, value in data %}
<tr>
<td> Key: {{ key }} </td>
<td> Value: {{ value }} </td>
</tr>
{% endfor %}
For anyone else following along, I've simply taken Ahmet's answer and updated the original asker's jsfiddle here, substituting:
audio.mp3
for
http://www.uscis.gov/files/nativedocuments/Track%2093.mp3
linking in a freely available mp3 off the web. Thank you for sharing the easy solution!
Let me quote the official documentation:
Important gotcha on spying real objects!
Sometimes it's impossible to use when(Object) for stubbing spies. Example:
List list = new LinkedList(); List spy = spy(list); // Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) when(spy.get(0)).thenReturn("foo"); // You have to use doReturn() for stubbing doReturn("foo").when(spy).get(0);
In your case it goes something like:
doReturn(resultsIWant).when(myClassSpy).method1();
It might help somebody.
I had the similar error message, but only in dev and staging environments, not in production. The valid redirect URIs were correctly set, for the dev and staging subdomains as well as for production.
It turned out I forgot that for those environments we use the testing FB app, which is a separate one in the FB developer page. Had to select that and update its settings.
getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for
{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"
but you need to get into the array and then do a search for "characters"
try this
String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";
JSONObject jsonResponse;
try {
ArrayList<String> temp = new ArrayList<String>();
jsonResponse = new JSONObject(json);
JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
for(int i=0;i<movies.length();i++){
JSONObject movie = movies.getJSONObject(i);
JSONArray characters = movie.getJSONArray("characters");
for(int j=0;j<characters.length();j++){
temp.add(characters.getString(j));
}
}
Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
checked it :)
Inspired by @ford04 answer I use this hook, which also takes callbacks for success, errors, finally and an abortFn:
export const useAsync = (
asyncFn,
onSuccess = false,
onError = false,
onFinally = false,
abortFn = false
) => {
useEffect(() => {
let isMounted = true;
const run = async () => {
try{
let data = await asyncFn()
if (isMounted && onSuccess) onSuccess(data)
} catch(error) {
if (isMounted && onError) onSuccess(error)
} finally {
if (isMounted && onFinally) onFinally()
}
}
run()
return () => {
if(abortFn) abortFn()
isMounted = false
};
}, [asyncFn, onSuccess])
}
If the asyncFn is doing some kind of fetch from back-end it often makes sense to abort it when the component is unmounted (not always though, sometimes if ie. you're loading some data into a store you might as well just want to finish it even if component is unmounted)
In [92]: (myseries==7).argmax()
Out[92]: 3
This works if you know 7 is there in advance. You can check this with (myseries==7).any()
Another approach (very similar to the first answer) that also accounts for multiple 7's (or none) is
In [122]: myseries = pd.Series([1,7,0,7,5], index=['a','b','c','d','e'])
In [123]: list(myseries[myseries==7].index)
Out[123]: ['b', 'd']
foreach(PropertyInfo propertyInfo in original.GetType().GetProperties()) {
if (propertyInfo.GetValue(updatedUser, null) == null)
propertyInfo.SetValue(updatedUser, propertyInfo.GetValue(original, null), null);
}
db.Entry(original).CurrentValues.SetValues(updatedUser);
db.SaveChanges();
with your VARCHAR, you may also need to specify the length, or its usually good to
What about grabbing the text, making a sting of it, then putting it into the query witrh
String TableName = "ComplicatedTableNameHere";
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere);
String editTextString1 = editText1.getText().toString();
BROKEN DOWN
String TableName = "ComplicatedTableNameHere";
//sets the table name as a string so you can refer to TableName instead of writing out your table name everytime
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere);
//gets the text from your edit text fieldfield
//editText1 = your edit text name
//EditTextIDhere = the id of your text field
String editTextString1 = editText1.getText().toString();
//sets the edit text as a string
//editText1 is the name of the Edit text from the (EditText) we defined above
//editTextString1 = the string name you will refer to in future
then use
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (Column_Name, Column_Name2, Column_Name3, Column_Name4)"
+ " VALUES ( "+EditTextString1+", 'Column_Value2','Column_Value3','Column_Value4');");
Hope this helps some what...
NOTE each string is within
'"+stringname+"'
its the 'and' that enable the multi line element of the srting, without it you just get the first line, not even sure if you get the whole line, it may just be the first word
Seems the easiest method is simply to use the Replace method that ships with .Net and has been around since .Net 1.0:
string res = Microsoft.VisualBasic.Strings.Replace(res,
"%PolicyAmount%",
"$0",
Compare: Microsoft.VisualBasic.CompareMethod.Text);
In order to use this method, you have to add a Reference to the Microsoft.VisualBasic assemblly. This assembly is a standard part of the .Net runtime, it is not an extra download or marked as obsolete.
function converToLocalTime(serverDate) {
var dt = new Date(Date.parse(serverDate));
var localDate = dt;
var gmt = localDate;
var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
var localNow = new Date().getTimezoneOffset(); // get the timezone
// offset in minutes
var localTime = min - localNow; // get the local time
var dateStr = new Date(localTime * 1000 * 60);
// dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return dateStr;
}
df['First Season'].loc[(df['First Season'] > 1990)] = 1
strange that nobody has this answer, the only missing part of your code is the ['First Season'] right after df and just remove your curly brackets inside.
Just want to add another way of doing this. I've seen multiple people on various related threads ask if you can use VerifyRenderingInServerForm without adding it to the parent page.
You actually can do this but it's a bit of a bodge.
First off create a new Page class which looks something like the following:
public partial class NoRenderPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
public override void VerifyRenderingInServerForm(Control control)
{
//Allows for printing
}
public override bool EnableEventValidation
{
get { return false; }
set { /*Do nothing*/ }
}
}
Does not need to have an .ASPX associated with it.
Then in the control you wish to render you can do something like the following.
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
var page = new NoRenderPage();
page.DesignerInitialize();
var form = new HtmlForm();
page.Controls.Add(form);
form.Controls.Add(pnl);
controlToRender.RenderControl(hw);
Now you've got your original control rendered as HTML. If you need to, add the control back into it's original position. You now have the HTML rendered, the page as normal and no changes to the page itself.
DDL is Data Definition Language: Just think you are defining the DB.
So we use CREATE,ALTER TRUNCATE commands.
DML is after defining we are Manipulating the data. So we use SELECT,INSERT, UPDATE, DELETE command.
Remember DDL commands are auto-committed. You don't need to use COMMIT statements.
DML (Data Manipulation Language) commands need to be commited/rolled back.
After you've retrieved the reflect.Value
of the field by using Field(i)
you can get a
interface value from it by calling Interface()
. Said interface value then represents the
value of the field.
There is no function to convert the value of the field to a concrete type as there are,
as you may know, no generics in go. Thus, there is no function with the signature GetValue() T
with T
being the type of that field (which changes of course, depending on the field).
The closest you can achieve in go is GetValue() interface{}
and this is exactly what reflect.Value.Interface()
offers.
The following code illustrates how to get the values of each exported field in a struct using reflection (play):
import (
"fmt"
"reflect"
)
func main() {
x := struct{Foo string; Bar int }{"foo", 2}
v := reflect.ValueOf(x)
values := make([]interface{}, v.NumField())
for i := 0; i < v.NumField(); i++ {
values[i] = v.Field(i).Interface()
}
fmt.Println(values)
}
Nope.
While in debug configuration there is a DEBUG
defined constant (automatically defined by Visual Studio) while there is no such constant defined for release mode. Check your project settings under build.
Selecting [Define DEBUG constant] under Project -> Build is like including #define DEBUG at the beginning of every file.
If you want to define a RELEASE constant for the release configuration go to:
Try this in your css:
#ntext{
color: #000000;
}
Then the following in all your navigation bar list codes:
<li><a href="#" id="ntext"><span class="glyphicon glyphicon-user"></span> About</a></li>
Are you targeting the android.R or the one in your own project?
Are you sure your own R.java file is generated? Mistakes in your xml views could cause the R.java not to be generated. Go through your view files and make sure all the xml is right!
As an alternative, one can rely on the cartesian product provided by itertools: itertools.product
, which avoids creating a temporary key or modifying the index:
import numpy as np
import pandas as pd
import itertools
def cartesian(df1, df2):
rows = itertools.product(df1.iterrows(), df2.iterrows())
df = pd.DataFrame(left.append(right) for (_, left), (_, right) in rows)
return df.reset_index(drop=True)
Quick test:
In [46]: a = pd.DataFrame(np.random.rand(5, 3), columns=["a", "b", "c"])
In [47]: b = pd.DataFrame(np.random.rand(5, 3), columns=["d", "e", "f"])
In [48]: cartesian(a,b)
Out[48]:
a b c d e f
0 0.436480 0.068491 0.260292 0.991311 0.064167 0.715142
1 0.436480 0.068491 0.260292 0.101777 0.840464 0.760616
2 0.436480 0.068491 0.260292 0.655391 0.289537 0.391893
3 0.436480 0.068491 0.260292 0.383729 0.061811 0.773627
4 0.436480 0.068491 0.260292 0.575711 0.995151 0.804567
5 0.469578 0.052932 0.633394 0.991311 0.064167 0.715142
6 0.469578 0.052932 0.633394 0.101777 0.840464 0.760616
7 0.469578 0.052932 0.633394 0.655391 0.289537 0.391893
8 0.469578 0.052932 0.633394 0.383729 0.061811 0.773627
9 0.469578 0.052932 0.633394 0.575711 0.995151 0.804567
10 0.466813 0.224062 0.218994 0.991311 0.064167 0.715142
11 0.466813 0.224062 0.218994 0.101777 0.840464 0.760616
12 0.466813 0.224062 0.218994 0.655391 0.289537 0.391893
13 0.466813 0.224062 0.218994 0.383729 0.061811 0.773627
14 0.466813 0.224062 0.218994 0.575711 0.995151 0.804567
15 0.831365 0.273890 0.130410 0.991311 0.064167 0.715142
16 0.831365 0.273890 0.130410 0.101777 0.840464 0.760616
17 0.831365 0.273890 0.130410 0.655391 0.289537 0.391893
18 0.831365 0.273890 0.130410 0.383729 0.061811 0.773627
19 0.831365 0.273890 0.130410 0.575711 0.995151 0.804567
20 0.447640 0.848283 0.627224 0.991311 0.064167 0.715142
21 0.447640 0.848283 0.627224 0.101777 0.840464 0.760616
22 0.447640 0.848283 0.627224 0.655391 0.289537 0.391893
23 0.447640 0.848283 0.627224 0.383729 0.061811 0.773627
24 0.447640 0.848283 0.627224 0.575711 0.995151 0.804567
Fastest by far (time is in comparison to Jacobs):
clc; clear all;
V = rand(1024*1024*32,1);
N = 10;
tic;
for i=1:N,
d = 1/sqrt(V(1)*V(1)+V(2)*V(2)+V(3)*V(3));
V1 = V*d;
end;
toc % 1.5s
Thank you to all the commenters on this page. When I first installed the latest TortoiseSVN I got this error.
I was using the latest version, so decided to downgrade to 1.5.9 (as the rest of my colleagues were using) and this got it to work. Then, once built, my machine was moved onto another subnet and the problem started again.
I went to TortoiseSVN->Settings->Saved Data and cleared the Authentication data. After this it worked fine.
However, numbering starts at 1
, so:
x = arange(5)
y = np.exp(5)
plt.figure(1)
plt.plot(x, y)
z = np.sin(x)
plt.figure(2)
plt.plot(x, z)
w = np.cos(x)
plt.figure(1) # Here's the part I need, but numbering starts at 1!
plt.plot(x, w)
Also, if you have multiple axes on a figure, such as subplots, use the axes(h)
command where h
is the handle of the desired axes object to focus on that axes.
(don't have comment privileges yet, sorry for new answer!)
Ideally the pivot should be the middle value in the entire array. This will reduce the chances of getting worst case performance.
What is the meaning of parameter -1?
You can read -1
as dynamic number of parameters or "anything". Because of that there can be only one parameter -1
in view()
.
If you ask x.view(-1,1)
this will output tensor shape [anything, 1]
depending on the number of elements in x
. For example:
import torch
x = torch.tensor([1, 2, 3, 4])
print(x,x.shape)
print("...")
print(x.view(-1,1), x.view(-1,1).shape)
print(x.view(1,-1), x.view(1,-1).shape)
Will output:
tensor([1, 2, 3, 4]) torch.Size([4])
...
tensor([[1],
[2],
[3],
[4]]) torch.Size([4, 1])
tensor([[1, 2, 3, 4]]) torch.Size([1, 4])
$x = '1234567'; echo substr ($x, 0, 3); // outputs 123 echo substr ($x, 1, 1); // outputs 2 echo substr ($x, -2); // outputs 67 echo substr ($x, 1); // outputs 234567 echo substr ($x, -2, 1); // outputs 6
Try this piece of code:
try {
Log.e("log_tag", "Error in convert String" + result.toString());
JSONObject json_data = new JSONObject(result);
String status = json_data.getString("Status");
{
String data = json_data.getString("locations");
JSONArray json_data1 = new JSONArray(data);
for (int i = 0; i < json_data1.length(); i++) {
json_data = json_data1.getJSONObject(i);
String lat = json_data.getString("lat");
String lng = json_data.getString("long");
}
}
}
If you're in local machine then use this command
/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
For remote machine, use below one
/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
I'm doing something like this
$url = https://en.example.com
$splitedBySlash = explode('/', $url);
$splitedByDot = explode('.', $splitedBySlash[2]);
$subdomain = $splitedByDot[0];
Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate
now has second parameter values
, which is being used for new record, but not for search
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'Taylor',
'lastName' => 'Otwell'
]);
let counter =1;
for(let item in items) {
counter++;
setTimeout(()=>{
//your code
},counter*5000); //5Sec delay between each iteration
}
I also faced the issue that link was not opening on browser here is my fix with steps:
1: Install this cordova plugin.
cordova plugin add cordova-plugin-inappbrowser
2: add the open link in the html like following.
<a href="#" onclick="window.open('https://www.google.com/', '_system', 'location=yes');" >Google</a>
3: this is the most importaint step due to this I faced lots of issue:
download the cordova.js
file and paste it in the www
folder.
Then make a reference of this in the index.html
file.
<script src="cordova.js"></script>
This solution will work for both the environment android and iPhone.
I don't have code to hand, but I always liked the approach of building a 2D lookup table of size 256 * 256 chars (RFC 1978, PPP Predictor Compression Protocol). To compress a string you loop over each char and use the lookup table to get the 'predicted' next char using the current and previous char as indexes into the table. If there is a match you write a single 1 bit, otherwise write a 0, the char and update the lookup table with the current char. This approach basically maintains a dynamic (and crude) lookup table of the most probable next character in the data stream.
You can start with a zeroed lookup table, but obviosuly it works best on very short strings if it is initialised with the most likely character for each character pair, for example, for the English language. So long as the initial lookup table is the same for compression and decompression you don't need to emit it into the compressed data.
This algorithm doesn't give a brilliant compression ratio, but it is incredibly frugal with memory and CPU resources and can also work on a continuous stream of data - the decompressor maintains its own copy of the lookup table as it decompresses, thus the lookup table adjusts to the type of data being compressed.
Main advantage of <jsp:include />
over <%@ include >
is:
<jsp:include />
allows to pass parameters
<jsp:include page="inclusion.jsp">
<jsp:param name="menu" value="objectValue"/>
</jsp:include>
which is not possible in <%@include file="somefile.jsp" %>
Maybe you should reset frame of the button, I had some problem too, and nslog the view of keyboard like this:
ios8:
"<UIInputSetContainerView: 0x7fef0364b0d0; frame = (0 0; 320 568); autoresize = W+H; layer = <CALayer: 0x7fef0364b1e0>>"
before8:
"<UIPeripheralHostView: 0x11393c860; frame = (0 352; 320 216); autoresizesSubviews = NO; layer = <CALayer: 0x11393ca10>>"
My experience:
var text = $('#myInputField');
var myObj = {title: 'Some title', content: text};
$.post(myUrl, myObj, callback);
The problem is that I forgot to add .val() to the end of $('#myInputField'); this action makes me waste time trying to figure out what was wrong, causing Illegal Invocation Error, since $('#myInputField') was in a different file than that system pointed out incorrect code. Hope this answer help fellows in the same mistake to avoid to loose time.
You can use JPGraph and Graphpite
This works correctly now:
begin
# statment
end until <condition>
But, it may be remove in the future, because the begin
statement is counterintuitive. See: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745
Matz (Ruby’s Creator) recommended doing it this way:
loop do
# ...
break if <condition>
end
I have a different approach from other people here, and it an approach that is guaranteed work without dealing with the CookieSyncManager (where you are at the mercy of semantics like "Note that even sync() happens asynchronously").
Essentially, we browse to the correct domain, then we execute javascript from the page context to set cookies for that domain (the same way the page itself would). Two drawbacks to the method are that may introduce an extra round trip time due to the extra http request you have to make; and if your site does not have the equivalent of a blank page, it may flash whatever URL you load first before taking you to the right place.
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.cookie.Cookie;
import android.annotation.SuppressLint;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewFragment {
private static final String BLANK_PAGE = "/blank.html"
private CookieSyncManager mSyncManager;
private CookieManager mCookieManager;
private String mTargetUrl;
private boolean mInitializedCookies;
private List<Cookie> mAllCookies;
public WebViewFragment(Context ctx) {
// We are still required to create an instance of Cookie/SyncManager.
mSyncManager = CookieSyncManager.createInstance(ctx);
mCookieManager = CookieManager.getInstance();
}
@SuppressLint("SetJavaScriptEnabled") public void loadWebView(
String url, List<Cookie> cookies, String domain) {
final WebView webView = ...
webView.setWebViewClient(new CookeWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
mInitializedCookies = false;
mTargetUrl = url;
mAllCookies = cookies;
// This is where the hack starts.
// Instead of loading the url, we load a blank page.
webView.loadUrl("http://" + domain + BLANK_PAGE);
}
public static String buildCookieString(final Cookie cookie) {
// You may want to add the secure flag for https:
// + "; secure"
// In case you wish to convert session cookies to have an expiration:
// + "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
// Note that you cannot set the HttpOnly flag as we are using
// javascript to set the cookies.
return cookie.getName() + "=" + cookie.getValue()
+ "; path=" + cookie.getPath()
+ "; domain=" + cookie.getDomain()
};
public synchronized String generateCookieJavascript() {
StringBuilder javascriptCode = new StringBuilder();
javascriptCode.append("javascript:(function(){");
for (final Cookie cookie : mAllCookies) {
String cookieString = buildCookieString(cookie);
javascriptCode.append("document.cookie=\"");
javascriptCode.append(
StringEscapeUtils.escapeJavascriptString(cookieString));
javascriptCode.append("\";");
}
// We use javascript to load the next url because we do not
// receive an onPageFinished event when this code finishes.
javascriptCode.append("document.location=\"");
javascriptCode.append(
StringEscapeUtils.escapeJavascriptString(mTargetUrl));
javascriptCode.append("\";})();");
return javascriptCode.toString();
}
private class CookieWebViewClient extends WebViewClient {
@Override public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (!mInitializedCookies) {
mInitializedCookies = true;
// Run our javascript code now that the temp page is loaded.
view.loadUrl(generateCookieJavascript());
return;
}
}
}
}
If you trust the domain the cookies are from, you may be able to get away without apache commons, but you have to understand that this can present a XSS risk if you are not careful.
In my case this error was specific to the hello-world
docker image. I used the nginx
image instead of the hello-world
image and the error was resolved.
The exceptions versus returning error code argument should be about flow control not philosophy (how "exceptional" an error is):
void f1() throws ExceptionType1, ExceptionType2 {}
void catchFunction() {
try{
while(someCondition){
try{
f1();
}catch(ExceptionType2 e2){
//do something, don't break the loop
}
}
}catch(ExceptionType1 e1){
//break the loop, do something else
}
}
How are you setting blob to DB? You should do:
//imagine u have a a prepared statement like:
PreparedStatement ps = conn.prepareStatement("INSERT INTO table VALUES (?)");
String blobString= "This is the string u want to convert to Blob";
oracle.sql.BLOB myBlob = oracle.sql.BLOB.createTemporary(conn, false,oracle.sql.BLOB.DURATION_SESSION);
byte[] buff = blobString.getBytes();
myBlob.putBytes(1,buff);
ps.setBlob(1, myBlob);
ps.executeUpdate();
Use conditional comments in HTML, like this:
<!--[if IE 8]>
<style>...</style>
<![endif]-->
See here: http://www.quirksmode.org/css/condcom.html
You can test for IE versions reliably and also be sure other browsers won't be confused.
Create Sequence.
CREATE SEQUENCE user_role_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 3
CACHE 1;
ALTER TABLE user_role_id_seq
OWNER TO postgres;
and alter table
ALTER TABLE user_roles ALTER COLUMN user_role_id SET DEFAULT nextval('user_role_id_seq'::regclass);
AFAIK, the only way this could be done is by using the state=directory
option.
While template
module supports most of copy
options, which in turn supports most file
options, you can not use something like state=directory
with it. Moreover, it would be quite confusing (would it mean that {{project_root}}/conf/code.conf
is a directory ? or would it mean that {{project_root}}/conf/
should be created first.
So I don't think this is possible right now without adding a previous file
task.
- file:
path: "{{project_root}}/conf"
state: directory
recurse: yes
An add-on to the previous answers since I came across this concern:
If you really want to insert something like 24-May-2005
to your DATE column, you could do something like this:
INSERT INTO someTable(Empid,Date_Joined)
VALUES
('S710',STR_TO_DATE('24-May-2005', '%d-%M-%Y'));
In the above query please note that if it's May
(ie: the month in letters) the format should be %M
.
NOTE: I tried this with the latest MySQL version 8.0 and it works!
This XPath:
count(//Property[long = '11007'])
returns the same value as:
count(//Property/long[text() = '11007'])
...except that the first counts Property
nodes that match the criterion and the second counts long
child nodes that match the criterion.
As per your comment and reading your question a couple of times, I believe that you want to find uniqueness based on a combination of criteria. Therefore, in actuality, I think you are actually checking multiple conditions. The following would work as well:
count(//Property[@Name = 'Alive'][long = '11007'])
because it means the same thing as:
count(//Property[@Name = 'Alive' and long = '11007'])
Of course, you would substitute the values for parameters in your template. The above code only illustrates the point.
EDIT (after question edit)
You were quite right about the XML being horrible. In fact, this is a downright CodingHorror candidate! I had to keep recounting to keep track of the "Property" node I was on presently. I feel your pain!
Here you go:
count(/root/ac/Properties/Property[Properties/Property/Properties/Property/long = $parPropId])
Note that I have removed all the other checks (for ID and Value). They appear not to be required since you are able to arrive at the relevant node using the hierarchy in the XML. Also, you already mentioned that the check for uniqueness is based only on the contents of the long
element.
If you have a process that already generates and returns an Image type, you can alter the bind and not have to modify any additional image creation code.
Refer to the ".Source" of the image in the binding statement.
XAML
<Image Name="imgOpenClose" Source="{Binding ImageOpenClose.Source}"/>
View Model Field
private Image _imageOpenClose;
public Image ImageOpenClose
{
get
{
return _imageOpenClose;
}
set
{
_imageOpenClose = value;
OnPropertyChanged();
}
}
Open a new worksheet on the related instance (Alt-F10)
and run the following query
SELECT view_name, owner
FROM sys.all_views
ORDER BY owner, view_name
char
: fixed-length character data with a maximum length of 8000 characters.nchar
: fixed-length unicode data with a maximum length of 4000 characters.Char
= 8 bit lengthNChar
= 16 bit lengthos.path.commonprefix() and os.path.relpath() are your friends:
>>> print os.path.commonprefix(['/usr/var/log', '/usr/var/security'])
'/usr/var'
>>> print os.path.commonprefix(['/tmp', '/usr/var']) # No common prefix: the root is the common prefix
'/'
You can thus test whether the common prefix is one of the paths, i.e. if one of the paths is a common ancestor:
paths = […, …, …]
common_prefix = os.path.commonprefix(list_of_paths)
if common_prefix in paths:
…
You can then find the relative paths:
relative_paths = [os.path.relpath(path, common_prefix) for path in paths]
You can even handle more than two paths, with this method, and test whether all the paths are all below one of them.
PS: depending on how your paths look like, you might want to perform some normalization first (this is useful in situations where one does not know whether they always end with '/' or not, or if some of the paths are relative). Relevant functions include os.path.abspath() and os.path.normpath().
PPS: as Peter Briggs mentioned in the comments, the simple approach described above can fail:
>>> os.path.commonprefix(['/usr/var', '/usr/var2/log'])
'/usr/var'
even though /usr/var
is not a common prefix of the paths. Forcing all paths to end with '/' before calling commonprefix()
solves this (specific) problem.
PPPS: as bluenote10 mentioned, adding a slash does not solve the general problem. Here is his followup question: How to circumvent the fallacy of Python's os.path.commonprefix?
PPPPS: starting with Python 3.4, we have pathlib, a module that provides a saner path manipulation environment. I guess that the common prefix of a set of paths can be obtained by getting all the prefixes of each path (with PurePath.parents()
), taking the intersection of all these parent sets, and selecting the longest common prefix.
PPPPPS: Python 3.5 introduced a proper solution to this question: os.path.commonpath()
, which returns a valid path.
I like the Infragistics controls. The WebDropDown has what you need. The only drawback is they can be a bit spendy.
$userRecord = Model::where([['email','=',$email],['password','=', $password]])->first();
or
$userRecord = self::where([['email','=',$email],['password','=', $password]])->first();
I` think this condition is better then 2 where. Its where condition array in array of where conditions;
Updated for Bootstrap 4
Bootstrap 4 now includes a position-fixed
class for this purpose so there is no need for additional CSS...
<div class="container">
<div class="row">
<div class="col-lg-3">
<div class="position-fixed">
Fixed content
</div>
</div>
<div class="col-lg-9">
Normal scrollable content
</div>
</div>
</div>
I got the answer.
grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'
Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:
All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.
This restriction accomplishes four functions, 1st and 3rd are important in this particular case:
And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.
One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.
There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:
If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.
Hope this will helps you to find the proper solution!
Found a good explanation with solutions: https://vcfvct.wordpress.com/2016/12/15/spring-nested-transactional-rollback-only/
1) remove the @Transacional from the nested method if it does not really require transaction control. So even it has exception, it just bubbles up and does not affect transactional stuff.
OR:
2) if nested method does need transaction control, make it as REQUIRE_NEW for the propagation policy that way even if throws exception and marked as rollback only, the caller will not be affected.
You can't directly add custom headers with window.open() in popup window but to work that we have two possible solutions
- Write Ajax method to call that particular URL with headers in a separate HTML file and use that HTML as url in
<i>window.open()</i>
here is abc.html
$.ajax({
url: "ORIGIONAL_URL",
type: 'GET',
dataType: 'json',
headers: {
Authorization : 'Bearer ' + data.id_token,
AuthorizationCheck : 'AccessCode ' +data.checkSum ,
ContentType :'application/json'
},
success: function (result) {
console.log(result);
},
error: function (error) {
} });
call html
window.open('*\abc.html')
here CORS policy can block the request if CORS is not enabled in requested URL.
- You can request a URL that triggers a server-side program which makes the request with custom headers and then returns the response redirecting to that particular url.
Suppose in Java Servlet(/requestURL) we'll make this request
`
String[] responseHeader= new String[2];
responseHeader[0] = "Bearer " + id_token;
responseHeader[1] = "AccessCode " + checkSum;
String url = "ORIGIONAL_URL";
URL obj = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) obj.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Authorization", responseHeader[0]);
urlConnection.setRequestProperty("AuthorizationCheck", responseHeader[1]);
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer response1 = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response1.append(inputLine);
}
in.close();
response.sendRedirect(response1.toString());
// print result
System.out.println(response1.toString());
} else {
System.out.println("GET request not worked");
}
`
call servlet in window.open('/requestURL')
You need to make sure, when you run command (install npm -g gulp), it will create install gulp on C:\ directory.
that directory should match with whatver npm path variable set in your java path.
just run path from command prompt, and verify this. if not, change your java class path variable wherever you gulp is instaled.
It should work.
You can do:
>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
I know this question is old now, but after doing a ton of research on various solutions to this problem, I think I may have come up with a better solution.
UPDATE 1: Since posting this answer, I have added all of this code to a simple service that I have posted to GitHub. The repo is located here. Feel free to check it out for more info.
UPDATE 2: This answer is great if all you need is a lightweight solution for pulling in stylesheets for your routes. If you want a more complete solution for managing on-demand stylesheets throughout your application, you may want to checkout Door3's AngularCSS project. It provides much more fine-grained functionality.
In case anyone in the future is interested, here's what I came up with:
1. Create a custom directive for the <head>
element:
app.directive('head', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'E',
link: function(scope, elem){
var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
elem.append($compile(html)(scope));
scope.routeStyles = {};
$rootScope.$on('$routeChangeStart', function (e, next, current) {
if(current && current.$$route && current.$$route.css){
if(!angular.isArray(current.$$route.css)){
current.$$route.css = [current.$$route.css];
}
angular.forEach(current.$$route.css, function(sheet){
delete scope.routeStyles[sheet];
});
}
if(next && next.$$route && next.$$route.css){
if(!angular.isArray(next.$$route.css)){
next.$$route.css = [next.$$route.css];
}
angular.forEach(next.$$route.css, function(sheet){
scope.routeStyles[sheet] = sheet;
});
}
});
}
};
}
]);
This directive does the following things:
$compile
) an html string that creates a set of <link />
tags for every item in the scope.routeStyles
object using ng-repeat
and ng-href
.<link />
elements to the <head>
tag.$rootScope
to listen for '$routeChangeStart'
events. For every '$routeChangeStart'
event, it grabs the "current" $$route
object (the route that the user is about to leave) and removes its partial-specific css file(s) from the <head>
tag. It also grabs the "next" $$route
object (the route that the user is about to go to) and adds any of its partial-specific css file(s) to the <head>
tag.ng-repeat
part of the compiled <link />
tag handles all of the adding and removing of the page-specific stylesheets based on what gets added to or removed from the scope.routeStyles
object.Note: this requires that your ng-app
attribute is on the <html>
element, not on <body>
or anything inside of <html>
.
2. Specify which stylesheets belong to which routes using the $routeProvider
:
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/some/route/1', {
templateUrl: 'partials/partial1.html',
controller: 'Partial1Ctrl',
css: 'css/partial1.css'
})
.when('/some/route/2', {
templateUrl: 'partials/partial2.html',
controller: 'Partial2Ctrl'
})
.when('/some/route/3', {
templateUrl: 'partials/partial3.html',
controller: 'Partial3Ctrl',
css: ['css/partial3_1.css','css/partial3_2.css']
})
}]);
This config adds a custom css
property to the object that is used to setup each page's route. That object gets passed to each '$routeChangeStart'
event as .$$route
. So when listening to the '$routeChangeStart'
event, we can grab the css
property that we specified and append/remove those <link />
tags as needed. Note that specifying a css
property on the route is completely optional, as it was omitted from the '/some/route/2'
example. If the route doesn't have a css
property, the <head>
directive will simply do nothing for that route. Note also that you can even have multiple page-specific stylesheets per route, as in the '/some/route/3'
example above, where the css
property is an array of relative paths to the stylesheets needed for that route.
3. You're done Those two things setup everything that was needed and it does it, in my opinion, with the cleanest code possible.
Hope that helps someone else who might be struggling with this issue as much as I was.
On saveAndFlush
, changes will be flushed to DB immediately in this command. With save
, this is not necessarily true, and might stay just in memory, until flush
or commit
commands are issued.
But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.
In your case, you probably use some sort of transactions mechanism, which issues commit
command for you if everything works out fine.
I'm sticking with DbVisualizer Free until something better comes along.
EDIT/UPDATE: been using https://dbeaver.io/ lately, really enjoying this
Note that Robert's answer is correct, and it works in sh
as well. You can (portably) simplify it even further:
for i in "$@"
is equivalent to:
for i
I.e., you don't need anything!
Testing ($
is command prompt):
$ set a b "spaces here" d
$ for i; do echo "$i"; done
a
b
spaces here
d
$ for i in "$@"; do echo "$i"; done
a
b
spaces here
d
I first read about this in Unix Programming Environment by Kernighan and Pike.
In bash
, help for
documents this:
for NAME [in WORDS ... ;] do COMMANDS; done
If
'in WORDS ...;'
is not present, then'in "$@"'
is assumed.
The greps can be chained. For example:
tail -f admin.log | grep -v "Nopaging the limit is" | grep -v "keyword to remove is"
I used in similar case the answer from Günter Zöchbauer, and it was perfect to me, moving the form creation to a function and calling it from ngOnInit().
For illustration, that's how I made it, including the fields initialization:
ngOnInit() {
// initializing the form model here
this.createForm();
}
createForm() {
let EMAIL_REGEXP = /^[^@]+@([^@\.]+\.)+[^@\.]+$/i; // here just to add something more, useful too
this.userForm = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(3)]),
city: new FormControl(''),
email: new FormControl(null, Validators.pattern(EMAIL_REGEXP))
});
this.initializeFormValues();
}
initializeFormValues() {
const people = {
name: '',
city: 'Rio de Janeiro', // Only for demonstration
email: ''
};
(<FormGroup>this.userForm).setValue(people, { onlySelf: true });
}
resetForm() {
this.createForm();
this.submitted = false;
}
I added a button to the form for a smart reset (with the fields initialization):
In the HTML file (or inline template):
<button type="button" [disabled]="userForm.pristine" (click)="resetForm()">Reset</button>
After loading the form at first time or after clicking the reset button we have the following status:
FORM pristine: true
FORM valid: false (because I have required a field)
FORM submitted: false
Name pristine: true
City pristine: true
Email pristine: true
And all the field initializations that a simple form.reset() doesn't make for us! :-)
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
$emailSmtpServerPort = "587"
$emailSmtpUser = "username"
$emailSmtpPass = 'password'
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "[From email address]"
$emailMessage.To.Add( "[Send to email address]" )
$emailMessage.Subject = "Testing e-mail"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = @"
<p>Here is a message that is <strong>HTML formatted</strong>.</p>
<p>From your friendly neighborhood IT guy</p>
"@
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )
The trick is to implement a stable sort. I've created a Widget class that can contain your test data:
public class Widget : IComparable
{
int x;
int y;
public int X
{
get { return x; }
set { x = value; }
}
public int Y
{
get { return y; }
set { y = value; }
}
public Widget(int argx, int argy)
{
x = argx;
y = argy;
}
public int CompareTo(object obj)
{
int result = 1;
if (obj != null && obj is Widget)
{
Widget w = obj as Widget;
result = this.X.CompareTo(w.X);
}
return result;
}
static public int Compare(Widget x, Widget y)
{
int result = 1;
if (x != null && y != null)
{
result = x.CompareTo(y);
}
return result;
}
}
I implemented IComparable, so it can be unstably sorted by List.Sort().
However, I also implemented the static method Compare, which can be passed as a delegate to a search method.
I borrowed this insertion sort method from C# 411:
public static void InsertionSort<T>(IList<T> list, Comparison<T> comparison)
{
int count = list.Count;
for (int j = 1; j < count; j++)
{
T key = list[j];
int i = j - 1;
for (; i >= 0 && comparison(list[i], key) > 0; i--)
{
list[i + 1] = list[i];
}
list[i + 1] = key;
}
}
You would put this in the sort helpers class that you mentioned in your question.
Now, to use it:
static void Main(string[] args)
{
List<Widget> widgets = new List<Widget>();
widgets.Add(new Widget(0, 1));
widgets.Add(new Widget(1, 1));
widgets.Add(new Widget(0, 2));
widgets.Add(new Widget(1, 2));
InsertionSort<Widget>(widgets, Widget.Compare);
foreach (Widget w in widgets)
{
Console.WriteLine(w.X + ":" + w.Y);
}
}
And it outputs:
0:1
0:2
1:1
1:2
Press any key to continue . . .
This could probably be cleaned up with some anonymous delegates, but I'll leave that up to you.
EDIT: And NoBugz demonstrates the power of anonymous methods...so, consider mine more oldschool :P
Check out the sortBy
method for Eloquent: http://laravel.com/docs/eloquent
If you want to pass with "arguments" a few others, you have to create the array of all arguments together, i.e. like this:
var Log = {
log: function() {
var args = ['myarg here'];
for(i=0; i<arguments.length; i++) args = args.concat(arguments[i]);
console.log.apply(this, args);
}
}
Another flavor for same "proxy for nuget": alternatively you can set your nuget proxing settings to connect through fiddler. Below cmd will save proxy settings in in default nuget config file for user at %APPDATA%\NuGet\NuGet.Config
nuget config -Set HTTP_PROXY=http://127.0.0.1:8888
Whenever you need nuget to reach out the internet, just open Fiddler, asumming you have fiddler listening on default port 8888.
This configuration is not sensitive to passwork changes because fiddler will resolve any authentication with up stream proxy for you.
It's actually the JavaScript array reduce
function rather than being something specific to TypeScript.
As described in the docs: Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
Here's an example which sums up the values of an array:
let total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue);_x000D_
console.log(total);
_x000D_
The snippet should produce 6
.
Note: You should not edit the default settings, because they get reset on updates/upgrades. For customization, you should override any setting by using the user bindings.
On Mac:
This opens a document that you can edit the keybindings for Sublime.
If you search "ctrl+super+g"
you find this:
{ "keys": ["ctrl+super+g"], "command": "find_all_under" },
In my case it is similar to @Michael Easter: I got a problem in a job due to lack of disk space. I cleared some space, restarted Jenkins but still the problem persisted.
The solution was to go to Jenkins -> Manage Jenkins -> Manage Nodes and just Click on the button to update the status.
Just complementing @PeterBechP 's answer.
Don't forget to scape the special chars. https://stackoverflow.com/a/6969486
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
var name = 'Peter+with+special+chars';
model.findOne({name: new RegExp('^'+escapeRegExp(name)+'$', "i")}, function(err, doc) {
//Do your action here..
});
Doing $('body').find();
is not necessary when looking up by ID; there is no performance gain.
Please also note that having an ID that starts with a number is not valid HTML:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
I know this question is too old, but still, I think this approach would be cleaner:
cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);
In this case you wont need to go over the entire options with each()
.
Although by that time prop()
didn't exist so for older versions of jQuery use attr()
.
UPDATE
You have to be certain when using contains
because you can find multiple options, in case of the string inside cat
matches a substring of a different option than the one you intend to match.
Then you should use:
cat = $.URLDecode(cat);
$('#cbCategory option')
.filter(function(index) { return $(this).text() === cat; })
.prop('selected', true);
PostgreSql is very advanced when related to logging techniques
Logs are stored in Installationfolder/data/pg_log folder
. While log settings are placed in postgresql.conf
file.
Log format is usually set as stderr
. But CSV log format is recommended. In order to enable CSV format change in
log_destination = 'stderr,csvlog'
logging_collector = on
In order to log all queries, very usefull for new installations, set min. execution time for a query
log_min_duration_statement = 0
In order to view active Queries on your database, use
SELECT * FROM pg_stat_activity
To log specific queries set query type
log_statement = 'all' # none, ddl, mod, all
For more information on Logging queries see PostgreSql Log.
I know this is old, but since Postgresql 9.3 there is an option to use a keyword "LATERAL" to use RELATED subqueries inside of JOINS, so the query from the question would look like:
SELECT
name, author_id, count(*), t.total
FROM
names as n1
INNER JOIN LATERAL (
SELECT
count(*) as total
FROM
names as n2
WHERE
n2.id = n1.id
AND n2.author_id = n1.author_id
) as t ON 1=1
GROUP BY
n1.name, n1.author_id
You can't by default. The dot is the separator / trigger for attribute lookup / key lookup / slice.
Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:
- Dictionary lookup. Example: foo["bar"]
- Attribute lookup. Example: foo.bar
- List-index lookup. Example: foo[bar]
But you can make a filter which lets you pass in an argument:
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters
@register.filter(name='lookup')
def lookup(value, arg):
return value[arg]
{{ mydict|lookup:item.name }}
One of the easiest way to do it is by using
npx --ignore-existing create-react-app [project name]
This will remove the old cached version of create-react-app and then get the new version to create the project.
Note: Adding the name of the project is important as just ignoring the existing create-react-app version is stale and the changes in your machines global env is temporary and hence later just using npx create-react-app [project name]
will not provide the desired result.
First of All, this can be easily done, for e.g. by PHP to force the browser to renew files based on cache date (expiration time). If you just need it for experimental needs, then try to use ctrl+shift+del to clear all cache at once inside Firefox browser. The third solution is to use many add-ons that exits for Firefox to clear cache based on time lines.
The error in the Google DevTools are caused Google extensions.
No more errors in the console.
Python lists are mutable objects and here:
plot_data = [[]] * len(positions)
you are repeating the same list len(positions)
times.
>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>>
Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.
If you want different lists, you can do this way:
plot_data = [[] for _ in positions]
for example:
>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]
Give your parent div position: relative
, then give your child div position: absolute
, this will absolute position the div inside of its parent, then you can give the child bottom: 0px;
See example here:
If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.
// function scope
// this initializes all elements to 0
int arr[4] = {0};
// equivalent to
int arr[4] = {0, 0, 0, 0};
// file scope
int arr[4];
// equivalent to
int arr[4] = {0};
Please note that there is no standard way to initialize the elements of an array to a value other than zero using an initializer list which contains a single element (the value). You must explicitly initialize all elements of the array using the initializer list.
// initialize all elements to 4
int arr[4] = {4, 4, 4, 4};
// equivalent to
int arr[] = {4, 4, 4, 4};
Regexes can also limit the number of characters.
r = re.compile("^[a-z]{1,15}$")
gives you a regex that only matches if the input is entirely lowercase ASCII letters and 1 to 15 characters long.
Issue in my case: Some updates were made to some rows within a transaction and before the transaction was committed, in another place, the same rows were being updated outside this transaction. Ensuring that all the updates to the rows are made within the same transaction resolved my issue
.
>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM
Try replacing %I
with %H
.
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
In my case, in the host file, the machine name is hard coded with older IP. I replace the older IP with the new one, the issue is resolved.
Host file location
WindowsDrive:\Windows\System32\drivers\etc\hosts
Modifications done 159.xx.xx.xxx MachineName
Update: The code in this answer is for Super CSV 1.52. Updated code examples for Super CSV 2.4.0 can be found at the project website: http://super-csv.github.io/super-csv/index.html
The SuperCSV project directly supports the parsing and structured manipulation of CSV cells. From http://super-csv.github.io/super-csv/examples_reading.html you'll find e.g.
given a class
public class UserBean {
String username, password, street, town;
int zip;
public String getPassword() { return password; }
public String getStreet() { return street; }
public String getTown() { return town; }
public String getUsername() { return username; }
public int getZip() { return zip; }
public void setPassword(String password) { this.password = password; }
public void setStreet(String street) { this.street = street; }
public void setTown(String town) { this.town = town; }
public void setUsername(String username) { this.username = username; }
public void setZip(int zip) { this.zip = zip; }
}
and that you have a CSV file with a header. Let's assume the following content
username, password, date, zip, town
Klaus, qwexyKiks, 17/1/2007, 1111, New York
Oufu, bobilop, 10/10/2007, 4555, New York
You can then create an instance of the UserBean and populate it with values from the second line of the file with the following code
class ReadingObjects {
public static void main(String[] args) throws Exception{
ICsvBeanReader inFile = new CsvBeanReader(new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
try {
final String[] header = inFile.getCSVHeader(true);
UserBean user;
while( (user = inFile.read(UserBean.class, header, processors)) != null) {
System.out.println(user.getZip());
}
} finally {
inFile.close();
}
}
}
using the following "manipulation specification"
final CellProcessor[] processors = new CellProcessor[] {
new Unique(new StrMinMax(5, 20)),
new StrMinMax(8, 35),
new ParseDate("dd/MM/yyyy"),
new Optional(new ParseInt()),
null
};
String[] splitted = fileName.split(".");
String fileNameWithoutExtension = fileName.replace("." + splitted[splitted.length - 1], "");
Inside a code block (eg, @foreach
), you need to mark the markup (or, in this case, Javascript) with @:
or the <text>
tag.
Inside the markup contexts, you need to surround code with code blocks (@{ ... }
or @if
, ...)
move
in windows is equivalent of mv
command in Linux
del
in windows is equivalent of rm
command in Linux
std::queue<myclass*> my_queue;
will do the job.
See here for more information on this container.
DECLARE @MYVAR NVARCHAR(100)
DECLARE @step int
SET @step = 0;
DECLARE MYTESTCURSOR CURSOR
DYNAMIC
FOR
SELECT col FROM [dbo].[table]
OPEN MYTESTCURSOR
FETCH LAST FROM MYTESTCURSOR INTO @MYVAR
print @MYVAR;
WHILE @step < 10
BEGIN
FETCH PRIOR FROM MYTESTCURSOR INTO @MYVAR
print @MYVAR;
SET @step = @step + 1;
END
CLOSE MYTESTCURSOR
DEALLOCATE MYTESTCURSOR
You can find that row with
DataRow row = table.Select("Product_id=2").FirstOrDefault();
and update it
row["Product_name"] = "cde";
I have solved this problem by importing the following dependency. you must manually import httpclient
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
I just found out you can also do a
array_splice($ar, 0, 0);
That does the re-indexing inplace, so you don't end up with a copy of the original array.
If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.
So instead of:
select cast(cast(1234567890 as float) as nvarchar(50))
1.23457e+009
You would use:
select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
1234567890
In these examples the innermost cast(1234567890 as float)
is used in place of selecting a value from the appropriate column.
I really recommend that you not store phone numbers in floats though!
What if the phone number starts with a zero?
select cast(0100884555 as float)
100884555
Whoops! We just stored an incorrect phone number...
You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.
var mouseOverHandler = function() {
// Do stuff
};
var mouseOutHandler = function () {
// Do stuff
};
$(function() {
// On the document load, apply to existing elements
$('select').hover(mouseOverHandler, mouseOutHandler);
});
// This next part would be in the callback from your Ajax call
$("<select></select>")
.append( /* Your <option>s */ )
.hover(mouseOverHandler, mouseOutHandler)
.appendTo( /* Wherever you need the select box */ )
;
This is now possible in modern browsers using localeCompare. By passing the numeric: true
option, it will smartly recognize numbers. You can do case-insensitive using sensitivity: 'base'
. Tested in Chrome, Firefox, and IE11.
Here's an example. It returns 1
, meaning 10 goes after 2:
'10'.localeCompare('2', undefined, {numeric: true, sensitivity: 'base'})
For performance when sorting large numbers of strings, the article says:
When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property. Docs link
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});_x000D_
var myArray = ['1_Document', '11_Document', '2_Document'];_x000D_
console.log(myArray.sort(collator.compare));
_x000D_
For a graphical view I'd use gitk
:
gitk [filename]
or to follow filename past renames
gitk --follow [filename]
In addition to what eugene and stevenl posted, you might encounter problems with using both <>
and <STDIN>
in one script: <>
iterates through (=concatenating) all files given as command line arguments.
However, should a user ever forget to specify a file on the command line, it will read from STDIN, and your code will wait forever on input
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
var iDiv2 = document.createElement('div');
iDiv2.className = "block-2";
iDiv.appendChild(iDiv2);
// Append to the document last so that the first append is more efficient.
document.body.appendChild(iDiv);
My problem was I had due to the non-existence of a native Swift CommonCrypto, used a bridging header and a target that with some magic included it in the build. Since CommonCrypto is now native, I solved the problem by removing the target and the #import
and instead added an import CommonCrypto
where I used it.
1. Why does the getOne(id) method fail?
See this section in the docs. You overriding the already in place transaction might be causing the issue. However, without more info this one is difficult to answer.
2. When I should use the getOne(id) method?
Without digging into the internals of Spring Data JPA, the difference seems to be in the mechanism used to retrieve the entity.
If you look at the JavaDoc for getOne(ID)
under See Also:
See Also:
EntityManager.getReference(Class, Object)
it seems that this method just delegates to the JPA entity manager's implementation.
However, the docs for findOne(ID)
do not mention this.
The clue is also in the names of the repositories.
JpaRepository
is JPA specific and therefore can delegate calls to the entity manager if so needed.
CrudRepository
is agnostic of the persistence technology used. Look here. It's used as a marker interface for multiple persistence technologies like JPA, Neo4J etc.
So there's not really a 'difference' in the two methods for your use cases, it's just that findOne(ID)
is more generic than the more specialised getOne(ID)
. Which one you use is up to you and your project but I would personally stick to the findOne(ID)
as it makes your code less implementation specific and opens the doors to move to things like MongoDB etc. in the future without too much refactoring :)
you could try this:
1. Open the "Android Virtual device Manager"
2. Select from one the listed devices there and run it.
3. Right click your Android App -> Run As -> Android Application
It worked for me. I tried this on an emulator in eclipse. It takes a while before the app is run. For me it took 33 seconds. Wait until the message in the console says "Success!"
const state.contactList = [{
name: 'jane',
email: '[email protected]'
},{},{},...]
const fileredArray = state.contactsList.filter((contactItem) => {
const regex = new RegExp(`${action.payload}`, 'gi');
return contactItem.nameProperty.match(regex) ||
contactItem.emailProperty.match(regex);
});
// contactList: all the contacts stored in state
// action.payload: whatever typed in search field
Since 9.0 this is even easier:
SELECT id,
string_agg(some_column, ',')
FROM the_table
GROUP BY id
Ahah! Cade is on the money.
An artifact in TOAD prints \r\n
as two placeholder 'blob' characters, but prints a single \r
also as two placeholders. The 1st step toward a solution is to use ..
REPLACE( col_name, CHR(13) || CHR(10) )
.. but I opted for the slightly more robust ..
REPLACE(REPLACE( col_name, CHR(10) ), CHR(13) )
.. which catches offending characters in any order. My many thanks to Cade.
M.
>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')
Using jq to convert the env to JSON:
env_as_json=`jq -c -n env`
docker run -e HOST_ENV="$env_as_json" <image>
this requires jq version 1.6 or newer
this pust the host env as json, essentially like so in Dockerfile:
ENV HOST_ENV (all env from the host as json)
Yow can use querySelectorAll to select all the classes and loop through them to assign the eventListener. The if condition checks if it contains the class name.
const arrClass = document.querySelectorAll(".className");
for (let i of arrClass) {
i.addEventListener("click", (e) => {
if (e.target.classList.contains("className")) {
console.log("Perfrom Action")
}
})
}
You could use for()
with assign()
to create many objects.
See the example from assign()
:
for(i in 1:6) { #-- Create objects 'r.1', 'r.2', ... 'r.6' --
nam <- paste("r", i, sep = ".")
assign(nam, 1:i)
Looking the new objects
ls(pattern = "^r..$")
Are you using the right chat_id and including your bot's token after "bot" in the address? (api.telegram.org/bottoken/sendMessage)
This page explains a few things about sending (down in "sendMessage" section) - basic stuff, but I often forget the basics.
To quote:
In order to use the sendMessage method we need to use the proper chat_id.
First things first let's send the /start command to our bot via a Telegram client.
After sent this command let's perform a getUpdates commands.
curl -s \
-X POST \ https://api.telegram.org/bot<token>/getUpdates \ | jq .
The response will be like the following
{ "result": [
{
"message": {
"text": "/start",
"date": 1435176541,
"chat": {
"username": "yourusername",
"first_name": "yourfirstname",
"id": 65535
},
"from": {
"username": "yourusername",
"first_name": "yourfirstname",
"id": 65535
},
"message_id": 1
},
"update_id": 714636917
} ], "ok": true }
We are interested in the property result.message[0].chat.id, save this information elsewhere.
Please note that this is only an example, you may want to set up some automatism to handle those informations Now how we can send a message ? It's simple let's check out this snippet.
curl -s \
-X POST \ https://api.telegram.org/bot<token>/sendMessage \
-d text="A message from your bot" \
-d chat_id=65535 \ | jq .
Where chat_id is the piece of information saved before.
I hope that helps.
Determine the type of an object with type
>>> obj = object()
>>> type(obj)
<class 'object'>
Although it works, avoid double underscore attributes like __class__
- they're not semantically public, and, while perhaps not in this case, the builtin functions usually have better behavior.
>>> obj.__class__ # avoid this!
<class 'object'>
Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell the difference.
Well that's a different question, don't use type - use isinstance
:
def foo(obj):
"""given a string with items separated by spaces,
or a list or tuple,
do something sensible
"""
if isinstance(obj, str):
obj = str.split()
return _foo_handles_only_lists_or_tuples(obj)
This covers the case where your user might be doing something clever or sensible by subclassing str
- according to the principle of Liskov Substitution, you want to be able to use subclass instances without breaking your code - and isinstance
supports this.
Even better, you might look for a specific Abstract Base Class from collections
or numbers
:
from collections import Iterable
from numbers import Number
def bar(obj):
"""does something sensible with an iterable of numbers,
or just one number
"""
if isinstance(obj, Number): # make it a 1-tuple
obj = (obj,)
if not isinstance(obj, Iterable):
raise TypeError('obj must be either a number or iterable of numbers')
return _bar_sensible_with_iterable(obj)
Or, perhaps best of all, use duck-typing, and don't explicitly type-check your code. Duck-typing supports Liskov Substitution with more elegance and less verbosity.
def baz(obj):
"""given an obj, a dict (or anything with an .items method)
do something sensible with each key-value pair
"""
for key, value in obj.items():
_baz_something_sensible(key, value)
type
to actually get an instance's class. isinstance
to explicitly check for actual subclasses or registered abstractions. Using std::bitset
int value = 123;
std::bitset<sizeof(int)> bits(value);
std::cout <<bits.to_string();
I am not sure if this fits your oracle version. On my 10g I can use pipelined table functions:
set serveroutput on
create type number_list as table of number;
-- since you want this solution
create or replace function split_csv (i_csv varchar2) return number_list pipelined
is
mystring varchar2(2000):= i_csv;
begin
for r in
( select regexp_substr(mystring,'[^,]+',1,level) element
from dual
connect by level <= length(regexp_replace(mystring,'[^,]+')) + 1
)
loop
--dbms_output.put_line(r.element);
pipe row(to_number(r.element, '999999.99'));
end loop;
end;
/
insert into foo
select column_a,column_b from
(select column_value column_a, rownum rn from table(split_csv('0.75, 0.64, 0.56, 0.45'))) a
,(select column_value column_b, rownum rn from table(split_csv('0.25, 0.5, 0.65, 0.8'))) b
where a.rn = b.rn
;
Have a look at PHP's available XML extensions.
The main difference between XML Parser and SimpleXML is that the latter is not a pull parser. SimpleXML is built on top of the DOM extensions and will load the entire XML file into memory. XML Parser like XMLReader will only load the current node into memory. You define handlers for specific nodes which will get triggered when the Parser encounters it. That is faster and saves on memory. You pay for that with not being able to use XPath.
Personally, I find SimpleXml quite limiting (hence simple) in what it offers over DOM. You can switch between DOM and SimpleXml easily though, but I usually dont bother and go the DOM route directly. DOM is an implementation of the W3C DOM API, so you might be familiar with it from other languages, for instance JavaScript.
It seems like you are essentially looking into computing the z-score or standard score of your data, which is calculated through the formula: z = (x-mean(x))/std(x)
This should work:
%% Original data (Normal with mean 1 and standard deviation 2)
x = 1 + 2*randn(100,1);
mean(x)
var(x)
std(x)
%% Normalized data with mean 0 and variance 1
z = (x-mean(x))/std(x);
mean(z)
var(z)
std(z)
I like PyInstaller - especially the "windowed" variant:
pyinstaller --onefile --windowed myscript.py
It will create one single *.exe file in a distination/folder.
The thing to watch out for when writing C++ dlls is name mangling. If you want interoperability between C and C++, you'd be better off by exporting non-mangled C-style functions from within the dll.
You have two options to use a dll
LoadLibrary()
or some suitable function to load the library, retrieve a function pointer (GetProcAddress
) and call it -- runtime dynamic linkingExporting classes will not work if you follow the second method though.
You have to add writing rights to the directory in which your sqlite database is stored. So running chmod 664 /srv/mysite
should help.
This is a security risk, so better solution is to change the owner of your database to www-data
:
chown www-data:www-data /srv/mysite
chown www-data:www-data /srv/mysite/DATABASE.sqlite
String
vs string
Argument of type 'String' is not assignable to parameter of type 'string'.
'string' is a primitive, but 'String' is a wrapper object.
Prefer using 'string' when possible.
String Object
// error
class SVGStorageUtils {
store: object;
constructor(store: object) {
this.store = store;
}
setData(key: String = ``, data: object) {
sessionStorage.setItem(key, JSON.stringify(data));
}
getData(key: String = ``) {
const obj = JSON.parse(sessionStorage.getItem(key));
}
}
string primitive
// ok
class SVGStorageUtils {
store: object;
constructor(store: object) {
this.store = store;
}
setData(key: string = ``, data: object) {
sessionStorage.setItem(key, JSON.stringify(data));
}
getData(key: string = ``) {
const obj = JSON.parse(sessionStorage.getItem(key));
}
}
You can do this on the command line:
python3 -m json.tool some.json
(as already mentioned in the commentaries to the question, thanks to @Kai Petzke for the python3 suggestion).
Actually python is not my favourite tool as far as json processing on the command line is concerned. For simple pretty printing is ok, but if you want to manipulate the json it can become overcomplicated. You'd soon need to write a separate script-file, you could end up with maps whose keys are u"some-key" (python unicode), which makes selecting fields more difficult and doesn't really go in the direction of pretty-printing.
You can also use jq:
jq . some.json
and you get colors as a bonus (and way easier extendability).
Addendum: There is some confusion in the comments about using jq to process large JSON files on the one hand, and having a very large jq program on the other. For pretty-printing a file consisting of a single large JSON entity, the practical limitation is RAM. For pretty-printing a 2GB file consisting of a single array of real-world data, the "maximum resident set size" required for pretty-printing was 5GB (whether using jq 1.5 or 1.6). Note also that jq can be used from within python after pip install jq
.
The reason your attempt wasn't working, is because the two animations (fade-in and fade-out) were working against each other.
Right before an object became visible, it was still invisible and so the animation for fading-out would run. Then, the fraction of a second later when that same object had become visible, the fade-in animation would try to run, but the fade-out was still running. So they would work against each other and you would see nothing.
Eventually the object would become visible (most of the time), but it would take a while. And if you would scroll down by using the arrow-button at the button of the scrollbar, the animation would sort of work, because you would scroll using bigger increments, creating less scroll-events.
Enough explanation, the solution (JS, CSS, HTML):
$(window).on("load",function() {_x000D_
$(window).scroll(function() {_x000D_
var windowBottom = $(this).scrollTop() + $(this).innerHeight();_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
_x000D_
/* If the element is completely within bounds of the window, fade it in */_x000D_
if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}_x000D_
} else { //object goes out of view (scrolling up)_x000D_
if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}_x000D_
}_x000D_
});_x000D_
}).scroll(); //invoke scroll-handler on page-load_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
if ($(this).css("opacity")==0) {...}
. This makes sure the object is only faded in when the opacity
is 0
. Same goes for fading out. And this prevents the fade-in and fade-out from working against each other, because now there's ever only one of the two running at one time on an object..animate()
to .fadeTo()
. It's jQuery's specialized function for opacity, a lot shorter to write and probably lighter than animate..position()
to .offset()
. This always calculates relative to the body, whereas position is relative to the parent. For your case I believe offset is the way to go.$(window).height()
to $(window).innerHeight()
. The latter is more reliable in my experience.$(window).scroll();
. Now you can give all desired objects on the page the .fade
class, and objects that should be invisible at page-load, will be faded out immediately.#container
from both HTML and CSS, because (at least for this answer) it isn't necessary. (I thought maybe you needed the height:2000px
because you used .position()
instead of .offset()
, otherwise I don't know. Feel free of course to leave it in your code.)If you want opacity values other than 0
and 1
, use the following code:
$(window).on("load",function() {_x000D_
function fade(pageLoad) {_x000D_
var windowBottom = $(window).scrollTop() + $(window).innerHeight();_x000D_
var min = 0.3;_x000D_
var max = 0.7;_x000D_
var threshold = 0.01;_x000D_
_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
_x000D_
/* If the element is completely within bounds of the window, fade it in */_x000D_
if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
if ($(this).css("opacity")<=min+threshold || pageLoad) {$(this).fadeTo(500,max);}_x000D_
} else { //object goes out of view (scrolling up)_x000D_
if ($(this).css("opacity")>=max-threshold || pageLoad) {$(this).fadeTo(500,min);}_x000D_
}_x000D_
});_x000D_
} fade(true); //fade elements on page-load_x000D_
$(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
threshold
and for min/max
at the start of the function. In the rest of the function these variables are referenced. This way, if you ever want to change the values again, you only have to do it in one place.|| pageLoad
to the if-clause. This was necessary to make sure all objects are faded to the correct opacity on page-load. pageLoad
is a boolean that is send along as an argument when fade()
is invoked.function fade() {...}
, in order to be able to send along the pageLoad
boolean when the scroll-handler is invoked.Explanation:
The reason the code in your fiddle didn't work, is because the actual opacity values are always a little off from the value you set it to. So if you set the opacity to 0.3
, the actual value (in this case) is 0.300000011920929
. That's just one of those little bugs you have to learn along the way by trail and error. That's why this if-clause won't work: if ($(this).css("opacity") == 0.3) {...}
.
I added a threshold, to take that difference into account: == 0.3
becomes <= 0.31
.
(I've set the threshold to 0.01
, this can be changed of course, just as long as the actual opacity will fall between the set value and this threshold.)
The operators are now changed from ==
to <=
and >=
.
If you want to fade the elements based on their visible percentage, use the following code:
$(window).on("load",function() {_x000D_
function fade(pageLoad) {_x000D_
var windowTop=$(window).scrollTop(), windowBottom=windowTop+$(window).innerHeight();_x000D_
var min=0.3, max=0.7, threshold=0.01;_x000D_
_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectHeight=$(this).outerHeight(), objectTop=$(this).offset().top, objectBottom=$(this).offset().top+objectHeight;_x000D_
_x000D_
/* Fade element in/out based on its visible percentage */_x000D_
if (objectTop < windowTop) {_x000D_
if (objectBottom > windowTop) {$(this).fadeTo(0,min+((max-min)*((objectBottom-windowTop)/objectHeight)));}_x000D_
else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
} else if (objectBottom > windowBottom) {_x000D_
if (objectTop < windowBottom) {$(this).fadeTo(0,min+((max-min)*((windowBottom-objectTop)/objectHeight)));}_x000D_
else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
} else if ($(this).css("opacity")<=max-threshold || pageLoad) {$(this).fadeTo(0,max);}_x000D_
});_x000D_
} fade(true); //fade elements on page-load_x000D_
$(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
I like to use: ArgumentException
, ArgumentNullException
, and ArgumentOutOfRangeException
.
ArgumentException
– Something is wrong with the argument.ArgumentNullException
– Argument is null.ArgumentOutOfRangeException
– I don’t use this one much, but a common use is indexing into a collection, and giving an index which is to large.There are other options, too, that do not focus so much on the argument itself, but rather judge the call as a whole:
InvalidOperationException
– The argument might be OK, but not in the current state of the object. Credit goes to STW (previously Yoooder). Vote his answer up as well.NotSupportedException
– The arguments passed in are valid, but just not supported in this implementation. Imagine an FTP client, and you pass a command in that the client doesn’t support.The trick is to throw the exception that best expresses why the method cannot be called the way it is. Ideally, the exception should be detailed about what went wrong, why it is wrong, and how to fix it.
I love when error messages point to help, documentation, or other resources. For example, Microsoft did a good first step with their KB articles, e.g. “Why do I receive an "Operation aborted" error message when I visit a Web page in Internet Explorer?”. When you encounter the error, they point you to the KB article in the error message. What they don’t do well is that they don’t tell you, why specifically it failed.
Thanks to STW (ex Yoooder) again for the comments.
In response to your followup, I would throw an ArgumentOutOfRangeException
. Look at what MSDN says about this exception:
ArgumentOutOfRangeException
is thrown when a method is invoked and at least one of the arguments passed to the method is not null reference (Nothing
in Visual Basic) and does not contain a valid value.
So, in this case, you are passing a value, but that is not a valid value, since your range is 1–12. However, the way you document it makes it clear, what your API throws. Because although I might say ArgumentOutOfRangeException
, another developer might say ArgumentException
. Make it easy and document the behavior.
In response to the answer by Tatu I have created a quick jsFiddle for showcasing his solution:
http://jsfiddle.net/duwood/sTX7y/
HTML
<p>Paste excel data here:</p>
<textarea name="excel_data" style="width:250px;height:150px;"></textarea><br>
<input type="button" onclick="javascript:generateTable()" value="Genereate Table"/>
<br><br>
<p>Table data will appear below</p>
<hr>
<div id="excel_table"></div>
JS
function generateTable() {
var data = $('textarea[name=excel_data]').val();
console.log(data);
var rows = data.split("\n");
var table = $('<table />');
for(var y in rows) {
var cells = rows[y].split("\t");
var row = $('<tr />');
for(var x in cells) {
row.append('<td>'+cells[x]+'</td>');
}
table.append(row);
}
// Insert into DOM
$('#excel_table').html(table);
}
for some applications, for example google chrome, they store it under /opt. you can follow the above instruction using dpkg -l to get the correct naming then dpkg -L to get the detail.
hope it helps
Something better would be:
<Grid Width="Your-specified-value" >
<ScrollViewer>
<TextBlock Width="Auto" TextWrapping="Wrap" />
</ScrollViewer>
</Grid>
This makes sure that the text in your textblock does not overflow and overlap the elements below the textblock as may be the case if you do not use the grid. That happened to me when I tried other solutions even though the textblock was already in a grid with other elements. Keep in mind that the width of the textblock should be Auto and you should specify the desired with in the Grid element. I did this in my code and it works beautifully. HTH.
Adding to all the answers here, I thought to mention, a very specific reason/scenario where you might want to prefer to throw the exception from the class's Init
method and not from the Ctor (which off course is the preferred and more common approach).
I will mention in advance that this example (scenario) assumes that you don't use "smart pointers" (i.e.- std::unique_ptr
) for your class'
s pointer(s) data members.
So to the point: In case, you wish that the Dtor of your class will "take action" when you invoke it after (for this case) you catch the exception that your Init()
method threw - you MUST not throw the exception from the Ctor, cause a Dtor invocation for Ctor's are NOT invoked on "half-baked" objects.
See the below example to demonstrate my point:
#include <iostream>
using namespace std;
class A
{
public:
A(int a)
: m_a(a)
{
cout << "A::A - setting m_a to:" << m_a << endl;
}
~A()
{
cout << "A::~A" << endl;
}
int m_a;
};
class B
{
public:
B(int b)
: m_b(b)
{
cout << "B::B - setting m_b to:" << m_b << endl;
}
~B()
{
cout << "B::~B" << endl;
}
int m_b;
};
class C
{
public:
C(int a, int b, const string& str)
: m_a(nullptr)
, m_b(nullptr)
, m_str(str)
{
m_a = new A(a);
cout << "C::C - setting m_a to a newly A object created on the heap (address):" << m_a << endl;
if (b == 0)
{
throw exception("sample exception to simulate situation where m_b was not fully initialized in class C ctor");
}
m_b = new B(b);
cout << "C::C - setting m_b to a newly B object created on the heap (address):" << m_b << endl;
}
~C()
{
delete m_a;
delete m_b;
cout << "C::~C" << endl;
}
A* m_a;
B* m_b;
string m_str;
};
class D
{
public:
D()
: m_a(nullptr)
, m_b(nullptr)
{
cout << "D::D" << endl;
}
void InitD(int a, int b)
{
cout << "D::InitD" << endl;
m_a = new A(a);
throw exception("sample exception to simulate situation where m_b was not fully initialized in class D Init() method");
m_b = new B(b);
}
~D()
{
delete m_a;
delete m_b;
cout << "D::~D" << endl;
}
A* m_a;
B* m_b;
};
void item10Usage()
{
cout << "item10Usage - start" << endl;
// 1) invoke a normal creation of a C object - on the stack
// Due to the fact that C's ctor throws an exception - its dtor
// won't be invoked when we leave this scope
{
try
{
C c(1, 0, "str1");
}
catch (const exception& e)
{
cout << "item10Usage - caught an exception when trying to create a C object on the stack:" << e.what() << endl;
}
}
// 2) same as in 1) for a heap based C object - the explicit call to
// C's dtor (delete pc) won't have any effect
C* pc = 0;
try
{
pc = new C(1, 0, "str2");
}
catch (const exception& e)
{
cout << "item10Usage - caught an exception while trying to create a new C object on the heap:" << e.what() << endl;
delete pc; // 2a)
}
// 3) Here, on the other hand, the call to delete pd will indeed
// invoke D's dtor
D* pd = new D();
try
{
pd->InitD(1,0);
}
catch (const exception& e)
{
cout << "item10Usage - caught an exception while trying to init a D object:" << e.what() << endl;
delete pd;
}
cout << "\n \n item10Usage - end" << endl;
}
int main(int argc, char** argv)
{
cout << "main - start" << endl;
item10Usage();
cout << "\n \n main - end" << endl;
return 0;
}
I will mention again, that it is not the recommended approach, just wanted to share an additional point of view.
Also, as you might have seen from some of the print in the code - it is based on item 10 in the fantastic "More effective C++" by Scott Meyers (1st edition).
This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:
window.getSelection().anchorNode.textContent.substring(
window.getSelection().extentOffset,
window.getSelection().anchorOffset)
You will get the error on REFRESH_FAST, if you do not create materialized view logs for the master table(s) the query is referring to. If anyone is not familiar with materialized views or using it for the first time, the better way is to use oracle sqldeveloper and graphically put in the options, and the errors also provide much better sense.
The NetBeans documentation merely states a hierarchy for FileEncodingQuery (FEQ), suggesting that you can set encoding on a per-file basis:
Just for reference, this is the wiki-page regarding project-wide settings:
Html.Hidden and Html.HiddenFor used to generate name-value pairs which waited by action method in controller. Sample Usage(*):
@using (Html.BeginForm("RemoveFromCart", "Cart")) {
@Html.Hidden("ProductId", line.Product.ProductID)
@Html.HiddenFor(x => x.ReturnUrl)
<input class="btn btn-sm btn-warning"
type="submit" value="Remove" />
}
If your action method wait for "ProductId" you have to generate this name in form via using (Html.Hidden or Html.HiddenFor) For the case it is not possible to generate this name with strongly typed model you simple write this name with a string thats "ProductId".
public ViewResult RemoveFromCart(int productId, string returnUrl){...}
If I had written Html.HiddenFor(x => line.Product.ProductID), the helper would render a hidden field with the name "line.Product.ProductID". The name of the field would not match the names of the parameters for the "RemoveFromCart" action method which waiting the name of "ProductId". This would prevent the default model binders from working, so the MVC Framework would not be able to call the method.
*Adam Freeman (Apress - Pro ASP.Net MVC 5)
Another approach(Inside of $function
to asure that the each
is executed on document ready
):
var ids = [1,2];
$(function(){
$('.checkbox-wrapper>input[type="checkbox"]').each(function(i,item){
if(ids.indexOf($(item).data('id')) > -1){
$(item).prop("checked", "checked");
}
});
});
What is the n.fn.init[0], and why it is returned? Why are my two seemingly identical JQuery functions returning different things?
Answer: It seems that your elements are not in the DOM yet, when you are trying to find them. As @Rory McCrossan pointed out, the
length:0
means that it doesn't find any element based on your search criteria.
n.fn.init[0]
, lets look at the core of the Jquery Library:var jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context );
};
Looks familiar, right?, now in a minified version of jquery, this should looks like:
var n = function( selector, context ) {
return new n.fn.init( selector, context );
};
So when you use a selector you are creating an instance of the jquery function; when found an element based on the selector criteria it returns the matched elements; when the criteria does not match anything it returns the prototype object of the function.
a flexbox option - font awesome 4.7 and below
FA 4.x Hosted URL - https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css
div {_x000D_
display: inline-flex; /* make element size relative to content */_x000D_
align-items: center; /* vertical alignment of items */_x000D_
line-height: 40px; /* vertically size by height, line-height or padding */_x000D_
padding: 0px 10px; /* horizontal with padding-l/r */_x000D_
border: 1px solid #ccc;_x000D_
}_x000D_
_x000D_
/* unnecessary styling below, ignore */_x000D_
body {display: flex;justify-content: center;align-items: center;height: 100vh;}div i {margin-right: 10px;}div {background-color: hsla(0, 0%, 87%, 0.5);}div:hover {background-color: hsla(34, 100%, 52%, 0.5);cursor: pointer;}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<div>_x000D_
<i class='fa fa-2x fa-camera'></i>_x000D_
hello world_x000D_
</div>
_x000D_
fiddle
http://jsfiddle.net/Hastig/V7DLm/180/
using flex and font awesome 5
FA 5.x Hosted URL - https://use.fontawesome.com/releases/v5.0.8/js/all.js
div {_x000D_
display: inline-flex; /* make element size relative to content */_x000D_
align-items: center; /* vertical alignment of items */_x000D_
padding: 3px 10px; /* horizontal vertical position with padding */_x000D_
border: 1px solid #ccc;_x000D_
}_x000D_
.svg-inline--fa { /* target all FA icons */_x000D_
padding-right: 10px;_x000D_
}_x000D_
.icon-camera .svg-inline--fa { /* target specific icon */_x000D_
font-size: 50px;_x000D_
}_x000D_
/* unnecessary styling below, ignore */_x000D_
body {display: flex;justify-content: center;align-items: center;height: 100vh; flex-direction: column;}div{margin: 10px 0;}div {background-color: hsla(0, 0%, 87%, 0.5);}div:hover {background-color: hsla(212, 100%, 63%, 1);cursor: pointer;}
_x000D_
<script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>_x000D_
<div class="icon-camera">_x000D_
<i class='fas fa-camera'></i>_x000D_
hello world_x000D_
</div>_x000D_
<div class="icon-clock">_x000D_
<i class='fas fa-clock'></i>_x000D_
hello world_x000D_
</div>
_x000D_
fiddle
You don't need regex to split a string on whitespace:
In [1]: text = '''WYATT - Ranked # 855 with 0.006 %
...: XAVIER - Ranked # 587 with 0.013 %
...: YONG - Ranked # 921 with 0.006 %
...: YOUNG - Ranked # 807 with 0.007 %'''
In [2]: print '\n'.join(line.split()[0] for line in text.split('\n'))
WYATT
XAVIER
YONG
YOUNG
Android handles transparency across views and drawables (including PNG images) natively, so the scenario you describe (a partially transparent ImageView
in front of a Gallery
) is certainly possible.
If you're having problems it may be related to either the layout or your image. I've replicated the layout you describe and successfully achieved the effect you're after. Here's the exact layout I used.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallerylayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Gallery
android:id="@+id/overview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ImageView
android:id="@+id/navigmaske"
android:background="#0000"
android:src="@drawable/navigmask"
android:scaleType="fitXY"
android:layout_alignTop="@id/overview"
android:layout_alignBottom="@id/overview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
Note that I've changed the parent RelativeLayout
to a height and width of fill_parent
as is generally what you want for a main Activity. Then I've aligned the top and bottom of the ImageView
to the top and bottom of the Gallery
to ensure it's centered in front of it.
I've also explicitly set the background of the ImageView
to be transparent.
As for the image drawable itself, if you put the PNG file somewhere for me to look at I can use it in my project and see if it's responsible.
You need install Google play image, Android SDK -> SDK platforms --> check show Package details --> install Google play.
Nick Craver's comment is the simplest to avoid the error that occurs if the dialog has not yet been defined:
if ($('#elem').is(':visible')) {
// do something
}
You should set visibility in your CSS first though, using simply:
#elem { display: none; }
Microsoft API Code Pack. ShellObjectWatcher class.
might be very simple
for example
<script src="js/myscript.js?id=123"></script>
<script>
var queryString = $("script[src*='js/myscript.js']").attr('src').split('?')[1];
</script>
You can then convert query string into json like below
var json = $.parseJSON('{"'
+ queryString.replace(/&/g, '","').replace(/=/g, '":"')
+ '"}');
and then can use like
console.log(json.id);
look at
http://jtds.sourceforge.net/faq.html#driverImplementation
What is the URL format used by jTDS?
The URL format for jTDS is:
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
... domain Specifies the Windows domain to authenticate in. If present and the user name and password are provided, jTDS uses Windows (NTLM) authentication instead of the usual SQL Server authentication (i.e. the user and password provided are the domain user and password). This allows non-Windows clients to log in to servers which are only configured to accept Windows authentication.
If the domain parameter is present but no user name and password are provided, jTDS uses its native Single-Sign-On library and logs in with the logged Windows user's credentials (for this to work one would obviously need to be on Windows, logged into a domain, and also have the SSO library installed -- consult README.SSO in the distribution on how to do this).
Probably way too late but this is another option:
$('body').popover({
selector: '[rel=popover]',
trigger: 'hover',
html: true,
content: function () {
return $(this).parents('.row').first().find('.metaContainer').html();
}
});
I am using Android Studio 2.1 and I have better consistency of getting the lightbulb by clicking on the class Name and hover over it for a second.
I cannot reproduce the error.
Perhaps I'm not understanding the problem.
The following works fine for me in SQL Server 2005, with the extra "foo" column appearing in the second select result:
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
GO
CREATE TABLE #Results ( Company CHAR(3), StepId TINYINT, FieldId TINYINT )
GO
select company, stepid, fieldid from #Results
GO
ALTER TABLE #Results ADD foo VARCHAR(50) NULL
GO
select company, stepid, fieldid, foo from #Results
GO
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
GO
You can also use this syntax. For YYYY-MM-JJ HH-MM:
var now = DateTime.now();
var month = now.month.toString().padLeft(2, '0');
var day = now.day.toString().padLeft(2, '0');
var text = '${now.year}-$month-$day ${now.hour}:${now.minute}';
I think ./gradlew tasks
is same with Android studio sync
. Why? I will explain it.
I meet a problem when I test jacoco coverage report. When I run ./gradlew clean :Test:testDebugUnitTest
in command line directly , error appear.
Error opening zip file or JAR manifest missing : build/tmp/expandedArchives/org.jacoco.agent-0.8.2.jar_5bdiis3s7lm1rcnv0gawjjfxc/jacocoagent.jar
However, if I click android studio sync firstly , it runs OK. Because the build/../jacocoagent.jar
appear naturally.
I dont know why, maybe there is bug in jacoco plugin. Unit I find running .gradlew tasks
makes the jar appear as well. So I can get the same result in gralde script.
Besides, gradle --recompile-scripts
does not work for the problem.
void addToSpecific()
{
int n;
int f=0; //flag
Node *temp=H; //H-Head, T-Tail
if(NULL!=H)
{
cout<<"Enter the Number"<<endl;
cin>>n;
while(NULL!=(temp->getNext()))
{
if(n==(temp->getInfo()))
{
f=1;
break;
}
temp=temp->getNext();
}
}
if(NULL==H)
{
Node *nn=new Node();
nn->setInfo();
nn->setNext(NULL);
T=H=nn;
}
else if(0==f)
{
Node *nn=new Node();
nn->setInfo();
nn->setNext(NULL);
T->setNext(nn);
T=nn;
}
else if(1==f)
{
Node *nn=new Node();
nn->setInfo();
nn->setNext(NULL);
nn->setNext((temp->getNext()));
temp->setNext(nn);
}
}
.modal-body {
max-height: 80vh;
overflow-y: scroll;
}
it's works for me
Most of the answers are good , but i thought of adding some more links of MSDN for more information
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<rotate
android:fromDegrees="45"
android:toDegrees="45"
android:pivotX="-40%"
android:pivotY="87%" >
<shape
android:shape="rectangle" >
<stroke android:color="@android:color/transparent" android:width="0dp"/>
<solid
android:color="#fff" />
</shape>
</rotate>
</item>
</layer-list>
There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.
One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.
VisJS supports this with its Arrows example, that supports draggable elements.
It also supports editable connections, with its Interaction Events example.
jEdit:
With the keyboard: press Alt-\ (Opt-\ in Mac OS X) to toggle between rectangular and normal selection mode; then use Shift plus arrow keys to extend selection. You can switch back to regular selection mode with another Alt-\ (Opt-\ in Mac OS X), if desired.
With the mouse: Either use Alt-\ (Opt-\ in Mac OS X) as above to toggle rectangular selection mode, then drag as usual; or Ctrl-drag (Cmd-drag in Mac OS X). You can switch back to regular selection mode with another Alt-\ (Opt-\ in Mac OS X), if desired.
Actually, you can even make a non-rectangular selection the normal way and then hit Alt-\ (Opt-\ in Mac OS X) to convert it into a rectangular one.