In my case the problem was the docker networks ip allocation range, see this post for details
I found the solution. I misplaced the path to the keystore.jks
file.
Searched for the file on my computer used that path and everything worked great.
You need to do the following:
public class CountryInfoResponse {
@JsonProperty("geonames")
private List<Country> countries;
//getter - setter
}
RestTemplate restTemplate = new RestTemplate();
List<Country> countries = restTemplate.getForObject("http://api.geonames.org/countryInfoJSON?username=volodiaL",CountryInfoResponse.class).getCountries();
It would be great if you could use some kind of annotation to allow you to skip levels, but it's not yet possible (see this and this)
It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.
Other than that, I would suggest two things...
First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...
ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0
Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.
I had the same problem, but with small difference. I had added NetworkConnectionCallback to check situation when internet connection had changed at runtime, and checking like this before sending all requests:
private fun isConnected(): Boolean {
val activeNetwork = cManager.activeNetworkInfo
return activeNetwork != null && activeNetwork.isConnected
}
There can be state like CONNECTING (you can see i? when you turn on wifi, icon starts blinking, after connecting to network, image is static). So, we have two different states: one CONNECT another CONNECTING, and when Retrofit tried to send request internet connection is disabled and it throws UnknownHostException. I forgot to add another type of exception in function which was responsible for sending requests.
try{
//for example, retrofit call
}
catch (e: Exception) {
is UnknownHostException -> "Unknown host!"
is ConnectException -> "No internet!"
else -> "Unknown exception!"
}
It's just a tricky moment that can by related with this problem.
Hope, I will help somebody)
Adding another answer that uses switch
... There are more comprehensive examples out there, but this will give you the idea.
In example, t
becomes the specified data type within each case
scope. Note, you have to provide a case
for only one type at a type, otherwise t
remains an interface
.
package main
import "fmt"
func main() {
var val interface{} // your starting value
val = 4
var i int // your final value
switch t := val.(type) {
case int:
fmt.Printf("%d == %T\n", t, t)
i = t
case int8:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case int16:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case int32:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case int64:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case bool:
fmt.Printf("%t == %T\n", t, t)
// // not covertible unless...
// if t {
// i = 1
// } else {
// i = 0
// }
case float32:
fmt.Printf("%g == %T\n", t, t)
i = int(t) // standardizes across systems
case float64:
fmt.Printf("%f == %T\n", t, t)
i = int(t) // standardizes across systems
case uint8:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case uint16:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case uint32:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case uint64:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case string:
fmt.Printf("%s == %T\n", t, t)
// gets a little messy...
default:
// what is it then?
fmt.Printf("%v == %T\n", t, t)
}
fmt.Printf("i == %d\n", i)
}
When you have android studio make your signed apk file it uses
<property name="ExportedApkPath" value="$PROJECT_DIR$/PROJNAME/APPNAME.apk" />
inside workspace.xml to find out where to place it. However, if you use ./gradlew assembleRelease
it places it inside PROJNAME/build/apk. I have the same problem. For some reason my android studio will not show me anything inside the apk subdirectory so the apk is for all intents and purposes missing. But if you search with finder it's most definitely there.
Just like Tom mentioned. When you start with capital A
then autocomplete will complete it as.
ANDROID.PERMISSION.INTERNET
When you start typing with a
then autocomplete will complete it as
android.permission.INTERNET
The second one is the correct one.
tv.setText( a1 + " ");
This will resolve your problem.
It looks like IDEA solves this for you (like everything else). When loading a large project and letting it thrash, it will open a dialog to up the memory settings. Entering 2048 for Xmx and clicking "Shutdown", then restarting IDEA makes IDEA start up with more memory. This seems to work well for Mac OS, though it never seems to persist for me on Windows (not sure about IDEA 12).
Use below code to generate files on fly..
<? //Generate text file on the fly
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=savethis.txt");
// do your Db stuff here to get the content into $content
print "This is some text...\n";
print $content;
?>
->DECLARE co_id INT ;
->DECLARE sname VARCHAR(10) ;
->SELECT course_id INTO co_id FROM course_details ;
->SELECT student_name INTO sname FROM course_details;
->DECLARE val1 int;
->DECLARE val2 int;
->SELECT student__id,student_name INTO val1,val2 FROM student_details;
--HAPPY CODING--
Sets the editor data. The data must be provided in the raw format (HTML). CKEDITOR.instances.editor1.setData( 'Put your Data.' ); refer this page
String formatting using %
is a great way to handle this. Here are some examples.
The formatting code '%s'
converts '12345'
to a string, but it's already a string.
>>> '%s' % '12345'
'12345'
'%.3s'
specifies to use only the first three characters.
>>> '%.3s' % '12345'
'123'
'%.7s'
says to use the first seven characters, but there are only five. No problem.
>>> '%.7s' % '12345'
'12345'
'%7s'
uses up to seven characters, filling missing characters with spaces on the left.
>>> '%7s' % '12345'
' 12345'
'%-7s'
is the same thing, except filling missing characters on the right.
>>> '%-7s' % '12345'
'12345 '
'%5.3'
says use the first three characters, but fill it with spaces on the left to total five characters.
>>> '%5.3s' % '12345'
' 123'
Same thing except filling on the right.
>>> '%-5.3s' % '12345'
'123 '
Can handle multiple arguments too!
>>> 'do u no %-4.3sda%3.2s wae' % ('12345', 6789)
'do u no 123 da 67 wae'
If you require even more flexibility, str.format()
is available too. Here is documentation for both.
You should be able to use crypt
, mcrypt
, or gpg
to meet your needs. They all support a number of algorithms. crypt
is a bit outdated though.
More info:
Your and
should be a &&
in the where
clause.
where epl.DepartAirportAfter > sd.UTCDepartureTime
and epl.ArriveAirportBy > sd.UTCArrivalTime
should be
where epl.DepartAirportAfter > sd.UTCDepartureTime
&& epl.ArriveAirportBy > sd.UTCArrivalTime
While it is possible to combine the results, I would advise against doing so.
You have two fundamentally different types of queries that return a different number of rows, a different number of columns and different types of data. It would be best to leave it as it is - two separate queries.
In my case (where none of the proposed solutions fit), the problem was I used async/await
where the signature for main
method looked this way:
static async void Main(string[] args)
I simply removed async
so the main
method looked this way:
static void Main(string[] args)
I also removed all instances of await
and used .Result
for async calls, so my console application could compile happily.
Use split()
let mut split = "some string 123 ffd".split("123");
This gives an iterator, which you can loop over, or collect()
into a vector.
for s in split {
println!("{}", s)
}
let vec = split.collect::<Vec<&str>>();
// OR
let vec: Vec<&str> = split.collect();
In my case, after installing AspNetCore.2.0.6.RuntimePackageStore_x64.exe
and DotNetCore.2.0.6-WindowsHosting.exe
, I need to restart server to make it worked without 502 bad gateway and proxy error.
UPDATE:
There is a way you could use it without restart: https://stackoverflow.com/a/50808634/3634867
os.path.exists(path) Returns True if path refers to an existing path. An existing path can be regular files (http://en.wikipedia.org/wiki/Unix_file_types#Regular_file), but also special files (e.g. a directory). So in essence this function returns true if the path provided exists in the filesystem in whatever form (notwithstanding a few exceptions such as broken symlinks).
os.path.isdir(path) in turn will only return true when the path points to a directory
You don't need "string" in your call to wordLengthFunction()
.
int wordLength = wordLengthFunction(string word);
should be
int wordLength = wordLengthFunction(word);
For clarity in this topic, a few points really should be made:
Sharpening images is an ill-posed problem. In other words, blurring is a lossy operation, and going back from it is in general not possible.
To sharpen single images, you need to somehow add constraints (assumptions) on what kind of image it is you want, and how it has become blurred. This is the area of natural image statistics. Approaches to do sharpening hold these statistics explicitly or implicitly in their algorithms (deep learning being the most implicitly coded ones). The common approach of up-weighting some of the levels of a DOG or Laplacian pyramid decomposition, which is the generalization of Brian Burns answer, assumes that a Gaussian blurring corrupted the image, and how the weighting is done is connected to assumptions on what was in the image to begin with.
Other sources of information can render the problem sharpening well-posed. Common such sources of information is video of a moving object, or multi-view setting. Sharpening in that setting is usually called super-resolution (which is a very bad name for it, but it has stuck in academic circles). There has been super-resolution methods in OpenCV since a long time.... although they usually dont work that well for real problems last I checked them out. I expect deep learning has produced some wonderful results here as well. Maybe someone will post in remarks on whats worthwhile out there.
git add . (add all files in this directory)
git add -all (add all files in all directories)
git add -N can be helpful for for listing which ones for later....
I know my solution is not very popular from the pythonic point of view, but I prefer to use the Java approach of one module->one class, with the module named as the class. I do understand the reason behind the python style, but I am not too fond of having a very large file containing a lot of classes. I find it difficult to browse, despite folding.
Another reason is version control: having a large file means that your commits tend to concentrate on that file. This can potentially lead to a higher quantity of conflicts to be resolved. You also loose the additional log information that your commit modifies specific files (therefore involving specific classes). Instead you see a modification to the module file, with only the commit comment to understand what modification has been done.
Summing up, if you prefer the python philosophy, go for the suggestions of the other posts. If you instead prefer the java-like philosophy, create a Nib.py containing class Nib.
Option 2 is correct: The nested <ul>
is a child of the <li>
it belongs in.
If you validate, option 1 comes up as an error in html 5 -- credit: user3272456
<ul>
as child of <li>
The proper way to make HTML nested list is with the nested <ul>
as a child of the <li>
to which it belongs. The nested list should be inside of the <li>
element of the list in which it is nested.
<ul>
<li>Parent/Item
<ul>
<li>Child/Subitem
</li>
</ul>
</li>
</ul>
A list item can contain another entire list — this is known as "nesting" a list. It is useful for things like tables of contents, such as the one at the start of this article:
- Chapter One
- Section One
- Section Two
- Section Three
- Chapter Two
- Chapter Three
The key to nesting lists is to remember that the nested list should relate to one specific list item. To reflect that in the code, the nested list is contained inside that list item. The code for the list above looks something like this:
<ol>
<li>Chapter One
<ol>
<li>Section One</li>
<li>Section Two </li>
<li>Section Three </li>
</ol>
</li>
<li>Chapter Two</li>
<li>Chapter Three </li>
</ol>
Note how the nested list starts after the <li>
and the text of the containing list item (“Chapter One”); then ends before the </li>
of the containing list item. Nested lists often form the basis for website navigation menus, as they are a good way to define the hierarchical structure of the website.
Theoretically you can nest as many lists as you like, although in practice it can become confusing to nest lists too deeply. For very large lists, you may be better off splitting the content up into several lists with headings instead, or even splitting it up into separate pages.
Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.
Java 8's stream()
interface provides a great way to update a list in place.
To safely update items in the list, use map()
:
List<String> letters = new ArrayList<>();
// add stuff to list
letters = letters.stream().map(x -> "D").collect(Collectors.toList());
To safely remove items in place, use filter()
:
letters.stream().filter(x -> !x.equals("A")).collect(Collectors.toList());
int number = 534;
int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
You can also pass the init parameters to the instance variables by position
# Abstract struct class
class Struct:
def __init__ (self, *argv, **argd):
if len(argd):
# Update by dictionary
self.__dict__.update (argd)
else:
# Update by position
attrs = filter (lambda x: x[0:2] != "__", dir(self))
for n in range(len(argv)):
setattr(self, attrs[n], argv[n])
# Specific class
class Point3dStruct (Struct):
x = 0
y = 0
z = 0
pt1 = Point3dStruct()
pt1.x = 10
print pt1.x
print "-"*10
pt2 = Point3dStruct(5, 6)
print pt2.x, pt2.y
print "-"*10
pt3 = Point3dStruct (x=1, y=2, z=3)
print pt3.x, pt3.y, pt3.z
print "-"*10
Right Click On Project -> Open Module Settings -> Click SDK's
Choose Java Home Directory
select email, count(*) as c FROM orders GROUP BY email
class SuperType {
public static void classMethod(){
System.out.println("Super type class method");
}
public void instancemethod(){
System.out.println("Super Type instance method");
}
}
public class SubType extends SuperType{
public static void classMethod(){
System.out.println("Sub type class method");
}
public void instancemethod(){
System.out.println("Sub Type instance method");
}
public static void main(String args[]){
SubType s=new SubType();
SuperType su=s;
SuperType.classMethod();// Prints.....Super type class method
su.classMethod(); //Prints.....Super type class method
SubType.classMethod(); //Prints.....Sub type class method
}
}
This example for static method overriding
Note: if we call a static method with object reference, then reference type(class) static method will be called, not object class static method.
Static method belongs to class only.
declare a double value and convert to long convert to string and formated to float the double value finally replace all the value like 123456789,0000 to 123456789
Double value = double value ;
Long longValue = value.longValue(); String strCellValue1 = new String(longValue.toString().format("%f",value).replaceAll("\\,?0*$", ""));
Here is one aditional free Floating Action Button library for Android. It has many customizations and requires SDK version 9 and higher
dependencies {
compile 'com.scalified:fab:1.1.2'
}
"ll" worked best for me, see:
http://mapki.com/wiki/Google_Map_Parameters (query reference)
it shall not be too hard to convert minutes, seconds to decimal
http://en.wikipedia.org/wiki/Decimal_degrees
for a marker, possibly the best would be ?q=Description@lat,long
You can do this with a list comprehension and index()
tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
[x[0] for x in tuple_list].index("kumquat")
2
[x[1] for x in tuple_list].index(7)
1
I'm not sure it is the most efficient way, but It works for me
Public Function RemoverTildes(stIn As String) As String
Dim stFormD As String = stIn.Normalize(NormalizationForm.FormD)
Dim sb As New StringBuilder()
For ich As Integer = 0 To stFormD.Length - 1
Dim uc As UnicodeCategory = CharUnicodeInfo.GetUnicodeCategory(stFormD(ich))
If uc <> UnicodeCategory.NonSpacingMark Then
sb.Append(stFormD(ich))
End If
Next
Return (sb.ToString().Normalize(NormalizationForm.FormC))
End Function
if you're more technically minded, this site is probably what you want: http://www.zytrax.com/tech/survival/ssl.html
warning: the rabbit hole goes deep :).
The "escape hatch" operation that lets you do weird things that are not otherwise supported by streams is to ask for an Iterator
:
Iterator<T> it = users.stream().filter((user) -> user.getId() < 0).iterator();
if (!it.hasNext())
throw new NoSuchElementException();
else {
result = it.next();
if (it.hasNext())
throw new TooManyElementsException();
}
Guava has a convenience method to take an Iterator
and get the only element, throwing if there are zero or multiple elements, which could replace the bottom n-1 lines here.
Actually if you create func:
create function p1() returns INTEGER DETERMINISTIC NO SQL return @p1;
and view:
create view h_parm as
select * from sw_hardware_big where unit_id = p1() ;
Then you can call a view with a parameter:
select s.* from (select @p1:=12 p) parm , h_parm s;
I hope it helps.
Why not disecting a bare minimum authentication module?
SweetAuth
https://www.npmjs.com/package/sweet-auth
It's simple as:
app.get('/private-page', (req, res) => {
if (req.user.isAuthorized) {
// user is logged in! send the requested page
// you can access req.user.email
}
else {
// user not logged in. redirect to login page
}
})
The answer shared by Paul is the best one. To expand more,
There can be only one default export per file. Whereas there can be more than one const exports. The default variable can be imported with any name, whereas const variable can be imported with it's particular name.
var message2 = 'I am exported';
export default message2;
export const message = 'I am also exported'
At the imports side we need to import it like this:
import { message } from './test';
or
import message from './test';
With the first import, the const variable is imported whereas, with the second one, the default one will be imported.
Another alternative. I prefer this approach because it is less writing but the two accomplish the same thing.
IF COLUMNPROPERTY(OBJECT_ID('dbo.Person'), 'ColumnName', 'ColumnId') IS NULL
BEGIN
ALTER TABLE Person
ADD ColumnName VARCHAR(MAX) NOT NULL
END
I also noticed yours is looking for where table does exist that is obviously just this
if COLUMNPROPERTY( OBJECT_ID('dbo.Person'),'ColumnName','ColumnId') is not null
The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH
clause. See this article for one example of translating a CONNECT BY
into a WITH
(technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.
Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:
CREATE TABLE emp(empid INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(10),
salary DECIMAL(9, 2),
mgrid INTEGER);
where mgrid
references an employee's manager's empid
, the task is, get the names of everybody who reports directly or indirectly to Joan
. In Oracle, that's a simple CONNECT
:
SELECT name
FROM emp
START WITH name = 'Joan'
CONNECT BY PRIOR empid = mgrid
In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):
WITH n(empid, name) AS
(SELECT empid, name
FROM emp
WHERE name = 'Joan'
UNION ALL
SELECT nplus1.empid, nplus1.name
FROM emp as nplus1, n
WHERE n.empid = nplus1.mgrid)
SELECT name FROM n
Oracle's START WITH
clause becomes the first nested SELECT
, the base case of the recursion, to be UNION
ed with the recursive part which is just another SELECT
.
SQL Server's specific flavor of WITH
is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.
This is possible with useState
or useReducer
, since useState
uses useReducer
internally:
const [, updateState] = React.useState();
const forceUpdate = React.useCallback(() => updateState({}), []);
forceUpdate
isn't intended to be used under normal circumstances, only in testing or other outstanding cases. This situation may be addressed in a more conventional way.
setCount
is an example of improperly used forceUpdate
, setState
is asynchronous for performance reasons and shouldn't be forced to be synchronous just because state updates weren't performed correctly. If a state relies on previously set state, this should be done with updater function,
If you need to set the state based on the previous state, read about the updater argument below.
<...>
Both state and props received by the updater function are guaranteed to be up-to-date. The output of the updater is shallowly merged with state.
setCount
may not be an illustrative example because its purpose is unclear but this is the case for updater function:
setCount(){
this.setState(({count}) => ({ count: count + 1 }));
this.setState(({count2}) => ({ count2: count + 1 }));
this.setState(({count}) => ({ count2: count + 1 }));
}
This is translated 1:1 to hooks, with the exception that functions that are used as callbacks should better be memoized:
const [state, setState] = useState({ count: 0, count2: 100 });
const setCount = useCallback(() => {
setState(({count}) => ({ count: count + 1 }));
setState(({count2}) => ({ count2: count + 1 }));
setState(({count}) => ({ count2: count + 1 }));
}, []);
Framework will handle switching the views for you once you setup your cell's backgroundView
and selectedBackgroundView
, see example from Managing the Visual State for Selections and Highlights:
UIView* backgroundView = [[UIView alloc] initWithFrame:self.bounds];
backgroundView.backgroundColor = [UIColor redColor];
self.backgroundView = backgroundView;
UIView* selectedBGView = [[UIView alloc] initWithFrame:self.bounds];
selectedBGView.backgroundColor = [UIColor whiteColor];
self.selectedBackgroundView = selectedBGView;
you only need in your class that implements UICollectionViewDelegate
enable cells to be highlighted and selected like this:
- (BOOL)collectionView:(UICollectionView *)collectionView
shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (BOOL)collectionView:(UICollectionView *)collectionView
shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath;
{
return YES;
}
This works me.
bool containsCharacter = test.IndexOf("s", StringComparison.OrdinalIgnoreCase) >= 0;
if your list looks like this: [1,2,3] you can do:
lst = [1,2,3]
df = pd.DataFrame([lst])
df.columns =['col1','col2','col3']
df
to get this:
col1 col2 col3
0 1 2 3
alternatively you can create a column as follows:
import numpy as np
df = pd.DataFrame(np.array([lst]).T)
df.columns =['col1']
df
to get this:
col1
0 1
1 2
2 3
I did it with transparent *.cur 1px to 1px, but it looks like small dot. :( I think it's the best cross-browser thing that I can do. CSS2.1 has no value 'none' for 'cursor' property - it was added in CSS3. Thats why it's workable not everywhere.
I am not sure if you are trying to create a remote branch from a local branch or vice versa, so I've outlined both scenarios as well as provided information on merging the remote and local branches.
Creating a remote called "github":
git remote add github git://github.com/jdoe/coolapp.git
git fetch github
List all remote branches:
git branch -r
github/gh-pages
github/master
github/next
github/pu
Create a new local branch (test) from a github's remote branch (pu):
git branch test github/pu
git checkout test
Merge changes from github's remote branch (pu) with local branch (test):
git fetch github
git checkout test
git merge github/pu
Update github's remote branch (pu) from a local branch (test):
git push github test:pu
Creating a new branch on a remote uses the same syntax as updating a remote branch. For example, create new remote branch (beta) on github from local branch (test):
git push github test:beta
Delete remote branch (pu) from github:
git push github :pu
To support SDK version >= 26, you also should build NotificationChanel and set a vibration pattern and sound there. There is a Kotlin code sample:
val vibrationPattern = longArrayOf(500)
val soundUri = "<your sound uri>"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val attr = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
val channelName: CharSequence = Constants.NOTIFICATION_CHANNEL_NAME
val importance = NotificationManager.IMPORTANCE_HIGH
val notificationChannel =
NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, channelName, importance)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationChannel.setSound(soundUri, attr)
notificationChannel.vibrationPattern = vibrationPattern
notificationManager.createNotificationChannel(notificationChannel)
}
And this is the builder:
with(NotificationCompat.Builder(applicationContext, Constants.NOTIFICATION_CHANNEL_ID)) {
setContentTitle("Some title")
setContentText("Some content")
setSmallIcon(R.drawable.ic_logo)
setAutoCancel(true)
setVibrate(vibrationPattern)
setSound(soundUri)
setDefaults(Notification.DEFAULT_VIBRATE)
setContentIntent(
// this is an extension function of context you should build
// your own pending intent and place it here
createNotificationPendingIntent(
Intent(applicationContext, target).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
)
)
return build()
}
Be sure your AudioAttributes
are chosen right to read more here.
var json = {"ListID" : "1", "ItemName":"test"};
$.ajax({
url: url,
type: 'POST',
data: username,
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
console.log("Success")
},
error : function(xhr, status, error) {
console.log("error")
}
);
A simple case that generates this error message:
In [8]: [1,2,3,4,5][np.array([1])]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-55def8e1923d> in <module>()
----> 1 [1,2,3,4,5][np.array([1])]
TypeError: only integer scalar arrays can be converted to a scalar index
Some variations that work:
In [9]: [1,2,3,4,5][np.array(1)] # this is a 0d array index
Out[9]: 2
In [10]: [1,2,3,4,5][np.array([1]).item()]
Out[10]: 2
In [11]: np.array([1,2,3,4,5])[np.array([1])]
Out[11]: array([2])
Basic python list indexing is more restrictive than numpy's:
In [12]: [1,2,3,4,5][[1]]
....
TypeError: list indices must be integers or slices, not list
Looking again at
indices = np.random.choice(range(len(X_train)), replace=False, size=50000, p=train_probs)
indices
is a 1d array of integers - but it certainly isn't scalar. It's an array of 50000 integers. List's cannot be indexed with multiple indices at once, regardless of whether they are in a list or array.
Pass by pointer is the only way you could pass "by reference" in C, so you still see it used quite a bit.
The NULL pointer is a handy convention for saying a parameter is unused or not valid, so use a pointer in that case.
References can't be updated once they're set, so use a pointer if you ever need to reassign it.
Prefer a reference in every case where there isn't a good reason not to. Make it const
if you can.
You can do something like this, than you you'll access the native mongodb functions inside mongoose:
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/local');
var connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function () {
connection.db.collection("YourCollectionName", function(err, collection){
collection.find({}).toArray(function(err, data){
console.log(data); // it will print your collection data
})
});
});
I prefer custom NavigationController rather than setting global ui, or put in ViewController.
Here is my solution
class AppNavigationController : UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
}
}
extension AppNavigationController : UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
let backButtonItem = UIBarButtonItem(
title: " ",
style: UIBarButtonItem.Style.plain,
target: nil,
action: nil)
backButtonItem.tintColor = UIColor.gray
viewController.navigationItem.backBarButtonItem = backButtonItem
}
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
}
}
Also you don't need to mess with Apple Api like EKEventEditViewController,PickerViewController and so on if you use global settings ui like UIBarButtonItem.appearance().tintColor = .white
If you don't know that you want to insert it at position #3, but you know the key that you want to insert it after, I cooked up this little function after seeing this question.
/**
* Inserts any number of scalars or arrays at the point
* in the haystack immediately after the search key ($needle) was found,
* or at the end if the needle is not found or not supplied.
* Modifies $haystack in place.
* @param array &$haystack the associative array to search. This will be modified by the function
* @param string $needle the key to search for
* @param mixed $stuff one or more arrays or scalars to be inserted into $haystack
* @return int the index at which $needle was found
*/
function array_insert_after(&$haystack, $needle = '', $stuff){
if (! is_array($haystack) ) return $haystack;
$new_array = array();
for ($i = 2; $i < func_num_args(); ++$i){
$arg = func_get_arg($i);
if (is_array($arg)) $new_array = array_merge($new_array, $arg);
else $new_array[] = $arg;
}
$i = 0;
foreach($haystack as $key => $value){
++$i;
if ($key == $needle) break;
}
$haystack = array_merge(array_slice($haystack, 0, $i, true), $new_array, array_slice($haystack, $i, null, true));
return $i;
}
Here's a codepad fiddle to see it in action: http://codepad.org/5WlKFKfz
Note: array_splice() would have been a lot more efficient than array_merge(array_slice()) but then the keys of your inserted arrays would have been lost. Sigh.
If you are sure jQuery is included try replacing $ with jQuery and try again.
Something like
jQuery(document).ready(function(){..
Still if you are getting error, you haven't included jQuery.
The options already listed are very good, however here a few more on this topic that I've researched and came across.
1) http://perfectionkills.com/exploring-canvas-drawing-techniques/
2) http://mcc.id.au/2010/signature.html
3) https://zipso.net/a-simple-touchscreen-sketchpad-using-javascript-and-html5/
And as always you may want to save the canvas to image:
http://www.html5canvastutorials.com/advanced/html5-canvas-save-drawing-as-an-image/
good luck and happy signing
Take a look at numpy.reshape .
>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)
>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape
# (5000, 25)
# One shape dimension can be -1.
# In this case, the value is inferred from
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)
Old question but nowadays CSS3 makes vertical alignment really simple!
Just add to the <div>
this css:
display:flex;
align-items:center;
justify-content:center;
Live Example:
.img_thumb {_x000D_
float: left;_x000D_
height: 120px;_x000D_
margin-bottom: 5px;_x000D_
margin-left: 9px;_x000D_
position: relative;_x000D_
width: 147px;_x000D_
background-color: rgba(0, 0, 0, 0.5);_x000D_
border-radius: 3px;_x000D_
display:flex;_x000D_
align-items:center;_x000D_
justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
<a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
<img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
</a>_x000D_
</div>
_x000D_
The clearest answer. Does “X& const x” make any sense?
No, it is nonsense
To find out what the above declaration means, read it right-to-left: “x is a const reference to a X”. But that is redundant — references are always const, in the sense that you can never reseat a reference to make it refer to a different object. Never. With or without the const.
In other words, “X& const x” is functionally equivalent to “X& x”. Since you’re gaining nothing by adding the const after the &, you shouldn’t add it: it will confuse people — the const will make some people think that the X is const, as if you had said “const X& x”.
I was only losing the session which was not a string or integer but a datarow. Putting the data in a serializable object and saving that into the session worked for me.
catch
ing in this fashion, in my experience, is dangerous. Any error thrown in the entire stack will be caught, not just an error from this promise (which is probably not what you want).
The second argument to a promise is already a rejection/failure callback. It's better and safer to use that instead.
Here's a typescript typesafe one-liner I wrote to handle this:
function wait<R, E>(promise: Promise<R>): [R | null, E | null] {
return (promise.then((data: R) => [data, null], (err: E) => [null, err]) as any) as [R, E];
}
// Usage
const [currUser, currUserError] = await wait<GetCurrentUser_user, GetCurrentUser_errors>(
apiClient.getCurrentUser()
);
This one-liner should work too:
(cd /path/to/your/app && npm start)
Note that the current directory will be changed to /path/to/your/app after executing this command. To preserve the working directory:
(cd /path/to/your/app && npm start && cd -)
I used this solution because a program configuration file I was editing back then didn't support specifying command line arguments.
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.
It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.
I had the same problem and I solved it with the following steps
Complete all the installation steps and restart Eclipse. You'll see a bunch of servers when you try to add a server runtime environment.
I've lead a few design patterns discussion groups (our site) and have read 5 or 6 patterns books. I recommend starting with the Head First Design Patterns book and attending or starting a discussion group. The Head First book might look a little Hasboro at first, but most people like it after reading a chapter or two.
Use the outstanding resource - Joshua Kereivisky's A Learning Guide to Design Patterns for the pattern ordering and to help your discussion group. Out of experience the one change I suggest to the ordering is to put Strategy first. Most of today's developers have experienced some good or bad incarnation of a Factory, so starting with Factory can lead to a lot of conversation and confusion about the pattern.This tends to take focus off how to study and learn patterns which is pretty essential at that first meeting.
I was interested to see that the original poster used a style that avoided early exits. Single Entry; Single Exit (SESE) is an interesting style that I've not really explored. It's late and I've got a bottle of cider, so I've written a solution (not tested) without an early exit.
I should have used an iterator. Unfortunately java.util.Iterator
has a side-effect in the get method. (I don't like the Iterator
design due to its exception ramifications.)
private Dog findDog(int id) {
int i = 0;
for (; i!=dogs.length() && dogs.get(i).getID()!=id; ++i) {
;
}
return i!=dogs.length() ? dogs.get(i) : null;
}
Note the duplication of the i!=dogs.length()
expression (could have chosen dogs.get(i).getID()!=id
).
var upload = multer({dest: "./uploads"});
var mongo = require('mongodb');
var Grid = require("gridfs-stream");
Grid.mongo = mongo;
router.post('/:id', upload.array('photos', 200), function(req, res, next){
gfs = Grid(db);
var ss = req.files;
for(var j=0; j<ss.length; j++){
var originalName = ss[j].originalname;
var filename = ss[j].filename;
var writestream = gfs.createWriteStream({
filename: originalName
});
fs.createReadStream("./uploads/" + filename).pipe(writestream);
}
});
In your view:
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="photos">
With this code you can add single as well as multiple images in MongoDB.
I just discovered that LNK2019
occurs during compilation in Visual Studio 2015 if forgetting to provide a definition for a declared function inside a class.
The linker error was highly cryptic, but I narrowed it down to what was missing by reading through the error and provided the definition outside the class to clear this up.
I’ve been struggling with this for a while now. Dycey’s solution is correct in that specifying the src
multiple times outputs the same thing in your css file. However, this seems to break in OSX Firefox 23 (probably other versions too, but I don’t have time to test).
The cross-browser @font-face
solution from Font Squirrel looks like this:
@font-face {
font-family: 'fontname';
src: url('fontname.eot');
src: url('fontname.eot?#iefix') format('embedded-opentype'),
url('fontname.woff') format('woff'),
url('fontname.ttf') format('truetype'),
url('fontname.svg#fontname') format('svg');
font-weight: normal;
font-style: normal;
}
To produce the src
property with the comma-separated values, you need to write all of the values on one line, since line-breaks are not supported in Sass. To produce the above declaration, you would write the following Sass:
@font-face
font-family: 'fontname'
src: url('fontname.eot')
src: url('fontname.eot?#iefix') format('embedded-opentype'), url('fontname.woff') format('woff'), url('fontname.ttf') format('truetype'), url('fontname.svg#fontname') format('svg')
font-weight: normal
font-style: normal
I think it seems silly to write out the path a bunch of times, and I don’t like overly long lines in my code, so I worked around it by writing this mixin:
=font-face($family, $path, $svg, $weight: normal, $style: normal)
@font-face
font-family: $family
src: url('#{$path}.eot')
src: url('#{$path}.eot?#iefix') format('embedded-opentype'), url('#{$path}.woff') format('woff'), url('#{$path}.ttf') format('truetype'), url('#{$path}.svg##{$svg}') format('svg')
font-weight: $weight
font-style: $style
Usage: For example, I can use the previous mixin to setup up the Frutiger Light font like this:
+font-face('frutigerlight', '../fonts/frutilig-webfont', 'frutigerlight')
Pickle uses different protocols
to convert your data to a binary stream.
In python 2 there are 3 different protocols (0
, 1
, 2
) and the default is 0
.
In python 3 there are 5 different protocols (0
, 1
, 2
, 3
, 4
) and the default is 3
.
You must specify in python 3 a protocol lower than 3
in order to be able to load the data in python 2. You can specify the protocol
parameter when invoking pickle.dump
.
If you want an inbuilt function to dump your data into some github markdown, you now have one. Take a look at to_markdown
:
df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}, index=['a', 'a', 'b'])
print(df.to_markdown())
| | A | B |
|:---|----:|----:|
| a | 1 | 1 |
| a | 2 | 2 |
| b | 3 | 3 |
Here's what that looks like on github:
Note that you will still need to have the tabulate
package installed.
Solved: The problem lies here:
I set POST
via both _CUSTOMREQUEST
and _POST
and the _CUSTOMREQUEST
persisted as POST
while _POST
switched to _HTTPGET
. The Server assumed the header from _CUSTOMREQUEST
to be the right one and came back with a 411.
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');
Well, you're going to have to check for null somewhere. You could do something like this:
from item in db.vw_Dropship_OrderItems
where (listStatus == null || listStatus.Contains(item.StatusCode))
&& (listMerchants == null || listMerchants.Contains(item.MerchantId))
select item;
Add the /usr/local/opt/python/libexec/bin
explicitly to your .bash_profile
:
export PATH="/usr/local/opt/python/libexec/bin:$PATH"
After that, it should work correctly.
This way we can do this with minimal changes :)
<html>
<head>
<style>
option:hover {
background-color: yellow;
}
</style>
</head>
<body>
<select onfocus='this.size=10;' onblur='this.size=0;' onchange='this.size=1; this.blur();'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</body>
</html>
_x000D_
I have come up with a slightly modified version of @SebastianRittau's wonderful answer (for Python > 3.4 I think), which will allow you to load a file with any extension as a module using spec_from_loader
instead of spec_from_file_location
:
from importlib.util import spec_from_loader, module_from_spec
from importlib.machinery import SourceFileLoader
spec = spec_from_loader("module.name", SourceFileLoader("module.name", "/path/to/file.py"))
mod = module_from_spec(spec)
spec.loader.exec_module(mod)
The advantage of encoding the path in an explicit SourceFileLoader
is that the machinery will not try to figure out the type of the file from the extension. This means that you can load something like a .txt
file using this method, but you could not do it with spec_from_file_location
without specifying the loader because .txt
is not in importlib.machinery.SOURCE_SUFFIXES
.
I don't have enough reputation to add a comment on the answer from pomber so I'm posting another answer. Using pomber's approach I kept receiving a "400 Bad Request" response from an API I was POSTing my JSON request to (Visual Studio 2017, .NET 4.6.2). Eventually the problem was traced to the "Content-Type" header produced by StringContent() being incorrect (see https://github.com/dotnet/corefx/issues/7864).
tl;dr
Use pomber's answer with an extra line to correctly set the header on the request:
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = client.PostAsync(url, content).Result;
I have tested the suggested solutions, they should all work:
select * from dual where (105 = to_number('105'))
=> delivers one dummy row
select * from dual where (10 = to_number('105'))
=> empty result
select * from dual where ('105' = to_char(105))
=> delivers one dummy row
select * from dual where ('105' = to_char(10))
=> empty result
Last 3 months
SELECT DATEADD(dd,DATEDIFF(dd,0,DATEADD(mm,-3,GETDATE())),0)
Today
SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0)
For future reference, if you want to mimic the behaviour of PHP's implode()
when no delimiter is specified (literally just join the pieces together), you need to pass an empty string into Javascript's join()
otherwise it defaults to using commas as delimiters:
var bits = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'];
alert(bits.join()); // H,e,l,l,o, ,W,o,r,l,d
alert(bits.join('')); // Hello World
Seems your initial data contains strings and not numbers. It would probably be best to ensure that the data is already of the required type up front.
However, you can convert strings to numbers like this:
pd.Series(['123', '42']).astype(float)
instead of float(series)
show variables where Variable_name='hostname';
That could help you !!
CAST both fields to datatype DATE and you can use a minus:
(CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference
Test case:
SELECT (CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference
FROM
generate_series('2014-01-01'::timestamp, '2014-02-01'::timestamp, interval '1 hour') g(joindate);
Result: 31
Or create a function datediff():
CREATE OR REPLACE FUNCTION datediff(timestamp, timestamp)
RETURNS int
LANGUAGE sql
AS
$$
SELECT CAST($1 AS date) - CAST($2 AS date) as DateDifference
$$;
The new font resource allows to directly set font
using
android:fontFamily="@font/my_font_in_font_folder"
Backticks enclose template literals, previously known as template strings. Template literals are string literals that allow embedded expressions and string interpolation features.
Template literals have expressions embedded in placeholders, denoted by the dollar sign and curly brackets around an expression, i.e. ${expression}
. The placeholder / expressions get passed to a function. The default function just concatenates the string.
To escape a backtick, put a backslash before it:
`\`` === '`'; => true
Use backticks to more easily write multi-line string:
console.log(`string text line 1
string text line 2`);
or
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
vs. vanilla JavaScript:
console.log('string text line 1\n' +
'string text line 2');
or
console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
Escape sequences:
\u
, for example \u00A9
\u{}
, for example \u{2F804}
\x
, for example \xA9
\
and (a) digit(s), for example \251
use a filter function os.path.isdir
over os.listdir()
something like this filter(os.path.isdir,[os.path.join(os.path.abspath('PATH'),p) for p in os.listdir('PATH/')])
Things are going better, right now you can use SVG files.
marker = new google.maps.Marker({
position: {lat: 36.720426, lng: -4.412573},
map: map,
draggable: true,
icon: "img/tree.svg"
});
If you want to do this programmatically you can use some of the options given to you as follows in a PowerShell script:
$processPID = $($(netstat -aon | findstr "9999")[0] -split '\s+')[-1]
taskkill /f /pid $processPID
However; be aware that the more accurate you can be the more precise your PID result will be. If you know which host the port is supposed to be on you can narrow it down a lot. netstat -aon | findstr "0.0.0.0:9999"
will only return one application and most llikely the correct one. Only searching on the port number may cause you to return processes that only happens to have 9999
in it, like this:
TCP 0.0.0.0:9999 0.0.0.0:0 LISTENING 15776
UDP [fe80::81ad:9999:d955:c4ca%2]:1900 *:* 12331
The most likely candidate usually ends up first, but if the process has ended before you run your script you may end up with PID 12331 instead and killing the wrong process.
Git for windows 2.6.3:
git submodule update --rebase --remote
We dont need redux-persist we can simply use redux for persistance.
react-redux + AsyncStorage = redux-persist
so inside createsotre file simply add these lines
store.subscribe(async()=> await AsyncStorage.setItem("store", JSON.stringify(store.getState())))
this will update the AsyncStorage whenever there are some changes in the redux store.
Then load the json converted store. when ever the app loads. and set the store again.
Because redux-persist creates issues when using wix react-native-navigation. If that's the case then I prefer to use simple redux with above subscriber function
I find it useful to understand the underlying tools. These are cl.exe (compiler) and link.exe (linker). You need to tell the compiler the signatures of the functions you want to call in the dynamic library (by including the library's header) and you need to tell the linker what the library is called and how to call it (by including the "implib" or import library).
This is roughly the same process gcc uses for linking to dynamic libraries on *nix, only the library object file differs.
Knowing the underlying tools means you can more quickly find the appropriate settings in the IDE and allows you to check that the commandlines generated are correct.
Say A.exe depends B.dll. You need to include B's header in A.cpp (#include "B.h"
) then compile and link with B.lib:
cl A.cpp /c /EHsc
link A.obj B.lib
The first line generates A.obj, the second generates A.exe. The /c
flag tells cl not to link and /EHsc
specifies what kind of C++ exception handling the binary should use (there's no default, so you have to specify something).
If you don't specify /c
cl will call link
for you. You can use the /link
flag to specify additional arguments to link
and do it all at once if you like:
cl A.cpp /EHsc /link B.lib
If B.lib is not on the INCLUDE
path you can give a relative or absolute path to it or add its parent directory to your include path with the /I
flag.
If you're calling from cygwin (as I do) replace the forward slashes with dashes.
If you write #pragma comment(lib, "B.lib")
in A.cpp you're just telling the compiler to leave a comment in A.obj telling the linker to link to B.lib. It's equivalent to specifying B.lib on the link commandline.
myObject as? String
returns nil
if myObject
is not a String
. Otherwise, it returns a String?
, so you can access the string itself with myObject!
, or cast it with myObject! as String
safely.
If you open the Settings tab for the repository on GitHub, click on Integrations & services, find Travis CI and click Edit, you should see a Test Service button. This will trigger a build.
This code will remove the indentation and list bullets.
ul {
padding: 0;
list-style-type: none;
}
DBCC CHECKIDENT('databasename.dbo.tablename', RESEED, number)
if number=0 then in the next insert the auto increment field will contain value 1
if number=101 then in the next insert the auto increment field will contain value 102
Some additional info... May be useful to you
Before giving auto increment number
in above query, you have to make sure your existing table's auto increment column contain values less that number
.
To get the maximum value of a column(column_name) from a table(table1), you can use following query
SELECT MAX(column_name) FROM table1
I am having the same problem, I found the below on the web somewhere....
Event handlers in Docs are a little tricky though. Because docs can handle multiple simultaneous edits by multiple users, the event handlers are handled server-side. The major issue with this structure is that when an event trigger script fails, it fails on the server. If you want to see the debug info you'll need to setup an explicit trigger under the triggers menu that emails you the debug info when the event fails or else it will fail silently.
I was facing this error while I deployed my Web API project locally and I was calling API project only with this URL given below:
localhost//myAPIProject
Since the error message says it is not http:// then I changed the URL and put a prefix http as given below and the error was gone.
Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)
I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.
But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.
These two links might help you, it shows the example via Node backend, but you get the point how it works:
And, of course, the CORS spec:
~Cheers
I actually wrote a patch to do this a few months ago (after someone asked about it in #angularjs on freenode).
It probably won't be merged, but it's very similar to ngClass: https://github.com/angular/angular.js/pull/4269
Whether it gets merged or not, the existing ng-attr-* stuff is probably suitable for your needs (as others have mentioned), although it might be a bit clunkier than the more ngClass-style functionality that you're suggesting.
Basically modulus Operator gives you remainder simple Example in maths what's left over/remainder of 11 divided by 3? answer is 2
for same thing C++ has modulus operator ('%')
Basic code for explanation
#include <iostream>
using namespace std;
int main()
{
int num = 11;
cout << "remainder is " << (num % 3) << endl;
return 0;
}
Which will display
remainder is 2
I have the same problem with mysqli. My solution is https://www.php.net/manual/en/mysqli.configuration.php
mysqli.reconnect = On
I would use a https://docs.flutter.io/flutter/widgets/Stack-class.html to be able to freely position widgets.
To create circles
new BoxDecoration(
color: effectiveBackgroundColor,
image: backgroundImage != null
? new DecorationImage(image: backgroundImage, fit: BoxFit.cover)
: null,
shape: BoxShape.circle,
),
and https://docs.flutter.io/flutter/widgets/Transform/Transform.rotate.html to position the white dots.
This should do it (bold as well);
label1.Font = new Font("Serif", 24,FontStyle.Bold);
The crc code in zlib (http://zlib.net/) is among the fastest there is, and has a very liberal open source license.
And you should not use adler-32 except for special applications where speed is more important than error detection performance.
I found the cleanest way to do this (especially on windows) is by adding the following to C:\Python26\Lib\site-packages\sitecustomize.py:
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
Note that I had to create this file. Of course, change the path to python if yours is different.
You can't transition between two background images, as there's no way for the browser to know what you want to interpolate. As you've discovered, you can transition the background position. If you want the image to fade in on mouse over, I think the best way to do it with CSS transitions is to put the image on a containing element and then animate the background colour to transparent on the link itself:
span {
background: url(button.png) no-repeat 0 0;
}
a {
width: 32px;
height: 32px;
text-align: left;
background: rgb(255,255,255);
-webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
-moz-transition: background 300ms ease-in 200ms;
-o-transition: background 300ms ease-in 200ms;
transition: background 300ms ease-in 200ms;
}
a:hover {
background: rgba(255,255,255,0);
}
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
Necroing this question but there's an explanation that no-one seems to have considered.
STATISTICS - Statistics are not available or misleading
If all of the following are true:
Then sql server may be incorrectly assuming that the columns are uncorrelated, leading to lower than expected cardinality estimates for applying both restrictions and a poor execution plan being selected. The fix in this case would be to create a statistics object linking the two columns, which is not an expensive operation.
If your goal is to monitor MySQL free space and you can't stop MySQL to shrink your ibdata file, then get it through table status commands. Example:
MySQL > 5.1.24:
mysqlshow --status myInnodbDatabase myTable | awk '{print $20}'
MySQL < 5.1.24:
mysqlshow --status myInnodbDatabase myTable | awk '{print $35}'
Then compare this value to your ibdata file:
du -b ibdata1
Source: http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html
If you don't want to use ng-form you can use a custom directive that will change the form's name attribute. Place this directive as an attribute on the same element as your ng-model.
If you're using other directives in conjunction, be careful that they don't have the "terminal" property set otherwise this function won't be able to run (given that it has a priority of -1).
For example, when using this directive with ng-options, you must run this one line monkeypatch: https://github.com/AlJohri/bower-angular/commit/eb17a967b7973eb7fc1124b024aa8b3ca540a155
angular.module('app').directive('fieldNameHack', function() {
return {
restrict: 'A',
priority: -1,
require: ['ngModel'],
// the ngModelDirective has a priority of 0.
// priority is run in reverse order for postLink functions.
link: function (scope, iElement, iAttrs, ctrls) {
var name = iElement[0].name;
name = name.replace(/\{\{\$index\}\}/g, scope.$index);
var modelCtrl = ctrls[0];
modelCtrl.$name = name;
}
};
});
I often find it useful to use ng-init to set the $index to a variable name. For example:
<fieldset class='inputs' ng-repeat="question questions" ng-init="qIndex = $index">
This changes your regular expression to:
name = name.replace(/\{\{qIndex\}\}/g, scope.qIndex);
If you have multiple nested ng-repeats, you can now use these variable names instead of $parent.$index.
Definition of "terminal" and "priority" for directives: https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object
Github Comment regarding need for ng-option monkeypatch: https://github.com/angular/angular.js/commit/9ee2cdff44e7d496774b340de816344126c457b3#commitcomment-6832095 https://twitter.com/aljohri/status/482963541520314369
UPDATE:
You can also make this work with ng-form.
angular.module('app').directive('formNameHack', function() {
return {
restrict: 'A',
priority: 0,
require: ['form'],
compile: function() {
return {
pre: function(scope, iElement, iAttrs, ctrls) {
var parentForm = $(iElement).parent().controller('form');
if (parentForm) {
var formCtrl = ctrls[0];
delete parentForm[formCtrl.$name];
formCtrl.$name = formCtrl.$name.replace(/\{\{\$index\}\}/g, scope.$index);
parentForm[formCtrl.$name] = formCtrl;
}
}
}
}
};
});
You are probably behind a firewall. Try cloning via https – that has a higher chance of not being blocked:
git clone https://github.com/angular/angular-phonecat.git
To check for DIRECTORIES you should not use something like:
if exist c:\windows\
To work properly use:
if exist c:\windows\\.
note the "." at the end.
As other answers note, the correct way to find the Java home directory is to use /usr/libexec/java_home
.
The official documentation for this is in Apple's Technical Q&A QA1170: Important Java Directories on OS X: https://developer.apple.com/library/mac/qa/qa1170/_index.html
I just found out that the following works:
https://www.youtube.com/embed/[video_id]?start=[start_at_second]&end=[end_at_second]
Note: the time must be an integer number of seconds (e.g. 119, not 1m59s).
You should use append to add to the list. But also here are few code tips:
I would use dict.setdefault
or defaultdict
to avoid having to specify the empty list in the dictionary definition.
If you use prev
to to filter out duplicated values you can simplfy the code using groupby
from itertools
Your code with the amendments looks as follows:
import itertools
def make_drug_dictionary(data):
drug_dictionary = {}
for key, row in itertools.groupby(data, lambda x: x[11]):
drug_dictionary.setdefault(key,[]).append(row[?])
return drug_dictionary
If you don't know how groupby works just check this example:
>>> list(key for key, val in itertools.groupby('aaabbccddeefaa'))
['a', 'b', 'c', 'd', 'e', 'f', 'a']
Using this
instead of $scope
works.
function AppCtrl($scope){_x000D_
$scope.searchText = "";_x000D_
$scope.check = function () {_x000D_
console.log("You typed '" + this.searchText + "'"); // used 'this' instead of $scope_x000D_
}_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app>_x000D_
<div ng-controller="AppCtrl">_x000D_
<input ng-model="searchText"/>_x000D_
<button ng-click="check()">Write console log</button>_x000D_
</div>_x000D_
</div>
_x000D_
Edit: At the time writing this answer, I had much more complicated situation than this. After the comments, I tried to reproduce it to understand why it works, but no luck. I think somehow (don't really know why) a new child scope is generated and this
refers to that scope. But if $scope
is used, it actually refers to the parent $scope because of javascript's lexical scope feature.
Would be great if someone having this problem tests this way and inform us.
You can use Math.Ceiling
http://msdn.microsoft.com/en-us/library/system.math.ceiling%28v=VS.100%29.aspx
You can use the properties tab in eclipse to set various values.
here are all the possible values
Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType
This is when a Promise
is completed with .reject()
or an exception was thrown in an async
executed code and no .catch()
did handle the rejection.
A rejected promise is like an exception that bubbles up towards the application entry point and causes the root error handler to produce that output.
See also
The ObjectDumper
class has been known to do that. I've never confirmed, but I've always suspected that the immediate window uses that.
EDIT: I just realized, that the code for ObjectDumper
is actually on your machine. Go to:
C:/Program Files/Microsoft Visual Studio 9.0/Samples/1033/CSharpSamples.zip
This will unzip to a folder called LinqSamples. In there, there's a project called ObjectDumper. Use that.
NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];
or use
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
You have to escape [
and ]
.
Try this:
$('.button').click(function(){
var fieldID = $(this).prev().attr("id");
fieldID = fieldID.replace(/([\[\]]+)/g, "\\$1");
$('#' + fieldID).val("hello world");
});
Have a look at py-multicast. Network module can check if an interface supports multicast (on Linux at least).
import multicast
from multicast import network
receiver = multicast.MulticastUDPReceiver ("eth0", "238.0.0.1", 1234 )
data = receiver.read()
receiver.close()
config = network.ifconfig()
print config['eth0'].addresses
# ['10.0.0.1']
print config['eth0'].multicast
#True - eth0 supports multicast
print config['eth0'].up
#True - eth0 is up
Perhaps problems with not seeing IGMP, were caused by an interface not supporting multicast?
You can use array.slice(0,1) // First index is removed and array is returned.
Rather than using a regular expression, I would recommend making use of an anchor element.
when you set the href
property of an anchor
, various other properties are set.
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"
However, if the value href
is bound to is not a valid url, then the value of those auxiliary properties will be the empty string.
Edit: as pointed out in the comments: if an invalid url is used, the properties of the current URL may be substituted.
So, as long as you're not passing in the URL of the current page, you can do something like:
function isValidURL(str) {
var a = document.createElement('a');
a.href = str;
return (a.host && a.host != window.location.host);
}
In WebApi 2 you can add this to global.asax
protected void Application_PostAuthorizeRequest()
{
System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
Then you could access the session through:
HttpContext.Current.Session
what i did was a quick fix by converting readlines to string but i do not recommencement it but it works and i dont know if there are limitations or not
`def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
readlines = str(readfile.readlines())
Type = readlines.split(",")
x = Type[1]
y = Type[2]
for points in Type:
print(x,y)
getQuakeData()`
You can use this for your purpose.
In parent form:
private void addCustomerToolStripMenuItem_Click(object sender, EventArgs e)
{
CustomerPage f = new CustomerPage();
f.LoadType = 1;
f.MdiParent = this;
f.Show();
f.Focus();
}
In child form:
public int LoadType{get;set;}
private void CustomerPage_Load(object sender, EventArgs e)
{
if (LoadType == 1)
{
this.button1.Visible = false;
}
}
You are correct that **
is the power function.
^
is bitwise XOR.
%
is indeed the modulus operation, but note that for positive numbers, x % m = x
whenever m > x
. This follows from the definition of modulus. (Additionally, Python specifies x % m
to have the sign of m
.)
//
is a division operation that returns an integer by discarding the remainder. This is the standard form of division using the /
in most programming languages. However, Python 3 changed the behavior of /
to perform floating-point division even if the arguments are integers. The //
operator was introduced in Python 2.6 and Python 3 to provide an integer-division operator that would behave consistently between Python 2 and Python 3. This means:
| context | `/` behavior | `//` behavior |
---------------------------------------------------------------------------
| floating-point arguments, Python 2 & 3 | float division | int divison |
---------------------------------------------------------------------------
| integer arguments, python 2 | int division | int division |
---------------------------------------------------------------------------
| integer arguments, python 3 | float division | int division |
For more details, see this question: Division in Python 2.7. and 3.3
You can do the same with .ix
, like this:
In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))
In [2]: df
Out[2]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 -0.905302 -0.435821 1.934512
3 0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
In [3]: df.ix[df.a>0, ['b','c']] = 0
In [4]: df
Out[4]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 0.000000 0.000000 1.934512
3 0.266113 0.000000 0.000000 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
EDIT
After the extra information, the following will return all columns - where some condition is met - with halved values:
>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)
I hope this helps!
Summary
This example assumes you always know where the apache root folder is '/var/www/' and you are trying to find the next folder path (e.g. '/var/www/my_website_folder'). Also this works from a script or the web browser which is why there is additional code.
Code PHP7
function getHtmlRootFolder(string $root = '/var/www/') {
// -- try to use DOCUMENT_ROOT first --
$ret = str_replace(' ', '', $_SERVER['DOCUMENT_ROOT']);
$ret = rtrim($ret, '/') . '/';
// -- if doesn't contain root path, find using this file's loc. path --
if (!preg_match("#".$root."#", $ret)) {
$root = rtrim($root, '/') . '/';
$root_arr = explode("/", $root);
$pwd_arr = explode("/", getcwd());
$ret = $root . $pwd_arr[count($root_arr) - 1];
}
return (preg_match("#".$root."#", $ret)) ? rtrim($ret, '/') . '/' : null;
}
Example
echo getHtmlRootFolder();
Output:
/var/www/somedir/
Details:
Basically first tries to get DOCUMENT_ROOT if it contains '/var/www/' then use it, else get the current dir (which much exist inside the project) and gets the next path value based on count of the $root path. Note: added rtrim statements to ensure the path returns ending with a '/' in all cases . It doesn't check for it requiring to be larger than /var/www/ it can also return /var/www/ as a possible response.
Using ASCII(RIGHT(ProductAlternateKey, 1))
you can see that the right most character in row 2 is a Line Feed or Ascii Character 10.
This can not be removed using the standard LTrim
RTrim
functions.
You could however use (REPLACE(ProductAlternateKey, CHAR(10), '')
You may also want to account for carriage returns and tabs. These three (Line feeds, carriage returns and tabs) are the usual culprits and can be removed with the following :
LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(ProductAlternateKey, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')))
If you encounter any more "white space" characters that can't be removed with the above then try one or all of the below:
--NULL
Replace([YourString],CHAR(0),'');
--Horizontal Tab
Replace([YourString],CHAR(9),'');
--Line Feed
Replace([YourString],CHAR(10),'');
--Vertical Tab
Replace([YourString],CHAR(11),'');
--Form Feed
Replace([YourString],CHAR(12),'');
--Carriage Return
Replace([YourString],CHAR(13),'');
--Column Break
Replace([YourString],CHAR(14),'');
--Non-breaking space
Replace([YourString],CHAR(160),'');
This list of potential white space characters could be used to create a function such as :
Create Function [dbo].[CleanAndTrimString]
(@MyString as varchar(Max))
Returns varchar(Max)
As
Begin
--NULL
Set @MyString = Replace(@MyString,CHAR(0),'');
--Horizontal Tab
Set @MyString = Replace(@MyString,CHAR(9),'');
--Line Feed
Set @MyString = Replace(@MyString,CHAR(10),'');
--Vertical Tab
Set @MyString = Replace(@MyString,CHAR(11),'');
--Form Feed
Set @MyString = Replace(@MyString,CHAR(12),'');
--Carriage Return
Set @MyString = Replace(@MyString,CHAR(13),'');
--Column Break
Set @MyString = Replace(@MyString,CHAR(14),'');
--Non-breaking space
Set @MyString = Replace(@MyString,CHAR(160),'');
Set @MyString = LTRIM(RTRIM(@MyString));
Return @MyString
End
Go
Which you could then use as follows:
Select
dbo.CleanAndTrimString(ProductAlternateKey) As ProductAlternateKey
from DimProducts
The VOLUME
command will mount a directory inside your container and store any files created or edited inside that directory on your hosts disk outside the container file structure, bypassing the union file system.
The idea is that your volumes can be shared between your docker containers and they will stay around as long as there's a container (running or stopped) that references them.
You can have other containers mount existing volumes (effectively sharing them between containers) by using the --volumes-from
command when you run a container.
The fundamental difference between VOLUME
and -v
is this: -v
will mount existing files from your operating system inside your docker container and VOLUME
will create a new, empty volume on your host and mount it inside your container.
Example:
VOLUME /var/lib/mysql
.some-volume
And then,
docker run --volumes-from some-volume docker-image-name:tag
some-volume
mounted in /var/lib/mysql
Note: Using --volumes-from
will mount the volume over whatever exists in the location of the volume. I.e., if you had stuff in /var/lib/mysql
, it will be replaced with the contents of the volume.
The only real way is to have a container around your image and use overflow:hidden
:
HTML
<div class="container"><img src="ckk.jpg" /></div>
CSS
.container {
width: 300px;
height: 200px;
display: block;
position: relative;
overflow: hidden;
}
.container img {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
It's a pain in CSS to do what you want and center the image, there is a quick fix in jquery such as:
var conHeight = $(".container").height();
var imgHeight = $(".container img").height();
var gap = (imgHeight - conHeight) / 2;
$(".container img").css("margin-top", -gap);
You could define a clone function.
I use this one :
function goclone(source) {
if (Object.prototype.toString.call(source) === '[object Array]') {
var clone = [];
for (var i=0; i<source.length; i++) {
clone[i] = goclone(source[i]);
}
return clone;
} else if (typeof(source)=="object") {
var clone = {};
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
clone[prop] = goclone(source[prop]);
}
}
return clone;
} else {
return source;
}
}
var B = goclone(A);
It doesn't copy the prototype, functions, and so on. But you should adapt it (and maybe simplify it) for you own need.
genrsa
has been replaced by genpkey
& when run manually in a terminal it will prompt for a password:
openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096
However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell
script:
get_passwd() {
local passwd=
echo -ne "Enter passwd for private key: ? "; read -s passwd
openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}
This strange bug was solved through Interface Builder parameters as the other answers did not resolve the issue.
All I did was make the default label size larger than the content potentially could be and have it reflected in the estimatedRowHeight
height too. Previously, I set the default row height in Interface Builder to 88px
and reflected it like so in my controller viewDidLoad()
:
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 88.0
But that didn't work. So I realized that content wouldn't ever become larger than maybe 100px
, so I set the default cell height to 108px
(larger than the potential content) and reflected it like so in the controller viewDidLoad()
:
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 108.0
This actually allowed the code to shrink down the initial labels to the correct size. In other words, it never expanded out to a larger size, but could always shrink down... Also, no additional self.tableView.reloadData()
was needed in viewWillAppear()
.
I know this does not cover highly variable content sizes, but this worked in my situation where the content had a maximum possible character count.
Not sure if this is a bug in Swift or Interface Builder but it works like a charm. Give it a try!
Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:
"Features" >
Unfortunately changing it through the UI means that the changes don't persist between logins.
The currently selected answer did not work well at all in my case, which I feel is a fairly typical one. I found the below function here and it works great!
function getAllUrlParams(url) {
// get query string from url (optional) or window
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split('#')[0];
// split our query string into its component parts
var arr = queryString.split('&');
for (var i=0; i<arr.length; i++) {
// separate the keys and the values
var a = arr[i].split('=');
// in case params look like: list[]=thing1&list[]=thing2
var paramNum = undefined;
var paramName = a[0].replace(/\[\d*\]/, function(v) {
paramNum = v.slice(1,-1);
return '';
});
// set parameter value (use 'true' if empty)
var paramValue = typeof(a[1])==='undefined' ? true : a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
paramValue = paramValue.toLowerCase();
// if parameter name already exists
if (obj[paramName]) {
// convert value to array (if still string)
if (typeof obj[paramName] === 'string') {
obj[paramName] = [obj[paramName]];
}
// if no array index number specified...
if (typeof paramNum === 'undefined') {
// put the value on the end of the array
obj[paramName].push(paramValue);
}
// if array index number specified...
else {
// put the value at that index number
obj[paramName][paramNum] = paramValue;
}
}
// if param name doesn't exist yet, set it
else {
obj[paramName] = paramValue;
}
}
}
return obj;
}
You can use int
and set the base to 2
(for binary):
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>
However, if you cannot use int
like that, then you could always do this:
binary = raw_input('enter a number: ')
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
print decimal
Below is a demonstration:
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> decimal = 0
>>> for digit in binary:
... decimal = decimal*2 + int(digit)
...
>>> print decimal
25
>>>
In PowerShell, you could set the http_proxy and https_proxy environment variables like so:
$env:http_proxy="http://proxy:3128"
$env:https_proxy="http://proxy:3128"
I came looking for the answer to the Swift 3 Data to String question and never got a good answer. After some fooling around I came up with this:
var testString = "This is a test string"
var somedata = testString.data(using: String.Encoding.utf8)
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!
If you don't wanna use rfind then this will do the trick/
def find_last(s, t):
last_pos = -1
while True:
pos = s.find(t, last_pos + 1)
if pos == -1:
return last_pos
else:
last_pos = pos
Two comments:
and
and or
for logical operations in Python.The simple GUI way, as provided by J Y in a previous answer:
This works well and reminds you of the significance of allocation unit size. But it does have a caveat: as seen in comments to previous answer, Windows will sometimes show "Size on disk" as 0 for a very small file. In my testing, NTFS filesystems with allocation unit size 4096 bytes required the file to be 800 bytes to consistently avoid this issue. On FAT32 file systems this issue seems nonexistent, even a single byte file will work - just not empty.
some data structures are missing from the standard java collections.
Bag (like set but can contain elements multiple times)
UniqueList (ordered list, can contain each element only once)
seems you would need a uniquelist in this case
if you need flexible data structures, you might be interested in Google Collections
work for me...
<android.support.v7.widget.Toolbar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/toolBar"
android:background="@color/colorGreen"
app:title="Title"
app:titleTextColor="@color/colorBlack"
app:navigationIcon="@drawable/ic_action_back"/>
Change the vm value in eclipse.ini file with the correct path to your JDK something like this,
-vm /Library/Java/JavaVirtualMachines/jdk-11.0.5.jdk/Contents/Home/bin
Path to eclipse.ini looks to me something like this,
/Users/tomcat/eclipse/jee-2018-09/Eclipse.app/Contents/Eclipse
<execute-test-successful-condition> if <test> else <execute-test-fail-condition>
with your code-snippet it would become,
count = 0 if count == N else N + 1
The POSIX specification for find says:
-mtime
n
The primary shall evaluate as true if the file modification time subtracted from the initialization time, divided by 86400 (with any remainder discarded), isn
.
Interestingly, the description of find
does not further specify 'initialization time'. It is probably, though, the time when find
is initialized (run).
In the descriptions, wherever
n
is used as a primary argument, it shall be interpreted as a decimal integer optionally preceded by a plus ( '+' ) or minus-sign ( '-' ) sign, as follows:
+n
More thann
.
n
Exactlyn
.
-n
Less thann
.
At the given time (2014-09-01 00:53:44 -4:00, where I'm deducing that AST is Atlantic Standard Time, and therefore the time zone offset from UTC is -4:00 in ISO 8601 but +4:00 in ISO 9945 (POSIX), but it doesn't matter all that much):
1409547224 = 2014-09-01 00:53:44 -04:00
1409457540 = 2014-08-30 23:59:00 -04:00
so:
1409547224 - 1409457540 = 89684
89684 / 86400 = 1
Even if the 'seconds since the epoch' values are wrong, the relative values are correct (for some time zone somewhere in the world, they are correct).
The n
value calculated for the 2014-08-30 log file therefore is exactly 1
(the calculation is done with integer arithmetic), and the +1
rejects it because it is strictly a > 1
comparison (and not >= 1
).
git reset --hard <tag/branch/commit id>
Notes:
git reset
without the --hard
option resets the commit history, but not the files. With the --hard
option the files in working tree are also reset. (credited user)
If you wish to commit that state so that the remote repository also points to the rolled back commit do: git push <reponame> -f
(credited user)
see http://editorconfig.org and https://docs.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017
If it does not exist, add a new file called .editorconfig for your project
manipulate editor config to use your preferred behaviour.
I prefer spaces over tabs, and CRLF for all code files.
Here's my .editorconfig
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.tmpl.html]
indent_size = 4
[*.scss]
indent_size = 2
I find all previous answers on-spot but let's put things in context.
The 403 forbidden response comes from the CSRF middleware (see Cross Site Request Forgery protection):
By default, a ‘403 Forbidden’ response is sent to the user if an incoming request fails the checks performed by CsrfViewMiddleware.
Many options are available. I would recommend to follow the answer of @fivef in order to make jQuery add the X-CSRFToken
header before every AJAX request with $.ajaxSetup
.
This answer requires the cookie jQuery plugin. If this is not desirable, another possibility is to add:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
BUT: if the setting CSRF_COOKIE_HTTPONLY
is set to True, which often happens as the Security middleware recommends so, then the cookie is not there, even if @ensure_csrf_cookie()
is used. In this case {% csrf_token %}
must be provided in every form, which produces an output such as <input name="csrfmiddlewaretoken" value="cr6O9...FUXf6" type="hidden">
. So the csrfToken
variable would simply be obtained with:
var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();
Again $.ajaxSetup
would be required of course.
Other options which are available but not recommended are to disable the middleware or the csrf protection for the specific form with @csrf_exempt()
.
I checked all above and it didn't work for me,
There are some steps I found.
I used PHP Version 5.5.9-1ubuntu4.17 on Ubuntu 14.04
First check the folder
#ls /etc/php5/mods-available/
json.ini mcrypt.ini mysqli.ini mysql.ini mysqlnd.ini opcache.ini pdo.ini pdo_mysql.ini readline.ini xcache.ini
If it did not contain mysqli.ini, read other answer for installing it,
Open php.ini
find extension_dir
In my case , I must set extension_dir = /usr/lib/php5/20121212
And restart apache2 : /ect/init.d/apache2 restart
Do this if you are using GoDaddy, I'm using Lets Encrypt SSL if you want you can get it.
Here is the code - The code is in asp.net core 2.0 but should work in above versions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;
namespace UnityAssets.Website.Services
{
public class EmailSender : IEmailSender
{
public async Task SendEmailAsync(string toEmailAddress, string subject, string htmlMessage)
{
var email = new MimeMessage();
email.From.Add(new MailboxAddress("Application Name", "[email protected]"));
email.To.Add(new MailboxAddress(toEmailAddress, toEmailAddress));
email.Subject = subject;
var body = new BodyBuilder
{
HtmlBody = htmlMessage
};
email.Body = body.ToMessageBody();
using (var client = new SmtpClient())
{
//provider specific settings
await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
await client.AuthenticateAsync("[email protected]", "sketchunity").ConfigureAwait(false);
await client.SendAsync(email).ConfigureAwait(false);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
}
}
Add the parameter yourself.
$.get(url,{ "_": $.now() }, function(rdata){
console.log(rdata);
});
As of jQuery 3.0, you can now do this:
$.get({
url: url,
cache: false
}).then(function(rdata){
console.log(rdata);
});
Use underscore library, very useful: _.keys(obj).length
.
Use
It is the entity used to represent a non-breaking space. It is essentially a standard space, the primary difference being that a browser should not break (or wrap) a line of text at the point that this occupies.
var a = 'something' + '         ' + 'something'
A common character entity used in HTML is the non-breaking space ( ).
Remember that browsers will always truncate spaces in HTML pages. If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text, you can use the character entity.
http://www.w3schools.com/html/html_entities.asp
Demo
var a = 'something' + '         ' + 'something';_x000D_
_x000D_
document.body.innerHTML = a;
_x000D_
echo date('D', strtotime($date));
echo date('l', strtotime($date));
Result
Tue
Tuesday
I used this lmp function quite a lot of times.
And at one point I decided to add new features to enhance data analysis. I am not in expert in R or statistics but people are usually looking at different information of a linear regression :
Let's have an example. You have here
Here a reproducible example with different variables:
Ex<-structure(list(X1 = c(-36.8598, -37.1726, -36.4343, -36.8644,
-37.0599, -34.8818, -31.9907, -37.8304, -34.3367, -31.2984, -33.5731
), X2 = c(64.26, 63.085, 66.36, 61.08, 61.57, 65.04, 72.69, 63.83,
67.555, 76.06, 68.61), Y1 = c(493.81544, 493.81544, 494.54173,
494.61364, 494.61381, 494.38717, 494.64122, 493.73265, 494.04246,
494.92989, 494.98384), Y2 = c(489.704166, 489.704166, 490.710962,
490.653212, 490.710612, 489.822928, 488.160904, 489.747776, 490.600579,
488.946738, 490.398958), Y3 = c(-19L, -19L, -19L, -23L, -30L,
-43L, -43L, -2L, -58L, -47L, -61L)), .Names = c("X1", "X2", "Y1",
"Y2", "Y3"), row.names = c(NA, 11L), class = "data.frame")
library(reshape2)
library(ggplot2)
Ex2<-melt(Ex,id=c("X1","X2"))
colnames(Ex2)[3:4]<-c("Y","Yvalue")
Ex3<-melt(Ex2,id=c("Y","Yvalue"))
colnames(Ex3)[3:4]<-c("X","Xvalue")
ggplot(Ex3,aes(Xvalue,Yvalue))+
geom_smooth(method="lm",alpha=0.2,size=1,color="grey")+
geom_point(size=2)+
facet_grid(Y~X,scales='free')
#Use the lmp function
lmp <- function (modelobject) {
if (class(modelobject) != "lm") stop("Not an object of class 'lm' ")
f <- summary(modelobject)$fstatistic
p <- pf(f[1],f[2],f[3],lower.tail=F)
attributes(p) <- NULL
return(p)
}
# create function to extract different informations from lm
lmtable<-function (var1,var2,data,signi=NULL){
#var1= y data : colnames of data as.character, so "Y1" or c("Y1","Y2") for example
#var2= x data : colnames of data as.character, so "X1" or c("X1","X2") for example
#data= data in dataframe, variables in columns
# if signi TRUE, round p-value with 2 digits and add *** if <0.001, ** if < 0.01, * if < 0.05.
if (class(data) != "data.frame") stop("Not an object of class 'data.frame' ")
Tabtemp<-data.frame(matrix(NA,ncol=6,nrow=length(var1)*length(var2)))
for (i in 1:length(var2))
{
Tabtemp[((length(var1)*i)-(length(var1)-1)):(length(var1)*i),1]<-var1
Tabtemp[((length(var1)*i)-(length(var1)-1)):(length(var1)*i),2]<-var2[i]
colnames(Tabtemp)<-c("Var.y","Var.x","p-value","a","b","r^2")
for (n in 1:length(var1))
{
Tabtemp[(((length(var1)*i)-(length(var1)-1))+n-1),3]<-lmp(lm(data[,var1[n]]~data[,var2[i]],data))
Tabtemp[(((length(var1)*i)-(length(var1)-1))+n-1),4]<-coef(lm(data[,var1[n]]~data[,var2[i]],data))[1]
Tabtemp[(((length(var1)*i)-(length(var1)-1))+n-1),5]<-coef(lm(data[,var1[n]]~data[,var2[i]],data))[2]
Tabtemp[(((length(var1)*i)-(length(var1)-1))+n-1),6]<-summary(lm(data[,var1[n]]~data[,var2[i]],data))$r.squared
}
}
signi2<-data.frame(matrix(NA,ncol=3,nrow=nrow(Tabtemp)))
signi2[,1]<-ifelse(Tabtemp[,3]<0.001,paste0("***"),ifelse(Tabtemp[,3]<0.01,paste0("**"),ifelse(Tabtemp[,3]<0.05,paste0("*"),paste0(""))))
signi2[,2]<-round(Tabtemp[,3],2)
signi2[,3]<-paste0(format(signi2[,2],digits=2),signi2[,1])
for (l in 1:nrow(Tabtemp))
{
Tabtemp$"p-value"[l]<-ifelse(is.null(signi),
Tabtemp$"p-value"[l],
ifelse(isTRUE(signi),
paste0(signi2[,3][l]),
Tabtemp$"p-value"[l]))
}
Tabtemp
}
# ------- EXAMPLES ------
lmtable("Y1","X1",Ex)
lmtable(c("Y1","Y2","Y3"),c("X1","X2"),Ex)
lmtable(c("Y1","Y2","Y3"),c("X1","X2"),Ex,signi=TRUE)
There is certainly a faster solution than this function but it works.
The method getDeviceId() of TelephonyManager returns the unique device ID, for example, the IMEI for GSM and the MEID or ESN for CDMA phones. Return null if device ID is not available.
Java Code
package com.AndroidTelephonyManager;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;
public class AndroidTelephonyManager extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textDeviceID = (TextView)findViewById(R.id.deviceid);
//retrieve a reference to an instance of TelephonyManager
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
textDeviceID.setText(getDeviceID(telephonyManager));
}
String getDeviceID(TelephonyManager phonyManager){
String id = phonyManager.getDeviceId();
if (id == null){
id = "not available";
}
int phoneType = phonyManager.getPhoneType();
switch(phoneType){
case TelephonyManager.PHONE_TYPE_NONE:
return "NONE: " + id;
case TelephonyManager.PHONE_TYPE_GSM:
return "GSM: IMEI=" + id;
case TelephonyManager.PHONE_TYPE_CDMA:
return "CDMA: MEID/ESN=" + id;
/*
* for API Level 11 or above
* case TelephonyManager.PHONE_TYPE_SIP:
* return "SIP";
*/
default:
return "UNKNOWN: ID=" + id;
}
}
}
XML
<linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<textview android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="@string/hello">
<textview android:id="@+id/deviceid" android:layout_height="wrap_content" android:layout_width="fill_parent">
</textview></textview></linearlayout>
Permission Required READ_PHONE_STATE in manifest file.
Code to check whether two elements exist in array whose product equals k:
n = len(arr1)
for i in arr1:
if k%i==0:
print(i)
You do like this. the function return the old text.
$('button').click(function(){
$(this).text(function(i,old){
return old=='Read More' ? 'Read Less' : 'Read More';
});
});
A dozen pages is not a big deal when using OFFSET
. But when you have hundreds of pages, you will find that OFFSET
is bad for performance. This is because all the skipped rows need to be read each time.
It is better to remember where you left off.
Though the answer has been given for the question. I would like to add, if in case we need to print numbers without any spaces then we can use the following code
for i in range(1,n):
print(i,end="")
You get SyntaxError
error exception because Python has no &&
operator. It has and
and &
where the latter one is the correct choice to create boolean expressions on Column
(|
for a logical disjunction and ~
for logical negation).
Condition you created is also invalid because it doesn't consider operator precedence. &
in Python has a higher precedence than ==
so expression has to be parenthesized.
(col("Age") == "") & (col("Survived") == "0")
## Column<b'((Age = ) AND (Survived = 0))'>
On a side note when
function is equivalent to case
expression not WHEN
clause. Still the same rules apply. Conjunction:
df.where((col("foo") > 0) & (col("bar") < 0))
Disjunction:
df.where((col("foo") > 0) | (col("bar") < 0))
You can of course define conditions separately to avoid brackets:
cond1 = col("Age") == ""
cond2 = col("Survived") == "0"
cond1 & cond2
When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".
If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".
I also had the same error. In my case reason was I have created a update trigger on a table and under that trigger I am again updating the same table. And when I have removed the update statement from the trigger my problem has been resolved.
The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:
var black = $('.black');
var white = $('.white');
The selector will find every element classed under black or white. Button functions stay as stated above:
$('#showBlackButton').click(function() {
black.show();
white.hide();
});
$('#showWhiteButton').click(function() {
white.show();
black.hide();
});
I just customized BootPc Deutschland's answer
You can simply use
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('body,html').animate({
scrollTop: 0
}, 800);
$('#btn-go-to-top').click(function () {
$('body,html').animate({
scrollTop: 0
}, 800);
return false;
});
});
</script>
this will help you to smoothly scroll to the top of the page.
and for styling
#btn-go-to-top {
opacity: .5;
width:4%;
height:8%;
display: none;
position: fixed;
bottom: 5%;
right: 3%;
z-index: 99;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 10px;
border-radius: 50%;
}
#btn-go-to-top:hover {
opacity: 1;
}
.top {
transition: all 0.5s ease 0s;
-moz-transition: all 0.5s ease 0s;
-webkit-transition: all 0.5s ease 0s;
-o-transition: all 0.5s ease 0s;
}
this styling makes the button arrive at the bottom-right of the page.
and in your page you can add the button to go to top like this
<div id="btn-go-to-top" class="text-center top">
<img src="uploads/Arrow.png" style="margin: 7px;" width="50%" height="50%">
</div>
hope this help you.if you have any doubts you are always free to ask me
You can apply more than one transform like this:
li:nth-of-type(2){
transform : translate(-20px, 0px) rotate(15deg);
}
Using the ternary operator is possible like following.[disabled] internally required true or false for its operation.
<button type="button"
[disabled]="(testVariable1 != 0 || testVariable2!=0)? true:false"
mat-button>Button</button>
Right: it has nothing to do with your code. I've found two valid solutions to this warning (not just disabling it). To better understand what a SourceMap is, I suggest you check out this answer, where it explains how it's something that helps you debug:
The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.
First solution: apparently, Mr Heelis was the closest one: you should add the .map file and there are some tools that help you with this problem (Grunt, Gulp and Google closure for example, quoting the answer). Otherwise you can download the .map file from official sites like Bootstrap, jquery, font-awesome, preload and so on.. (maybe installing things like popper or swiper by the npm command in a random folder and copying just the .map file in your js/css destination folder)
Second solution (the one I used): add the source files using a CDN (here all the advantages of using a CDN). Using the Content delivery network (CDN) you can simply add the cdn link, instead of the path to your folder. You can find cdn on official websites (Bootstrap, jquery, popper, etc..) or you can easily search on some websites like cloudflare, cdnjs, etc..
If you have the element in scroll view then you can also solve this issue as :
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/ed_password"
android:inputType="textPassword"
android:focusable="true"
android:imeOptions="actionNext"
android:nextFocusDown="@id/ed_confirmPassword" />
and in your activity:
edPassword.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_NEXT) {
focusOnView(scroll,edConfirmPassword);
return true;
}
return false;
}
});
public void focusOnView(ScrollView scrollView, EditText viewToScrollTo){
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.smoothScrollTo(0, viewToScrollTo.getBottom());
viewToScrollTo.requestFocus();
}
});
}
Install the favicon middleware and then do:
var favicon = require('serve-favicon');
app.use(favicon(__dirname + '/public/images/favicon.ico'));
Or better, using the path
module:
app.use(favicon(path.join(__dirname,'public','images','favicon.ico')));
(note that this solution will work in express 3 apps as well)
According to the API, .favicon
accepts a location parameter:
app.use(express.favicon("public/images/favicon.ico"));
Most of the time, you might want this (as vsync suggested):
app.use(express.favicon(__dirname + '/public/images/favicon.ico'));
Or better yet, use the path
module (as Druska suggested):
app.use(express.favicon(path.join(__dirname, 'public','images','favicon.ico')));
According to the package description:
ETag
based on the contents of the icon, rather than file system properties.Content-Type
.Take a look also to the do { ... }
command since gnuplot 4.6 as it is very powerful:
do for [t=0:50] {
outfile = sprintf('animation/bessel%03.0f.png',t)
set output outfile
splot u*sin(v),u*cos(v),bessel(u,t/50.0) w pm3d ls 1
}
Here's another way to possibly answer your question using the find function which gives you a literal numerical value of where something truly is
open('file', 'r').read().find('')
in find write the word you want to find
and 'file'
stands for your file name
For people who searched for php multidimensional array get values
and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach
, which is array_column
For example, if I only want to get hotel_name
from the below array, and form to another array:
$hotels = [
[
'hotel_name' => 'Hotel A',
'info' => 'Hotel A Info',
],
[
'hotel_name' => 'Hotel B',
'info' => 'Hotel B Info',
]
];
I can do this using array_column
:
$hotel_name = array_column($hotels, 'hotel_name');
print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']
For the actual answer for this question, it can also be beautified by array_column
and call_user_func_array('array_merge', $twoDimensionalArray);
Let's make the data in PHP:
$hotels = [
[
'hotel_name' => 'Hotel A',
'info' => 'Hotel A Info',
'rooms' => [
[
'room_name' => 'Luxury Room',
'bed' => 2,
'boards' => [
'board_id' => 1,
'price' => 200
]
],
[
'room_name' => 'Non Luxy Room',
'bed' => 4,
'boards' => [
'board_id' => 2,
'price' => 150
]
],
]
],
[
'hotel_name' => 'Hotel B',
'info' => 'Hotel B Info',
'rooms' => [
[
'room_name' => 'Luxury Room',
'bed' => 2,
'boards' => [
'board_id' => 3,
'price' => 900
]
],
[
'room_name' => 'Non Luxy Room',
'bed' => 4,
'boards' => [
'board_id' => 4,
'price' => 300
]
],
]
]
];
And here's the calculation:
$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');
foreach($boards as $board){
$board_id = $board['board_id'];
$price = $board['price'];
echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}
Which will give you the following result:
Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300
In just 2 words: non-static ("instance") methods take a hidden pointer to "this" (as their 1st param) which is the object you call the method on.
That's the only difference with a regular standalone function, dynamic dispatching notwithstanding.
If you are interested, read the details below.
I'll try to be short and will use C++ as an example although what I say can be applied to virtually every language.
Ok, I said there's no actual difference. Let's dig a bit deeper:
Dynamic dispatching aside, it means it's as simple as that:
class User {
public string name; // I made it public intentionally
public void printName() {
cout << this.name << endl;
}
};
is equivalent to
public getName(User & user) {
cout << user.name << endl;
}
So, essentially, user->printName()
is just syntactic sugar for getName(user)
.
If you don't use dynamic dispatch, that's all. If it is used, then it's a bit more involved, but the compiler will still emit what looks like a function taking this
as a first parameter.
Since the API you're calling is async, the Parallel.ForEach
version doesn't make much sense. You shouldnt use .Wait
in the WaitAll
version since that would lose the parallelism Another alternative if the caller is async is using Task.WhenAll
after doing Select
and ToArray
to generate the array of tasks. A second alternative is using Rx 2.0
In Python 3 there is an exit()
function:
elif choice == "q":
exit()
Before doing
git clone https://example.com/root/test.git
make sure that you have added ssh key in your system. Follow this : https://gitlab.com/profile/keys .
Once added run the above command. It will prompt for your gitlab username and password and on authentication, it will be cloned.
MySQL Workbench also has this feature neatly in the GUI. Simply run a query, click the save icon next to Export/Import:
Then choose "SQL INSERT statements (*.sql)" in the list.
Enter a name, click save, confirm the table name and you will have your dump file.
I used Robert Lee`s answer and it works great! Just writing down the complete function i'm using:
function isMobileDevice(){
$aMobileUA = array(
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
//Return true if Mobile User Agent is detected
foreach($aMobileUA as $sMobileKey => $sMobileOS){
if(preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])){
return true;
}
}
//Otherwise return false..
return false;
}
Adding a quick snippet to have it ready to execute:
Source: myparser.py
import argparse
parser = argparse.ArgumentParser(description="Flip a switch by setting a flag")
parser.add_argument('-w', action='store_true')
args = parser.parse_args()
print args.w
Usage:
python myparser.py -w
>> True
The simple way to do this is doing a div within a div
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
<div class="server-action-menu" id="server_1">Server 1_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
<div class="server-action-menu" id="server_1">Server 2_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
<div class="server-action-menu" id="server_1">Server 3_x000D_
</div>_x000D_
</div>
_x000D_
I tried @JsonDetect
and
@JsonIgnoreProperties(value = { "handler", "hibernateLazyInitializer" })
Neither of them worked for me. Using a third-party module seemed like a lot of work to me. So I just tried making a get
call on any property of the lazy object before passing to jackson
for serlization. The working code snippet looked something like this :
@RequestMapping(value = "/authenticate", produces = "application/json; charset=utf-8")
@ResponseBody
@Transactional
public Account authenticate(Principal principal) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) principal;
LoggedInUserDetails loggedInUserDetails = (LoggedInUserDetails) usernamePasswordAuthenticationToken.getPrincipal();
User user = userRepository.findOne(loggedInUserDetails.getUserId());
Account account = user.getAccount();
account.getFullName(); //Since, account is lazy giving it directly to jackson for serlization didn't worked & hence, this quick-fix.
return account;
}
Here is a more efficient version which uses on
for all contenteditables. It's based off the top answers here.
$('body').on('focus', '[contenteditable]', function() {
const $this = $(this);
$this.data('before', $this.html());
}).on('blur keyup paste input', '[contenteditable]', function() {
const $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
});
The project is here: https://github.com/balupton/html5edit
You can override Django save method official doc about it.
The modified version of your code:
class Order(models.Model):
cart = models.ForeignKey(Cart)
add_date = models.DateTimeField(auto_now_add=True)
order_number = models.IntegerField(default=0) # changed here
enable = models.BooleanField(default=True)
def save(self, *args, **kwargs):
self.order_number = self.order_number + 1
super().save(*args, **kwargs) # Call the "real" save() method.
Another way is to use signals. More one:
A backreference to the whole match value is \g<0>
, see re.sub
documentation:
The backreference
\g<0>
substitutes in the entire substring matched by the RE.
See the Python demo:
import re
method = 'images/:id/huge'
print(re.sub(r':[a-z]+', r'<span>\g<0></span>', method))
# => images/<span>:id</span>/huge
This has nothing to do with the MULTILINE flag; what you're seeing is the difference between the find()
and matches()
methods. find()
succeeds if a match can be found anywhere in the target string, while matches()
expects the regex to match the entire string.
Pattern p = Pattern.compile("xyz");
Matcher m = p.matcher("123xyzabc");
System.out.println(m.find()); // true
System.out.println(m.matches()); // false
Matcher m = p.matcher("xyz");
System.out.println(m.matches()); // true
Furthermore, MULTILINE
doesn't mean what you think it does. Many people seem to jump to the conclusion that you have to use that flag if your target string contains newlines--that is, if it contains multiple logical lines. I've seen several answers here on SO to that effect, but in fact, all that flag does is change the behavior of the anchors, ^
and $
.
Normally ^
matches the very beginning of the target string, and $
matches the very end (or before a newline at the end, but we'll leave that aside for now). But if the string contains newlines, you can choose for ^
and $
to match at the start and end of any logical line, not just the start and end of the whole string, by setting the MULTILINE flag.
So forget about what MULTILINE
means and just remember what it does: changes the behavior of the ^
and $
anchors. DOTALL
mode was originally called "single-line" (and still is in some flavors, including Perl and .NET), and it has always caused similar confusion. We're fortunate that the Java devs went with the more descriptive name in that case, but there was no reasonable alternative for "multiline" mode.
In Perl, where all this madness started, they've admitted their mistake and gotten rid of both "multiline" and "single-line" modes in Perl 6 regexes. In another twenty years, maybe the rest of the world will have followed suit.
Jquery VS javascript, I am completely against the OP in this question. Comparison happens with two similar things, not in such case.
Jquery is Javascript. A javascript library to reduce vague coding, collection commonly used javascript functions which has proven to help in efficient and fast coding.
Javascript is the source, the actual scripts that browser responds to.
setContentView(R.layout.avtivity_next);
I think this line of code should be moved to the next activity...
@dannyeuu's answer is correct. pd.concat naturally does a join on index columns, if you set the axis option to 1. The default is an outer join, but you can specify inner join too. Here is an example:
x = pd.DataFrame({'a': [2,4,3,4,5,2,3,4,2,5], 'b':[2,3,4,1,6,6,5,2,4,2], 'val': [1,4,4,3,6,4,3,6,5,7], 'val2': [2,4,1,6,4,2,8,6,3,9]})
x.set_index(['a','b'], inplace=True)
x.sort_index(inplace=True)
y = x.__deepcopy__()
y.loc[(14,14),:] = [3,1]
y['other']=range(0,11)
y.sort_values('val', inplace=True)
z = x.__deepcopy__()
z.loc[(15,15),:] = [3,4]
z['another']=range(0,22,2)
z.sort_values('val2',inplace=True)
pd.concat([x,y,z],axis=1)
JQUERY FORMATCURRENCY PLUGIN
http://code.google.com/p/jquery-formatcurrency/
Make your life easy when working with dates, timestamps and durations. Use HalDateTime from
http://sourceforge.net/projects/haldatetime/?source=directory
For example you can just use it to parse your input like this:
HalDateTime mydate = HalDateTime.valueOf( "25.12.1988" );
System.out.println( mydate ); // will print in ISO format: 1988-12-25
You can also specify patterns for parsing and printing.
Thanks to Joachim answer, I use the code to clear all back stack entry finally.
// In your FragmentActivity use getSupprotFragmentManager() to get the FragmentManager.
// Clear all back stack.
int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
for (int i = 0; i < backStackCount; i++) {
// Get the back stack fragment id.
int backStackId = getSupportFragmentManager().getBackStackEntryAt(i).getId();
getSupportFragmentManager().popBackStack(backStackId,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
} /* end of for */
Assuming that you want to insert/update single row, most optimal approach is to use SQL Server's REPEATABLE READ
transaction isolation level:
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
BEGIN TRANSACTION
IF (EXISTS (SELECT * FROM myTable WHERE key=@key)
UPDATE myTable SET ...
WHERE key=@key
ELSE
INSERT INTO myTable (key, ...)
VALUES (@key, ...)
COMMIT TRANSACTION
This isolation level will prevent/block subsequent repeatable read transactions from accessing same row (WHERE key=@key
) while currently running transaction is open.
On the other hand, operations on another row won't be blocked (WHERE key=@key2
).
from the yii2 framework
/**
* Generates a random string of specified length.
* The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
*
* @param int $length the length of the key in characters
* @return string the generated random key
*/
function generateRandomString($length = 10) {
$bytes = random_bytes($length);
return substr(strtr(base64_encode($bytes), '+/', '-_'), 0, $length);
}
Here Is my code For Zip the folders and its sub folders and its files and make it downloadable in zip Format
function zip()
{
$source='path/folder'// Path To the folder;
$destination='path/folder/abc.zip'// Path to the file and file name ;
$include_dir = false;
$archive = 'abc.zip'// File Name ;
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
if (file_exists($destination)) {
unlink ($destination);
}
$zip = new ZipArchive;
if (!$zip->open($archive, ZipArchive::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
if ($include_dir) {
$arr = explode("/",$source);
$maindir = $arr[count($arr)- 1];
$source = "";
for ($i=0; $i < count($arr) - 1; $i++) {
$source .= '/' . $arr[$i];
}
$source = substr($source, 1);
$zip->addEmptyDir($maindir);
}
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
}
If Any Issue With the Code Let Me know.
Based on @ArchCodeMonkey answer.
If you have declare(strict_types=1)
you must cast second argument to string
If your margin is set on the body, then setting the background color of the html tag should color the margin area
html { background-color: black; }
body { margin:50px; background-color: white; }
Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color
You can add it like this
header('Location: http://linkhere.com/'.$url_endpoint);
As Toan suggests, a simple hack would be to just select the rows first, and then select the columns over that.
>>> a[[0,1,3], :] # Returns the rows you want
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[12, 13, 14, 15]])
>>> a[[0,1,3], :][:, [0,2]] # Selects the columns you want as well
array([[ 0, 2],
[ 4, 6],
[12, 14]])
np.ix_
I recently discovered that numpy gives you an in-built one-liner to doing exactly what @Jaime suggested, but without having to use broadcasting syntax (which suffers from lack of readability). From the docs:
Using ix_ one can quickly construct index arrays that will index the cross product.
a[np.ix_([1,3],[2,5])]
returns the array[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]
.
So you use it like this:
>>> a = np.arange(20).reshape((5,4))
>>> a[np.ix_([0,1,3], [0,2])]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
And the way it works is that it takes care of aligning arrays the way Jaime suggested, so that broadcasting happens properly:
>>> np.ix_([0,1,3], [0,2])
(array([[0],
[1],
[3]]), array([[0, 2]]))
Also, as MikeC says in a comment, np.ix_
has the advantage of returning a view, which my first (pre-edit) answer did not. This means you can now assign to the indexed array:
>>> a[np.ix_([0,1,3], [0,2])] = -1
>>> a
array([[-1, 1, -1, 3],
[-1, 5, -1, 7],
[ 8, 9, 10, 11],
[-1, 13, -1, 15],
[16, 17, 18, 19]])
That is okay for removing of data connections by using VBA as follows:
Sub deleteConn()
Dim xlBook As Workbook
Dim Cn As WorkbookConnection
Dim xlSheet As Worksheet
Dim Qt As QueryTable
Set xlBook = ActiveWorkbook
For Each Cn In xlBook.Connections
Debug.Print VarType(Cn)
Cn.Delete
Next Cn
For Each xlSheet In xlBook.Worksheets
For Each Qt In xlSheet.QueryTables
Debug.Print Qt.Name
Qt.Delete
Next Qt
Next xlSheet
End Sub
If you're doing whiteboard coding, an interview, or even just planning to use a tree, the verbosity of these is all a little much.
It should further be said that the reason a tree is not in there like, say, a Pair
(about which the same could be said), is because you should be encapsulating your data in the class using it, and the simplest implementation looks like:
/***
/* Within the class that's using a binary tree for any reason. You could
/* generalize with generics IFF the parent class needs different value types.
*/
private class Node {
public String value;
public Node[] nodes; // Or an Iterable<Node> nodes;
}
That's really it for an arbitrary width tree.
If you wanted a binary tree it's often easier to use with named fields:
private class Node { // Using package visibility is an option
String value;
Node left;
Node right;
}
Or if you wanted a trie:
private class Node {
String value;
Map<char, Node> nodes;
}
Now you said you want
to be able to get all the children (some sort of list or array of Strings) given an input string representing a given node
That sounds like your homework.
But since I'm reasonably sure any deadline has now passed…
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class kidsOfMatchTheseDays {
static private class Node {
String value;
Node[] nodes;
}
// Pre-order; you didn't specify.
static public List<String> list(Node node, String find) {
return list(node, find, new ArrayList<String>(), false);
}
static private ArrayList<String> list(
Node node,
String find,
ArrayList<String> list,
boolean add) {
if (node == null) {
return list;
}
if (node.value.equals(find)) {
add = true;
}
if (add) {
list.add(node.value);
}
if (node.nodes != null) {
for (Node child: node.nodes) {
list(child, find, list, add);
}
}
return list;
}
public static final void main(String... args) {
// Usually never have to do setup like this, so excuse the style
// And it could be cleaner by adding a constructor like:
// Node(String val, Node... children) {
// value = val;
// nodes = children;
// }
Node tree = new Node();
tree.value = "root";
Node[] n = {new Node(), new Node()};
tree.nodes = n;
tree.nodes[0].value = "leftish";
tree.nodes[1].value = "rightish-leafy";
Node[] nn = {new Node()};
tree.nodes[0].nodes = nn;
tree.nodes[0].nodes[0].value = "off-leftish-leaf";
// Enough setup
System.out.println(Arrays.toString(list(tree, args[0]).toArray()));
}
}
This gets you use like:
$ java kidsOfMatchTheseDays leftish
[leftish, off-leftish-leaf]
$ java kidsOfMatchTheseDays root
[root, leftish, off-leftish-leaf, rightish-leafy]
$ java kidsOfMatchTheseDays rightish-leafy
[rightish-leafy]
$ java kidsOfMatchTheseDays a
[]
This might be late however this method does what you ask in a perfect manner, it even shows the elements in ' table - like ' style, which is brilliant for beginners to really understand how an Multidimensional Array looks.
public static void display(int x[][]) // So we allow the method to take as input Multidimensional arrays
{
//Here we use 2 loops, the first one is for the rows and the second one inside of the rows is for the columns
for(int rreshti = 0; rreshti < x.length; rreshti++) // Loop for the rows
{
for(int kolona = 0; kolona < x[rreshti].length;kolona++) // Loop for the columns
{
System.out.print(x[rreshti][kolona] + "\t"); // the \t simply spaces out the elements for a clear view
}
System.out.println(); // And this empty outputprint, simply makes sure each row (the groups we wrote in the beggining in seperate {}), is written in a new line, to make it much clear and give it a table-like look
}
}
After you complete creating this method, you simply put this into your main method:
display(*arrayName*); // So we call the method by its name, which can be anything, does not matter, and give that method an input (the Array's name)
NOTE. Since we made the method so that it requires Multidimensional Array as a input it wont work for 1 dimensional arrays (which would make no sense anyways)
Source: enter link description here
PS. It might be confusing a little bit since I used my language to name the elements / variables, however CBA to translate them, sorry.
Just figure out the difference in seconds (don't forget JS timestamps are actually measured in milliseconds) and decompose that value:
// get total seconds between the times
var delta = Math.abs(date_future - date_now) / 1000;
// calculate (and subtract) whole days
var days = Math.floor(delta / 86400);
delta -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
// what's left is seconds
var seconds = delta % 60; // in theory the modulus is not required
EDIT code adjusted because I just realised that the original code returned the total number of hours, etc, not the number of hours left after counting whole days.
Response.Write(@"<script language='javascript'>alert('Message:
\n" + "Hi!" + " .');</script>");
You have to do it the ugly way. If you really want something like this, you can check out CoffeeScript, which has that and a whole lot of other features that make it look more like python (sorry for making it sound like an advertisement, but I really like it.)