You can use yourstring.split("\x09"); I tested it, and it works.
For the particular case of Windows 10 October 2018 Update or later activedirectory
module is not available unless the optional feature RSAT: Active Directory Domain Services and Lightweight Directory Services Tools
is installed (instructions here + uncollapse install instructions).
Reopen Windows Powershell and import-module activedirectory
will work as expected.
It appears that in PHP you are obtaining the value of the submit button, not the select input. If you are using GET you will want to use $_GET['website_string']
or POST would be $_POST['website_string']
.
You will probably want the following HTML:
<select name="website_string">
<option value="" selected="selected"></option>
<option value="abc">ABC</option>
<option value="def">def</option>
<option value="hij">hij</option>
</select>
<input type="submit" />
With some PHP that looks like this:
<?php
$website_string = $_POST['website_string']; // or $_GET['website_string'];
?>
As You're getting values from textfield as jTextField3.getText();
.
As it is a textField
it will return you string format as its format says:
String getText()
Returns the text contained in this TextComponent.
So, convert your String
to Integer
as:
int jml = Integer.parseInt(jTextField3.getText());
instead of directly setting
int jml = jTextField3.getText();
The solution by dglmtn doesn't work when you have a 9-patch drawable with padding as background. Strange things happen, I don't even want to talk about it, if you have such a problem, you know them.
Now, If you want to have a listview with different states and 9-patch drawables (it would work with any drawables and colors, I think) you have to do 2 things:
What you should do is first set the row_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_enabled="true"
android:state_pressed="true" android:drawable="@drawable/list_item_bg_pressed" />
<item android:state_enabled="true"
android:state_focused="true" android:drawable="@drawable/list_item_bg_focused" />
<item android:state_enabled="true"
android:state_selected="true" android:drawable="@drawable/list_item_bg_focused" />
<item
android:drawable="@drawable/list_item_bg_normal" />
</selector>
Don't forget the android:state_selected
. It works like android:state_focused
for the list, but it's applied for the list item.
Now apply the selector to the items (row.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/row_selector"
>
...
</RelativeLayout>
Make a transparent selector for the list:
<ListView
android:id="@+id/android:list"
...
android:listSelector="@android:color/transparent"
/>
This should do the thing.
If choice
is available, use this:
choice /C X /T 10 /D X > nul
where /T 10
is the number of seconds to delay.
Note the syntax can vary depending on your Windows version, so use CHOICE /?
to be sure.
Use Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage
And you can convert the entire object to a string, filename.json is expected to be located in documents folder.
var text = File.ReadAllText("filename.json");
var json = JsonValue.Parse(text);
while (JsonValue.Null != null)
{
Console.WriteLine(json.ToString());
}
Console.ReadLine();
How about the assign
member function?
some_vector.assign(some_vector.size(), 0);
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
Just as an FYI, you can also specify those things as column attributes. For instance, I might have done:
.order_by(model.Entry.amount.desc())
This is handy since it avoids an import
, and you can use it on other places such as in a relation definition, etc.
For more information, you can refer this
If you're using a JetBrains IDE (like IntelliJ IDEA, Android Studio, PyCharm), you can drag the patch file and drop it inside the IDE, and a dialog will appear, showing the patch's content. All you have to do now is to click "Apply patch", and a commit will be created.
you can use _.castArray(obj).
example:
_.castArray({ 'a': 1 });
// => [{ 'a': 1 }]
Try this library:
https://github.com/avast/android-styled-dialogs
It's based on DialogFragments
instead of AlertDialogs
(like the one from @afollestad). The main advantage: Dialogs don't dismiss after rotation and callbacks still work.
No need to initialize an empty DataFrame (you weren't even doing that, you'd need pd.DataFrame()
with the parens).
Instead, to create a DataFrame where each series is a column,
series
, and df = pd.concat(series, axis=1)
Something like:
series = [pd.Series(mat[name][:, 1]) for name in Variables]
df = pd.concat(series, axis=1)
For me, I have fixed the problem using android:layout_centerVertical="true"
in a parent RelativeLayout
:
<RelativeLayout ... >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerVertical="true">
</RelativeLayout>
Numpy approach and timings against a list/array with 1.000.000 elements:
Timings:
In [10]: a.shape
Out[10]: (1000000,)
In [13]: len(lst)
Out[13]: 1000000
In [18]: %timeit a[a != 2]
100 loops, best of 3: 2.94 ms per loop
In [19]: %timeit [x for x in lst if x != 2]
10 loops, best of 3: 79.7 ms per loop
Conclusion: numpy is 27 times faster (on my notebook) compared to list comprehension approach
PS if you want to convert your regular Python list lst
to numpy array:
arr = np.array(lst)
Setup:
import numpy as np
a = np.random.randint(0, 1000, 10**6)
In [10]: a.shape
Out[10]: (1000000,)
In [12]: lst = a.tolist()
In [13]: len(lst)
Out[13]: 1000000
Check:
In [14]: a[a != 2].shape
Out[14]: (998949,)
In [15]: len([x for x in lst if x != 2])
Out[15]: 998949
As some of the answers point out, createdb
is a command line utility that could be used to create database.
Assuming you have a user named dbuser
, the following command could be used to create a database and provide access to dbuser
:
createdb -h localhost -p 5432 -U dbuser testdb
Replace localhost
with your correct DB host name, 5432
with correct DB port, and testdb
with the database name you want to create.
Now psql
could be used to connect to this newly created database:
psql -h localhost -p 5432 -U dbuser -d testdb
Tested with createdb
and psql
versions 9.4.15
.
Use sum()
in place of count()
Try below:
SELECT
ccc_news . * ,
SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments
FROM
ccc_news
LEFT JOIN
ccc_news_comments
ON
ccc_news_comments.news_id = ccc_news.news_id
WHERE
`ccc_news`.`category` = 'news_layer2'
AND `ccc_news`.`status` = 'Active'
GROUP BY
ccc_news.news_id
ORDER BY
ccc_news.set_order ASC
LIMIT 20
> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300
ubuntu$> vi source.cpp
:set binary noeol
there is no reliable way to do it, and I would not even try it, once the request is on the go; the only way to react reasonably is to ignore the response.
in most cases, it may happen in situations like: a user clicks too often on a button triggering many consecutive XHR, here you have many options, either block the button till XHR is returned, or dont even trigger new XHR while another is running hinting the user to lean back - or discard any pending XHR response but the recent.
This is supposedly because you trying to make cross-domain request, or something that is clarified as it.
You could try adding header('Access-Control-Allow-Origin: *');
to the requested file.
Also, such problem is sometimes occurs on server-sent events implementation in case of using event-source
or XHR polling
in IE 8-10 (which confused me first time).
In my case also \n was not working, I fixed issue by keeping number of lines to 0 and copied and pasted the text with new line itself for example instead of Hello \n World i pasted
Hello
World
in the interface builder.
Would this parser help you?
https://github.com/fiann/jquery.ogp
It parses meta OG data to JSON, so you can just use the data directly. If you prefer, you can read/write them directly using JQuery, of course. For example:
$("meta[property='og:title']").attr("content", document.title);
$("meta[property='og:url']").attr("content", location.toString());
Note the single-quotes around the attribute values; this prevents parse errors in jQuery.
If there's any chance that your datetimes aren't strict calendar dates, you should consider using enddate exclusion comparisons... This will prevent you from missing any requests created during the date of Jan 31.
DateTime now = DateTime.Now;
DateTime thisMonth = new DateTime(now.Year, now.Month, 1);
DateTime lastMonth = thisMonth.AddMonths(-1);
var RequestIds = rdc.request
.Where(r => lastMonth <= r.dteCreated)
.Where(r => r.dteCreated < thisMonth)
.Select(r => r.intRequestId);
See what I've done here: http://jsfiddle.net/dyarbrough93/c8wEC/
First off, you never set the dimensions of the overlay, meaning it wasn't showing up in the first place. Secondly, I recommend just changing the z-index of the overlay when you hover over the image. Change the opacity / color of the overlay to suit your needs.
.image { position: relative; width: 200px; height: 200px;}
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; background-color: gray; z-index: -10; width: 200px; height: 200px; opacity: 0.5}
.image:hover .overlay { z-index: 10}
I had the same issue. I just resolved this by updating the assembly via GAC.
To use gacutil on a development machine go to:
Start -> programs -> Microsoft Visual studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt (2010)
.
I used these commands to uninstall and Reinstall respectively.
gacutil /u myDLL
gacutil /i "C:\Program Files\Custom\mydllname.dll"
Note: i have not uninstall my dll in my case i have just updated dll with current path.
This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.
Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:
http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/
A (partial) practical work-around is to put things into a throw-away function.
Pasting
x = 1
x += 1
print(x)
results in
>>> x = 1
x += 1
print(x)
File "<stdin>", line 1
x += 1
print(x)
^
SyntaxError: multiple statements found while compiling a single statement
>>>
However, pasting
def abc():
x = 1
x += 1
print(x)
works:
>>> def abc():
x = 1
x += 1
print(x)
>>> abc()
2
>>>
Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython
/ jupyter qtconsole
is probably the next simplest option.
The above solutions suggesting the use of regex aren't ideal because this is such a small task and regex requires more resource overhead than the simplicity of the task justifies.
Here's what I do:
myString = myString.replace(' ', '').replace('\t', '').replace('\n', '')
or if you had a bunch of things to remove such that a single line solution would be gratuitously long:
removal_list = [' ', '\t', '\n']
for s in removal_list:
myString = myString.replace(s, '')
I might be misunderstanding your question, so apologies if I am.
If you're looking for the words "Quid", "Application Number", etc. to be bold, just wrap them in <strong>
tags:
<strong>Quid</strong>: ...
Hope that helps!
You can also do the following:
CREATE TABLE #TEMPTABLE
(
Column1 type1,
Column2 type2,
Column3 type3
)
INSERT INTO #TEMPTABLE
SELECT ...
SELECT *
FROM #TEMPTABLE ...
DROP TABLE #TEMPTABLE
Well, more technically speaking, the difference between a static method and a virtual method is the way the are linked.
A traditional "static" method like in most non OO languages gets linked/wired "statically" to its implementation at compile time. That is, if you call method Y() in program A, and link your program A with library X that implements Y(), the address of X.Y() is hardcoded to A, and you can not change that.
In OO languages like JAVA, "virtual" methods are resolved "late", at run-time, and you need to provide an instance of a class. So in, program A, to call virtual method Y(), you need to provide an instance, B.Y() for example. At runtime, every time A calls B.Y() the implementation called will depend on the instance used, so B.Y() , C.Y() etc... could all potential provide different implementations of Y() at runtime.
Why will you ever need that? Because that way you can decouple your code from the dependencies. For example, say program A is doing "draw()". With a static language, thats it, but with OO you will do B.draw() and the actual drawing will depend on the type of object B, which, at runtime, can change to square a circle etc. That way your code can draw multiple things with no need to change, even if new types of B are provided AFTER the code was written. Nifty -
It's probably easiest to have a function to pick a random value from an array. This is more generic, and is straightforward to call.
<T> T randomValue(T[] values) {
return values[mRandom.nextInt(values.length)];
}
Call like so:
MyEnum value = randomValue(MyEnum.values());
Please check if you open up a new connection with each of your requests (mysql_connect(...)). If you do so, make sure you close the connection afterwards (using mysql_close($link)).
Also, you should consider changing this behaviour as keeping one steady connection for each user may be a better way to accomplish your task.
If you didn't already, take a look at this obvious, but nonetheless useful information resource: http://php.net/manual/function.mysql-connect.php
Eclipse's compiler can assure that your java sources conform to a given JDK version even if you don't have that version installed. This feature is useful for ensuring backwards compatibility of your code.
Your code will still be compiled and run by the JDK you've selected.
Use mvn -X
or mvn --debug
to find out from which different locations Maven reads settings.xml. This switch activates debug logging. Just check the first lines of mvn --debug | findstr /i /c:using /c:reading
.
Right, Maven uses the Java system property user.home
as location for the .m2 folder.
But user.home
does not always resolve to %USERPROFILE%\.m2
. If you have moved the location of your Desktop folder to another place, user.home
might resolve to the parent directory of this new Desktop folder. This happens when using Windows Vista or a more recent Windows together with Java 7 or any older Java version.
The blog post Java’s “user.home” is Wrong on Windows describes it very well and gives links to the official bug reports. The bug is marked as resolved in Java 8. The comment of the blog's visitor Lars proposes a nice workaround.
You can use this:
string alpha = "abcdefghijklmnopqrstuvwxyz";
int length = alpha.Length;
for (int i = length - ((length - 1) % 5 + 1); i > 0; i -= 5)
{
alpha = alpha.Insert(i, "-");
}
Works perfectly with any string. As always, the size doesn't matter. ;)
This works for me (dont use the extension of the image, just the name):
String imagename = "myImage";
int res = getResources().getIdentifier(imagename, "drawable", this.getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(res);
I am making a blog website on github pages. I got an idea to embbed comments in the end of every blog page. I understand how firebase get and gives you data.
I have tested many times with project and even using console. I am totally disagree the saying vlit is vulnerable. Believe me there is no issue of showing your api key publically if you have followed privacy steps recommend by firebase. Go to https://console.developers.google.com/apis and perfrom a security steup.
Supported in: 4, 3.5 SP1, you can now just call a method on the object.
DataTable dataTable2 = dataTable1.Copy()
If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a
and b
:
import json
a = json.loads("""
{
"errors": [
{"error": "invalid", "field": "email"},
{"error": "required", "field": "name"}
],
"success": false
}
""")
b = json.loads("""
{
"success": false,
"errors": [
{"error": "required", "field": "name"},
{"error": "invalid", "field": "email"}
]
}
""")
>>> sorted(a.items()) == sorted(b.items())
False
... but that doesn't work, because in each case, the "errors"
item of the top-level dict is a list with the same elements in a different order, and sorted()
doesn't try to sort anything except the "top" level of an iterable.
To fix that, we can define an ordered
function which will recursively sort any lists it finds (and convert dictionaries to lists of (key, value)
pairs so that they're orderable):
def ordered(obj):
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj
If we apply this function to a
and b
, the results compare equal:
>>> ordered(a) == ordered(b)
True
This one liner helps me while creating dump of a single database.
PGPASSWORD="yourpassword" pg_dump -U postgres -h localhost mydb > mydb.pgsql
It it possible to do in the admin, but there is not a very straightforward way to it. Also, I would like to advice to keep most business logic in your models, so you won't be dependent on the Django Admin.
Maybe it would be easier (and maybe even better) if you have the two seperate fields on your model. Then add a method on your model that combines them.
For example:
class MyModel(models.model):
field1 = models.CharField(max_length=10)
field2 = models.CharField(max_length=10)
def combined_fields(self):
return '{} {}'.format(self.field1, self.field2)
Then in the admin you can add the combined_fields()
as a readonly field:
class MyModelAdmin(models.ModelAdmin):
list_display = ('field1', 'field2', 'combined_fields')
readonly_fields = ('combined_fields',)
def combined_fields(self, obj):
return obj.combined_fields()
If you want to store the combined_fields
in the database you could also save it when you save the model:
def save(self, *args, **kwargs):
self.field3 = self.combined_fields()
super(MyModel, self).save(*args, **kwargs)
for your exact sample, it should be like this.
DECLARE @m INT
SET @m = 321%11
SELECT @m
If you know the some content of the file you can try to decode it with several encoding and see which is missing. In general there is no way since a text file is a text file and those are stupid ;)
After looking at all of the answers, the one that helped me was providing proxy values in-line with the install command. One of my frustrations was adding the domain to my username. This is not needed. I used the following example to install a specific version of Angular:
npm install -g @angular/[email protected] --proxy "http://username:password@proxy_server:proxy_port" --registry http://registry.npmjs.org
I would like to expand open jfs's answer, which worked great for my problem: sorting two lists by a third, decorated list:
We can create our decorated list in any way, but in this case we will create it from the elements of one of the two original lists, that we want to sort:
# say we have the following list and we want to sort both by the algorithms name
# (if we were to sort by the string_list, it would sort by the numerical
# value in the strings)
string_list = ["0.123 Algo. XYZ", "0.345 Algo. BCD", "0.987 Algo. ABC"]
dict_list = [{"dict_xyz": "XYZ"}, {"dict_bcd": "BCD"}, {"dict_abc": "ABC"}]
# thus we need to create the decorator list, which we can now use to sort
decorated = [text[6:] for text in string_list]
# decorated list to sort
>>> decorated
['Algo. XYZ', 'Algo. BCD', 'Algo. ABC']
Now we can apply jfs's solution to sort our two lists by the third
# create and sort the list of indices
sorted_indices = list(range(len(string_list)))
sorted_indices.sort(key=decorated.__getitem__)
# map sorted indices to the two, original lists
sorted_stringList = list(map(string_list.__getitem__, sorted_indices))
sorted_dictList = list(map(dict_list.__getitem__, sorted_indices))
# output
>>> sorted_stringList
['0.987 Algo. ABC', '0.345 Algo. BCD', '0.123 Algo. XYZ']
>>> sorted_dictList
[{'dict_abc': 'ABC'}, {'dict_bcd': 'BCD'}, {'dict_xyz': 'XYZ'}]
In fact, it is very easy.
composer update
will do all this for you, but it will also update the other packages.
To remove a package without updating the others, specifiy that package in the command, for instance:
composer update monolog/monolog
will remove the monolog/monolog
package.
Nevertheless, there may remain some empty folders or files that cannot be removed automatically, and that have to be removed manually.
$(option).removeAttr('selected') //replace 'option' with selected option's selector
I was also getting the same issue I tried multiple IPs like my public IP and localhost default IP 127.0.0.1 in windows and default gateway but same response. but I forget to check by
C:> ipconfig
ipconfig cleanly say what is my actual IP address of that adapter with which I have connected like I was connected with Wifi adapter my IP address will show me as:
Wireless LAN adapter Wireless Network Connection:
Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : fe80::69fa:9475:431e:fad7%11
IPv4 Address. . . . . . . . . . . : 192.168.15.92
I hope this will help you.
A couple of answers that should work above but this is how i would write it.
Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.
add-text.tpl.html
<div ng-controller="myController">
<form ng-submit="addText(myText)">
<input type="text" placeholder="Let's Go" ng-model="myText">
<button type="submit">Add</button>
</form>
<ul>
<li ng-repeat="text in arrayText">{{ text }}</li>
</ul>
</div>
app.js
(function() {
function myController($scope) {
$scope.arrayText = ['hello', 'world'];
$scope.addText = function(myText) {
$scope.arrayText.push(myText);
};
}
angular.module('app', [])
.controller('myController', myController);
})();
You can use
app:cardBackgroundColor="@color/red"
or
android:backgroundTint="@color/red"
I would use JPA's constructor expression feature. See also following answer:
JPQL Constructor Expression - org.hibernate.hql.ast.QuerySyntaxException:Table is not mapped
Following the example in the question, it would be something like this.
SELECT DISTINCT new com.mypackage.MyNameType(c.name) from Customer c
np.convolve
needs a flattened array as one of it's inputs, you can use numpy.ndarray.flatten()
which is quite fast, find it here.
You should try doing it with css3 animation. Check the code bellow:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
position: relative;
-webkit-animation: myfirst 5s infinite; /* Chrome, Safari, Opera */
-webkit-animation-direction: alternate; /* Chrome, Safari, Opera */
animation: myfirst 5s infinite;
animation-direction: alternate;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
0% {background: red; left: 0px; top: 0px;}
25% {background: yellow; left: 200px; top: 0px;}
50% {background: blue; left: 200px; top: 200px;}
75% {background: green; left: 0px; top: 200px;}
100% {background: red; left: 0px; top: 0px;}
}
@keyframes myfirst {
0% {background: red; left: 0px; top: 0px;}
25% {background: yellow; left: 200px; top: 0px;}
50% {background: blue; left: 200px; top: 200px;}
75% {background: green; left: 0px; top: 200px;}
100% {background: red; left: 0px; top: 0px;}
}
</style>
</head>
<body>
<p><strong>Note:</strong> The animation-direction property is not supported in Internet Explorer 9 and earlier versions.</p>
<div></div>
</body>
</html>
Where 'div' is your animated object.
I hope you find this useful.
Thanks.
To add and enhance the other answers, in the console, enter $($0)
to get the element. If it's an Angularjs application, a jQuery lite version is loaded by default.
If you are not using jQuery, you can use angular.element($0) as in:
angular.element($0).scope()
To check if you have jQuery and the version, run this command in the console:
$.fn.jquery
If you have inspected an element, the currently selected element is available via the command line API reference $0. Both Firebug and Chrome have this reference.
However, the Chrome developer tools will make available the last five elements (or heap objects) selected through the properties named $0, $1, $2, $3, $4 using these references. The most recently selected element or object can be referenced as $0, the second most recent as $1 and so on.
Here is the Command Line API reference for Firebug that lists it's references.
$($0).scope()
will return the scope associated with the element. You can see its properties right away.
Some other things that you can use are:
$($0).scope().$parent
.
$($0).scope().$parent.$parent
$($0).scope().$root
$($0).isolateScope()
See Tips and Tricks for Debugging Unfamiliar Angularjs Code for more details and examples.
I think the prop method is more convenient when it comes to boolean attribute. http://api.jquery.com/prop/
This never gonna work, you can't stringify your FormData object.
You should do this:
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var fd = new FormData();
fd.append('title', title);
fd.append('text', text);
fd.append('file', file);
$http.post(uploadUrl, obj, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
blockUI.stop();
})
.error(function(error){
toaster.pop('error', 'Errore', error);
});
}
try this : worked for me
rm -rf .git
You can use mv
instead of rm
if you don't want to loose your stashed commits
then copy .git from other clone
cp <pathofotherrepository>/.git . -r
then do
git init
this should solve your problem , ALL THE BEST
Use StringBuilder's append line built-in functions:
StringBuilder sb = new StringBuilder();
sb.AppendLine("First line");
sb.AppendLine("Second line");
sb.AppendLine("Third line");
First line
Second line
Third line
You may want to use the BIT
data type, probably setting is as NOT NULL
:
Quoting the MSDN article:
bit (Transact-SQL)
An integer data type that can take a value of 1, 0, or NULL.
The SQL Server Database Engine optimizes storage of bit columns. If there are 8 or less bit columns in a table, the columns are stored as 1 byte. If there are from 9 up to 16 bit columns, the columns are stored as 2 bytes, and so on.
The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.
You could convert it to an array and then print that out with Arrays.toString(Object[])
:
System.out.println(Arrays.toString(stack.toArray()));
In most browsers, you can use a javascript variable instead of using document.getElementById
. Say your html body content is like this:
<section id="mySection"> Hello </section>
Then you can just refer to mySection
as a variable in javascript:
mySection.innerText += ', world'
// same as: document.getElementById('mySection').innerText += ', world'
See this snippet:
mySection.innerText += ', world!'
_x000D_
<section id="mySection"> Hello </section>
_x000D_
I recommend using the os module to avoid trouble in cross-platform. (windows,linux,mac)
Cause if the directory doesn't exists, it will return an exception.
import os
filepath = os.path.join('c:/your/full/path', 'filename')
if not os.path.exists('c:/your/full/path'):
os.makedirs('c:/your/full/path')
f = open(filepath, "a")
If this will be a function for a system or something, you can improve it by adding try/except for error control.
In Valid architectures: Select each entry (release, debug) and build and press backspace. It should work
Not removing but creating a new List
without that element with LINQ:
// remove
users = users.Where(u => u.userId != 123).ToList();
// new list
var modified = users.Where(u => u.userId == 123).ToList();
You can simply set the status code of the response to 200 like the following
public ActionResult SomeMethod(parameters...)
{
//others code here
...
Response.StatusCode = 200;
return YourObject;
}
There is a (somewhat) related question on StackOverflow:
Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeeze
d or sliced into a 2D array.
More generally, the reason for the Exception
TypeError: Invalid dimensions for image data
is shown here: matplotlib.pyplot.imshow()
needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!
You can easily check this with (these checks are done by imshow
, this function is only meant to give a more specific message in case it's not a valid input):
from __future__ import print_function
import numpy as np
def valid_imshow_data(data):
data = np.asarray(data)
if data.ndim == 2:
return True
elif data.ndim == 3:
if 3 <= data.shape[2] <= 4:
return True
else:
print('The "data" has 3 dimensions but the last dimension '
'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
''.format(data.shape[2]))
return False
else:
print('To visualize an image the data must be 2 dimensional or '
'3 dimensional, not "{}".'
''.format(data.ndim))
return False
In your case:
>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False
The np.asarray
is what is done internally by matplotlib.pyplot.imshow
so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list
) it's necessary.
In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()
import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0) # or axis=1
plt.imshow(a)
plt.show()
or just use something that accepts 1D arrays like plot
:
a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()
Target build x64 Target Server Hosting IIS 64 Bit
Right Click appPool hosting running the website/web application and set the enable 32 bit application = false.
<html>
<head>
<title>Test</title>
<script language="javascript">
function checkInput(ob) {
var invalidChars = /[^0-9]/gi
if(invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars,"");
}
}
</script>
</head>
<body>
<input type="text" onkeyup="checkInput(this)"/>
</body>
</html>
I had same problem when I define PATH below
C:\Program Files (x86)\Java\jre1.8.0_45\bin;C:\dev\sdk\android\platform-tools
and the problem solved when I bring adb root at first.
C:\dev\sdk\android\platform-tools;C:\Program Files (x86)\Java\jre1.8.0_45\bin
As a continues to @chaokunyang answer, I want to put here the script I write that does the work:
"requirements.txt" file
docker==4.4.0
Packer side: file name: "create-offline-python3.6-dependencies-repository.sh"
#!/usr/bin/env bash
# This script follows the steps described in this link:
# https://stackoverflow.com/a/51646354/8808983
LIBRARIES_DIR="python3.6-wheelhouse"
if [ -d ${LIBRARIES_DIR} ]; then
rm -rf ${LIBRARIES_DIR}/*
else
mkdir ${LIBRARIES_DIR}
fi
pip download -r requirements.txt -d ${LIBRARIES_DIR}
files_to_add=("requirements.txt" "install-python-libraries-offline.sh")
for file in "${files_to_add[@]}"; do
echo "Adding file ${file}"
cp "$file" ${LIBRARIES_DIR}
done
tar -cf ${LIBRARIES_DIR}.tar ${LIBRARIES_DIR}
Installer side: file name: "install-python-libraries-offline.sh"
#!/usr/bin/env bash
# This script follows the steps described in this link:
# https://stackoverflow.com/a/51646354/8808983
# This file should run during the installation process from inside the libraries directory, after it was untared:
# pythonX-wheelhouse.tar -> untar -> pythonX-wheelhouse
# |
# |--requirements.txt
# |--install-python-libraries-offline.sh
pip3 install -r requirements.txt --no-index --find-links .
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
I presume your application uses a masked edit box? This is a relatively well known problem, documented by Microsoft here:
http://support.microsoft.com/kb/177088
The article refers to VB4 and 5, but I am pretty sure the same is true for VB6.
EDIT
On further research, I am finding references to this problem with other controls as well. Recompiling your application on Windows XP for users that are running XP will probably produce them a working version, though it's not an ideal solution...
Generally, the "specialized structure" actually IS a sensible current state of an object, with its own methods.
class Some3SpaceThing(object):
def __init__(self,x):
self.g(x)
def g(self,x):
self.y0 = x + 1
self.y1 = x * 3
self.y2 = y0 ** y3
r = Some3SpaceThing( x )
r.y0
r.y1
r.y2
I like to find names for anonymous structures where possible. Meaningful names make things more clear.
It is highly unlikely that adding NameVirtualHost *:443
is the right solution, because there are a limited number of situations in which it is possible to support name-based virtual hosts over SSL. Read this and this for some details (there may be better docs out there; these were just ones I found that discuss the issue in detail).
If you're running a relatively stock Apache configuration, you probably have this somewhere:
<VirtualHost _default_:443>
Your best bet is to either:
VirtualHost
container, or VirtualHost
block and create a new one. Don't forget to include all the relevant SSL options.You can configure your pod with a grace period (for example 30 seconds or more, depending on container startup time and image size) and set "imagePullPolicy: "Always"
. And use kubectl delete pod pod_name
.
A new container will be created and the latest image automatically downloaded, then the old container terminated.
Example:
spec:
terminationGracePeriodSeconds: 30
containers:
- name: my_container
image: my_image:latest
imagePullPolicy: "Always"
I'm currently using Jenkins for automated builds and image tagging and it looks something like this:
kubectl --user="kube-user" --server="https://kubemaster.example.com" --token=$ACCESS_TOKEN set image deployment/my-deployment mycontainer=myimage:"$BUILD_NUMBER-$SHORT_GIT_COMMIT"
Another trick is to intially run:
kubectl set image deployment/my-deployment mycontainer=myimage:latest
and then:
kubectl set image deployment/my-deployment mycontainer=myimage
It will actually be triggering the rolling-update but be sure you have also imagePullPolicy: "Always"
set.
Update:
another trick I found, where you don't have to change the image name, is to change the value of a field that will trigger a rolling update, like terminationGracePeriodSeconds
. You can do this using kubectl edit deployment your_deployment
or kubectl apply -f your_deployment.yaml
or using a patch like this:
kubectl patch deployment your_deployment -p \
'{"spec":{"template":{"spec":{"terminationGracePeriodSeconds":31}}}}'
Just make sure you always change the number value.
The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName
to be the name of the file you wish to open.
Private Const TargetWBName As String = "myworkbook.xlsx"
'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
WorkbookOpen = False
On Error GoTo WorkBookNotOpen
If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
WorkbookOpen = True
Exit Function
End If
WorkBookNotOpen:
End Function
Private Sub Workbook_Open()
'Check if our target workbook is open
If WorkbookOpen(TargetWBName) = False Then
'set calculation to manual
Application.Calculation = xlCalculationManual
Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
DoEvents
Me.Close False
End If
End Sub
Set the constant 'TargetWBName' to be the name of the workbook that you wish to open.
This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself.
*NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True
after Me.Close
Here are some links that I found on face recognition libraries.
Image Identification links:
I tried this out for transmitting continuous data (float values converted to string) from my PC (MATLAB) to my phone. But, still my App misreads the delimiter '\n' and still data gets garbled. So, I took the character 'N' as the delimiter rather than '\n' (it could be any character that doesn't occur as part of your data) and I've achieved better transmission speed - I gave just 0.1 seconds delay between transmitting successive samples - with more than 99% data integrity at the receiver i.e. out of 2000 samples (float values) that I transmitted, only 10 were not decoded properly in my application.
My answer in short is: Choose a delimiter other than '\r' or '\n' as these create more problems for real-time data transmission when compared to other characters like the one I've used. If we work more, may be we can increase the transmission rate even more. I hope my answer helps someone!
http://rusanu.com/2006/01/30/how-long-should-i-expect-alter-databse-set-enable_broker-to-run/
alter database [<dbname>] set enable_broker with rollback immediate;
There is a simple way for @Sprunth's answer.
private void GetAllDiskDrives()
{
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject wmi_HD in searcher.Get())
{
HardDrive hd = new HardDrive();
hd.Model = wmi_HD["Model"].ToString();
hd.InterfaceType = wmi_HD["InterfaceType"].ToString();
hd.Caption = wmi_HD["Caption"].ToString();
hd.SerialNo =wmi_HD.GetPropertyValue("SerialNumber").ToString();//get the serailNumber of diskdrive
hdCollection.Add(hd);
}
}
public class HardDrive
{
public string Model { get; set; }
public string InterfaceType { get; set; }
public string Caption { get; set; }
public string SerialNo { get; set; }
}
You can try this
Process[] processes = Process.GetProcessesByName("processname");
foreach (Process p in processes)
{
IntPtr pFoundWindow = p.MainWindowHandle;
// Do something with the handle...
//
}
In Package Manager Console:
Update-Database Your_Migration_You_Want_To_Revert_To
More options and explanation on how to revert migrations can be seen here
Shorter example using http.get:
require('http').get('http://httpbin.org/ip', (res) => {
res.setEncoding('utf8');
res.on('data', function (body) {
console.log(body);
});
});
class App():
def __init__(self):
self.root = Tkinter.Tk()
button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
button.pack()
self.root.mainloop()
def quit(self):
self.root.destroy()
app = App()
The removeAttr()
function only removes HTML attributes. The display
is not a HTML attribute, it's a CSS property. You'd like to use css()
function instead to manage CSS properties.
But jQuery offers a show()
function which does exactly what you want in a concise call:
$("span").show();
In the latest version of the SDK, you would use the setBackgroundResource
method.
public void onClick(View v) {
if(v == ButtonName) {
ButtonName.setBackgroundResource(R.drawable.ImageResource);
}
}
This is how you can nest multiple bool queries in one outer bool query this using Kibana,
GET my_inedx/my_type/_search
{
"query" : {
"bool": { //bool indicates we are using boolean operator
"must" : [ //must is for **AND**
{
"match" : {
"description" : "some text"
}
},
{
"match" :{
"type" : "some Type"
}
},
{
"bool" : { //here its a nested boolean query
"should" : [ //should is for **OR**
{
"match" : {
//ur query
}
},
{
"match" : {}
}
]
}
}
]
}
}
}
This is how you can nest a query in ES
There are more types in "bool" like,
java.util.Date
is independent of the timezone. When you print cal_Two
though the Calendar
instance has got its timezone set to UTC
, cal_Two.getTime()
would return a Date
instance which does not have a timezone (and is always in the default timezone)
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
System.out.println(cal_Two.getTimeZone());
Output:
Sat Jan 25 16:40:28 IST 2014
sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
From the javadoc of TimeZone.setDefault()
Sets the TimeZone that is returned by the getDefault method. If zone is null, reset the default to the value it had originally when the VM first started.
Hence, moving your setDefault()
before cal_Two
is instantiated you would get the correct result.
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
Calendar cal_Three = Calendar.getInstance();
System.out.println(cal_Three.getTime());
Output:
Sat Jan 25 11:15:29 UTC 2014
Sat Jan 25 11:15:29 UTC 2014
If you use the conditional(ternary) operator the compiler needs an implicit conversion between both types, otherwise you get an exception.
So you could fix it by casting one of both to System.Object
:
planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : (object) AgeItem.AgeIndex;
But since the result is not really pretty and you always have to remember this casting, you could use such an extension method instead:
public static object GetDBNullOrValue<T>(this T val)
{
bool isDbNull = true;
Type t = typeof(T);
if (Nullable.GetUnderlyingType(t) != null)
isDbNull = EqualityComparer<T>.Default.Equals(default(T), val);
else if (t.IsValueType)
isDbNull = false;
else
isDbNull = val == null;
return isDbNull ? DBNull.Value : (object) val;
}
Then you can use this concise code:
planIndexParameter.Value = AgeItem.AgeIndex.GetDBNullOrValue();
This is borderline programming, but look into using tr:
$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'
Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.
You would certainly benefit from using a responsive framework for your project. It would save you a good amount of headaches. However, seeing the structure of your HTML I would do the following:
Please check the example: http://jsfiddle.net/xLA4q/
HTML:
<div class="nav-content-wrapper">
<div class="left-nav">asdasdasd ads asd ads asd ad asdasd ad ad a ad</div>
<div class="content">asd as dad ads ads ads ad ads das ad sad</div>
</div>
CSS:
.nav-content-wrapper{position:relative; overflow:auto; display:block;height:300px;}
.left-nav{float:left;width:30%;height:inherit;}
.content{float:left;width:70%;height:inherit;}
In Html5, you can now use
<form>
<input type="number" min="1" max="100">
</form>
Close() - managed resource can be temporarily closed and can be opened once again.
Dispose() - permanently removes managed or not managed resource
The VirtualPathProviderViewEngine, on which the WebFormsViewEngine is based, is supposed to support the "~" and "/" characters at the front of the path so your examples above should work.
I noticed your examples use the path "~/Account/myPartial.ascx", but you mentioned that your user control is in the Views/Account folder. Have you tried
<%Html.RenderPartial("~/Views/Account/myPartial.ascx");%>
or is that just a typo in your question?
I've tried the other answers listed above, but they are very far from decent solutions when dealing with large files -- especially once a single line's size occupies more than ~1/4 of available RAM.
Both bash and awk slurp the entire line, even though for this problem it's not needed. Bash will error out once a line is too long, even if you have enough memory.
I've implemented an extremely simple, fairly unoptimized python script that when tested with large files (~4 GB per line) doesn't slurp, and is by far a better solution than those given.
If this is time critical code for production, you can rewrite the ideas in C or perform better optimizations on the read call (instead of only reading a single byte at a time), after testing that this is indeed a bottleneck.
Code assumes newline is a linefeed character, which is a good assumption for Unix, but YMMV on Mac OS/Windows. Be sure the file ends with a linefeed to ensure the last line character count isn't overlooked.
from sys import stdin, exit
counter = 0
while True:
byte = stdin.buffer.read(1)
counter += 1
if not byte:
exit()
if byte == b'\x0a':
print(counter-1)
counter = 0
I had a similar problem. I tried to restore a 2005 .bak file, and i received exactly the same error. I selected the overwrite option as well to no avail.
my solution was to grant the SQL user access to the directory in question, by going to the folder and editing the access rights through the property screen.
The solution I've come up with is:
isinstance(y, (np.ndarray, np.generic) )
However, it's not 100% clear that all numpy types are guaranteed to be either np.ndarray
or np.generic
, and this probably isn't version robust.
You can write the following:
Path.Combine(Path.GetParentDirectory(GetType(MyClass).Assembly.Location), "Images\image.jpg")
This is easy all you need to do is something like this Grab your contents like this
$result->get(filed1) = 'some modification';
$result->get(filed2) = 'some modification2';
You need a Flask view that will receive POST data and an HTML form that will send it.
from flask import request
@app.route('/addRegion', methods=['POST'])
def addRegion():
...
return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
Project file path: <input type="text" name="projectFilePath"><br>
<input type="submit" value="Submit">
</form>
If you just have a static svg string you want to include, you can use dangerouslySetInnerHTML
:
render: function() {
return <span dangerouslySetInnerHTML={{__html: "<svg>...</svg>"}} />;
}
and React will include the markup directly without processing it at all.
Let me share what I end up with, which allows to set correctly width or height by getting the image dimensions. In addition, the code allows to fetch a loading image while the large image data we need is being transfered:
Use static method Image.prefetch to have the image downloaded and available to cache.
Use static method Image.getSize to collect height and width and use it to compute an aspect ratio and then the final height (or width)
Display image with a default style to your prefered width (The height will be computed with aspect ratio kept)
function ImageX(props: {source: string, id: string})
{
const [imageHeight, setImageHeight] = React.useState(1);
Image.prefetch(props.source)
.then(() => {
Image.getSize(props.source, (width, height) => {
let aspectRatio = height/width;
setImageHeight(aspectRatio*Dimensions.get('window').width);
});
})
.catch(error => console.log(error))
if (imageHeight <=1) //Image not in cache (disk) yet
{
return (
<Image key={props.id} style={styleimg.image} source={{uri: 'http://www.dsdsd/loaderpreview.gif'}}/>
);
}
else
{
return (
<Image key={props.id} style={styleimg.image} height={imageHeight} source={{uri: props.source}}/>
);
}
}
const styleimg = StyleSheet.create({ image: { width: Dimensions.get('window').width, resizeMode: 'contain' //... // you can set a height defaults } });
Actually they are the same. LEFT OUTER JOIN
is same as LEFT JOIN
and RIGHT OUTER JOIN
is same as RIGHT JOIN
. It is more informative way to compare from INNER Join
.
See this Wikipedia article for details.
This is an additional way to find out the number of CPU cores (and a lot of other information), but this code requires an additional dependence:
Native Operating System and Hardware Information https://github.com/oshi/oshi
SystemInfo systemInfo = new SystemInfo();
HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
CentralProcessor centralProcessor = hardwareAbstractionLayer.getProcessor();
Get the number of logical CPUs available for processing:
centralProcessor.getLogicalProcessorCount();
This maybe because the textview is too high. Change android:layout_height of the textview to wrap_content or use
android:gravity="center_vertical"
There are three ways of defining things in Scala:
def
defines a methodval
defines a fixed value (which cannot be modified)var
defines a variable (which can be modified)Looking at your code:
def person = new Person("Kumar",12)
This defines a new method called person
. You can call this method only without ()
because it is defined as parameterless method. For empty-paren method, you can call it with or without '()'. If you simply write:
person
then you are calling this method (and if you don't assign the return value, it will just be discarded). In this line of code:
person.age = 20
what happens is that you first call the person
method, and on the return value (an instance of class Person
) you are changing the age
member variable.
And the last line:
println(person.age)
Here you are again calling the person
method, which returns a new instance of class Person
(with age
set to 12). It's the same as this:
println(person().age)
CSS
li {
display: inline-block;
}
Works for me also.
Easier way for me is to switch to R1C1
notation and just use R[-1]C1
and switch back when done.
You should try using isinstance()
if isinstance(object, list):
## DO what you want
In your case
if isinstance(tmpDict[key], list):
## DO SOMETHING
To elaborate:
x = [1,2,3]
if type(x) == list():
print "This wont work"
if type(x) == list: ## one of the way to see if it's list
print "this will work"
if type(x) == type(list()):
print "lets see if this works"
if isinstance(x, list): ## most preferred way to check if it's list
print "This should work just fine"
The difference between isinstance()
and type()
though both seems to do the same job is that isinstance()
checks for subclasses in addition, while type()
doesn’t.
I see that this question is solved, but, I want to add some information than can help someone.
if you want use hex to set background color, I found this function and work:
func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}
I use this function as follows:
view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)
some times you must use self
:
self.view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)
Well that was it, I hope it helps someone .
sorry for my bad english.
this work on iOS 7.1+
I experienced the same problem and following solution solved this problem. You should try the following solution.
sudo mkdir -p /data/db
sudo chown -R 'username' /data/db
This works for me every time:
if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){
//THEN CLICK ON THE SUBMIT BUTTON
}else{
//DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
}
For me ComboBox.DropDownClosed
Event did it.
private void cbValueType_DropDownClosed(object sender, EventArgs e)
{
if (cbValueType.SelectedIndex == someIntValue) //sel ind already updated
{
// change sel Index of other Combo for example
cbDataType.SelectedIndex = someotherIntValue;
}
}
Basically VOLUME
and -v
option are almost equal. These mean 'mount specific directory on your container'. For example, VOLUME /data
and -v /data
is exactly same meaning. If you run the image that have VOLUME /data
or with -v /data
option, /data
directory is mounted your container. This directory doesn't belong to your container.
Imagine that You add some files to /data
on the container, then commit the container into new image. There isn't any files on data directory because mounted /data
directory is belong to original container.
$ docker run -it -v /data --name volume ubuntu:14.04 bash
root@2b5e0f2d37cd:/# cd /data
root@2b5e0f2d37cd:/data# touch 1 2 3 4 5 6 7 8 9
root@2b5e0f2d37cd:/data# cd /tmp
root@2b5e0f2d37cd:/tmp# touch 1 2 3 4 5 6 7 8 9
root@2b5e0f2d37cd:/tmp# exit
exit
$ docker commit volume nacyot/volume
835cfe3d8d159622507ba3256bb1c0b0d6e7c1419ae32751ad0f925c40378945
nacyot $ docker run -it nacyot/volume
root@dbe335c7e64d:/# cd /data
root@dbe335c7e64d:/data# ls
root@dbe335c7e64d:/data# cd /tmp
root@dbe335c7e64d:/tmp# ls
1 2 3 4 5 6 7 8 9
root@dbe335c7e64d:/tmp#
root@dbe335c7e64d:/tmp#
This mounted directory like /data
is used to store data that is not belong to your application. And you can predefine the data directory that is not belong to the container by using VOLUME
.
A difference between Volume
and -v
option is that you can use -v
option dynamically on starting container. It mean you can mount some directory dynamically. And another difference is that you can mount your host directory on your container by using -v
Style the td
and th
instead
td, th {
border: 1px solid black;
}
And also to make it so there is no spacing between cells use:
table {
border-collapse: collapse;
}
(also note, you have border-style: none;
which should be border-style: solid;
)
See an example here: http://jsfiddle.net/KbjNr/
I made this work in this way:
<button class="btn" ng-click='toggleClass($event)'>button one</button>
<button class="btn" ng-click='toggleClass($event)'>button two</button>
in your controller:
$scope.toggleClass = function (event) {
$(event.target).toggleClass('active');
}
In SQL 2017 or higher, you can use this:
declare @hits int = 0
set @hits = (select value from STRING_SPLIT('F609,4DFA,8499',','));
select count(@hits)
The way you are performing the injection of the property will not work, because the injection is done after the constructor is called.
You need to do one of the following:
Better solution
@Component
public class MyBean {
private final String prop;
@Autowired
public MyBean(@Value("${some.prop}") String prop) {
this.prop = prop;
System.out.println("================== " + prop + "================== ");
}
}
Solution that will work but is less testable and slightly less readable
@Component
public class MyBean {
@Value("${some.prop}")
private String prop;
public MyBean() {
}
@PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Also note that is not Spring Boot specific but applies to any Spring application
I tried pretty much everything suggested in the answers above. Unfortunately, nothing worked. Then I signout out of my Github account on VS Code and signed in again. Added the remote origin with the following command.
git remote add origin https://github.com/pete/first_app.git
And it was working.
If you really want Jackson to return a date with another time zone than UTC (and I myself have several good arguments for that, especially when some clients just don't get the timezone part) then I usually do:
ObjectMapper mapper = new ObjectMapper();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
dateFormat.setTimeZone(TimeZone.getTimeZone("CET"));
mapper.getSerializationConfig().setDateFormat(dateFormat);
// ... etc
It has no adverse effects on those that understand the timezone-p
Reset form validation after adding new fields.
function resetFormValidator(formId) {
$(formId).removeData('validator');
$(formId).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(formId);
}
Why do you need to encrypt the database? The user could easily disassemble your program and figure out the key. If you're encrypting it for network transfer, then consider using PGP instead of squeezing an encryption layer into a database layer.
Xcode 10.1 • Swift 4.2
import UIKit
class ProgressHUD: UIVisualEffectView {
var title: String?
var theme: UIBlurEffect.Style = .light
let strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
let activityIndicator = UIActivityIndicatorView()
init(title: String, theme: UIBlurEffect.Style = .light) {
super.init(effect: UIBlurEffect(style: theme))
self.title = title
self.theme = theme
[activityIndicator, strLabel].forEach(contentView.addSubview(_:))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
if let superview = self.superview {
frame = CGRect(x: superview.frame.midX - strLabel.frame.width / 2,
y: superview.frame.midY - strLabel.frame.height / 2, width: 160, height: 46)
layer.cornerRadius = 15.0
layer.masksToBounds = true
activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
activityIndicator.startAnimating()
strLabel.text = title
strLabel.font = .systemFont(ofSize: 14, weight: UIFont.Weight.medium)
switch theme {
case .dark:
strLabel.textColor = .white
activityIndicator.style = .white
default:
strLabel.textColor = .gray
activityIndicator.style = .gray
}
}
}
func show() {
self.isHidden = false
}
func hide() {
self.isHidden = true
}
}
Use:
let progress = ProgressHUD(title: "Authorization", theme: .dark)
[progress].forEach(view.addSubview(_:))
Perhaps something like this for the first problem, you can simply access the columns by their names:
>>> df = pd.DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df[df['c']>.5][['b','e']]
b e
1 0.071146 0.132145
2 0.495152 0.420219
For the second problem:
>>> df[df['c']>.5][['b','e']].values
array([[ 0.07114556, 0.13214495],
[ 0.49515157, 0.42021946]])
You can do it in a less than a minute with Google Drive (and free, no hassles)
• Bulk Upload all your images on imgur.com
• Copy the Links of all the images together, appended with .jpg. Only imgur lets you do copy all the image links together, do that using the image tab top right.
• Use http://TextMechanic.co to prepend and append each line with this:
Prefix : =image("
AND
Suffix : ", 1)
So that it looks like this =image("URL", 1)
• Copy All
• Paste it in Google Spreadsheet
• Voila!
References :
http://www.labnol.org/internet/images-in-google-spreadsheet/18167/
https://support.google.com/drive/bin/answer.py?hl=en&answer=87037&from=1068225&rd=1
From application perspective, if one needs only to avoid duplicates then HashSet
is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet
has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.
Note: Recent npm
versions do this automatically when package-locks are enabled, so this is not necessary except for removing development packages with the --production
flag.
Run npm prune
to remove modules not listed in package.json
.
From npm help prune
:
This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.
Extraneous packages are packages that are not listed on the parent package's dependencies list.
If the
--production
flag is specified, this command will remove the packages specified in your devDependencies.
run this command on your terminal(here -v11 is for version 11(java11))-:
/usr/libexec/java_home -v11
you will get the path on your terminal something like this -:
/Library/Java/JavaVirtualMachines/jdk-11.0.9.jdk/Contents/Home
now you need to open your bash profile in any editor for eg VS Code
if you want to edit your bash_profile in vs code then run this command -:
code ~/.bash_profile
else run this command and then press i to insert the path. -:
open ~/.bash_profile
you will get your .bash_profile now you need to add the path so add this in .bash_profile (path which you get from 1st command)-:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-11.0.9.jdk/Contents/Home
if you were using code editor then now go to terminal and run this command to save the changes -:
source ~/.bash_profile
else press esc then :wq to exit from bash_profile then go to terminal and run the command given above. process completed. now you can check using this command -:
echo $JAVA_HOME
you will get/Library/Java/JavaVirtualMachines/jdk-11.0.9.jdk/Contents/Home
That's not how to add an item to a string. This:
newinv=inventory+str(add)
Means you're trying to concatenate a list and a string. To add an item to a list, use the list.append()
method.
inventory.append(add) #adds a new item to inventory
print(inventory) #prints the new inventory
Hope this helps!
Just use the str().lower()
method, unless high-performance is important - in which case write that sorting method as a C extension.
"How to write a Python Extension" seems like a decent intro..
More interestingly, This guide compares using the ctypes library vs writing an external C module (the ctype is quite-substantially slower than the C extension).
I much prefer the array
module to the struct
module for this kind of tasks (ones involving sequences of homogeneous values):
>>> import array
>>> array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring()
'\x11\x18y\x01\x0c\xde"L'
no len
call, no string manipulation needed, etc -- fast, simple, direct, why prefer any other approach?!
Best choice is using
AppDomain.CurrentDomain.BaseDirectory
because it's in the system namespace and there is no dependency to system.web
this way your code will be more portable
I've made an improved algorithm for this, which handles nicely nodes with different size. It prints top-down using lines.
package alg;
import java.util.ArrayList;
import java.util.List;
/**
* Binary tree printer
*
* @author MightyPork
*/
public class TreePrinter
{
/** Node that can be printed */
public interface PrintableNode
{
/** Get left child */
PrintableNode getLeft();
/** Get right child */
PrintableNode getRight();
/** Get text to be printed */
String getText();
}
/**
* Print a tree
*
* @param root
* tree root node
*/
public static void print(PrintableNode root)
{
List<List<String>> lines = new ArrayList<List<String>>();
List<PrintableNode> level = new ArrayList<PrintableNode>();
List<PrintableNode> next = new ArrayList<PrintableNode>();
level.add(root);
int nn = 1;
int widest = 0;
while (nn != 0) {
List<String> line = new ArrayList<String>();
nn = 0;
for (PrintableNode n : level) {
if (n == null) {
line.add(null);
next.add(null);
next.add(null);
} else {
String aa = n.getText();
line.add(aa);
if (aa.length() > widest) widest = aa.length();
next.add(n.getLeft());
next.add(n.getRight());
if (n.getLeft() != null) nn++;
if (n.getRight() != null) nn++;
}
}
if (widest % 2 == 1) widest++;
lines.add(line);
List<PrintableNode> tmp = level;
level = next;
next = tmp;
next.clear();
}
int perpiece = lines.get(lines.size() - 1).size() * (widest + 4);
for (int i = 0; i < lines.size(); i++) {
List<String> line = lines.get(i);
int hpw = (int) Math.floor(perpiece / 2f) - 1;
if (i > 0) {
for (int j = 0; j < line.size(); j++) {
// split node
char c = ' ';
if (j % 2 == 1) {
if (line.get(j - 1) != null) {
c = (line.get(j) != null) ? '-' : '+';
} else {
if (j < line.size() && line.get(j) != null) c = '+';
}
}
System.out.print(c);
// lines and spaces
if (line.get(j) == null) {
for (int k = 0; k < perpiece - 1; k++) {
System.out.print(" ");
}
} else {
for (int k = 0; k < hpw; k++) {
System.out.print(j % 2 == 0 ? " " : "-");
}
System.out.print(j % 2 == 0 ? "+" : "+");
for (int k = 0; k < hpw; k++) {
System.out.print(j % 2 == 0 ? "-" : " ");
}
}
}
System.out.println();
}
// print line of numbers
for (int j = 0; j < line.size(); j++) {
String f = line.get(j);
if (f == null) f = "";
int gap1 = (int) Math.ceil(perpiece / 2f - f.length() / 2f);
int gap2 = (int) Math.floor(perpiece / 2f - f.length() / 2f);
// a number
for (int k = 0; k < gap1; k++) {
System.out.print(" ");
}
System.out.print(f);
for (int k = 0; k < gap2; k++) {
System.out.print(" ");
}
}
System.out.println();
perpiece /= 2;
}
}
}
To use this for your Tree, let your Node
class implement PrintableNode
.
Example output:
2952:0
+-----------------------------------------------+
1249:-1 5866:0
+-----------------------+ +-----------------------+
491:-1 1572:0 4786:1 6190:0
+-----+ +-----+ +-----------+
339:0 5717:0 6061:0 6271:0
you can use ajax calls to call different methods without a postback
$.ajax({
type: "POST",
url: "@(Url.Action("Action", "Controller"))",
data: {id: 'id', id1: 'id1' },
contentType: "application/json; charset=utf-8",
cache: false,
async: true,
success: function (result) {
//do something
}
});
First off, you have to specify you wish to use Document Literal style:
$client = new SoapClient(NULL, array(
'location' => 'https://example.com/path/to/service',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL)
);
Then, you need to transform your data into a SoapVar; I've written a simple transform function:
function soapify(array $data)
{
foreach ($data as &$value) {
if (is_array($value)) {
$value = soapify($value);
}
}
return new SoapVar($data, SOAP_ENC_OBJECT);
}
Then, you apply this transform function onto your data:
$data = soapify(array(
'Acquirer' => array(
'Id' => 'MyId',
'UserId' => 'MyUserId',
'Password' => 'MyPassword',
),
));
Finally, you call the service passing the Data parameter:
$method = 'Echo';
$result = $client->$method(new SoapParam($data, 'Data'));
if ($elem.parents('.left').length) {
}
For whom can help, nowadays in 2018, youtube have options for this:
(Example in Catalan, sorry :)
Translation of the 3 arrows : "Share" - "Embed" - "Show suggested videos when the video is finished"
<hr>
is not from struts. It is just an HTML tag.
So, take a look here: http://www.microbion.co.uk/web/vertline.htm This link will give you a couple of tips.
In
int *ptr= l_matrix[0];
you can access like
*p
*(p+1)
*(p+2)
after all 2 dimensional arrays are also stored as 1-d.
After discussion posting updated answer:
Option Explicit
Sub test()
Dim wk As String, yr As String
Dim fname As String, fpath As String
Dim owb As Workbook
With Application
.DisplayAlerts = False
.ScreenUpdating = False
.EnableEvents = False
End With
wk = ComboBox1.Value
yr = ComboBox2.Value
fname = yr & "W" & wk
fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"
On Error GoTo ErrorHandler
Set owb = Application.Workbooks.Open(fpath & "\" & fname)
'Do Some Stuff
With owb
.SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
.Close
End With
With Application
.DisplayAlerts = True
.ScreenUpdating = True
.EnableEvents = True
End With
Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then
Else: Call Clear
End Sub
Error Handling:
You could try something like this to catch a specific error:
On Error Resume Next
Set owb = Application.Workbooks.Open(fpath & "\" & fname)
If Err.Number = 1004 Then
GoTo FileNotFound
Else
End If
...
Exit Sub
FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then
Else: Call Clear
you can use ![ ](any link of image)
Also I would suggest to use https://stackedit.io/ for markdown formating and wring it is much easy than remembering all the markdown syntax
I faced the same problem, and resolved it by changing the BodyStyle attribut value to "WebMessageBodyStyle.Bare" :
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProjectWithGeocodings/{projectId}")]
GeoCod_Project GetProjectWithGeocodings(string projectId);
The returned object will no longer be wrapped.
use \r\n
combination to append a new line in node js
var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
stream.once('open', function(fd) {
stream.write(msg+"\r\n");
});
class department:
campus_name="attock"
def printer(self):
print(self.campus_name)
class CS_dept(department):
def overr_CS(self):
department.printer(self)
print("i am child class1")
c=CS_dept()
c.overr_CS()
I have tried the code that Marcos posted and it didn't worked for me. Whatever i was given to the Y coordinate the cursor didn't moved on Y axis. The code below will work if you want the position of the cursor relative to the left-up corner of your desktop, not relative to your application.
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_MOVE = 0x0001;
public void DoMouseClick()
{
X = Cursor.Position.X;
Y = Cursor.Position.Y;
//move to coordinates
pt = (Point)pc.ConvertFromString(X + "," + Y);
Cursor.Position = pt;
//perform click
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
I only use mouse_event function to actually perform the click. You can give X and Y what coordinates you want, i used values from textbox:
X = Convert.ToInt32(tbX.Text);
Y = Convert.ToInt32(tbY.Text);
For apscheduler
< 3.0, see Unknown's answer.
For apscheduler
> 3.0
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
@sched.scheduled_job('interval', seconds=10)
def timed_job():
print('This job is run every 10 seconds.')
@sched.scheduled_job('cron', day_of_week='mon-fri', hour=10)
def scheduled_job():
print('This job is run every weekday at 10am.')
sched.configure(options_from_ini_file)
sched.start()
apscheduler
documentation.
This for apscheduler-3.3.1
on Python 3.6.2
.
"""
Following configurations are set for the scheduler:
- a MongoDBJobStore named “mongo”
- an SQLAlchemyJobStore named “default” (using SQLite)
- a ThreadPoolExecutor named “default”, with a worker count of 20
- a ProcessPoolExecutor named “processpool”, with a worker count of 5
- UTC as the scheduler’s timezone
- coalescing turned off for new jobs by default
- a default maximum instance limit of 3 for new jobs
"""
from pytz import utc
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ProcessPoolExecutor
"""
Method 1:
"""
jobstores = {
'mongo': {'type': 'mongodb'},
'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
executors = {
'default': {'type': 'threadpool', 'max_workers': 20},
'processpool': ProcessPoolExecutor(max_workers=5)
}
job_defaults = {
'coalesce': False,
'max_instances': 3
}
"""
Method 2 (ini format):
"""
gconfig = {
'apscheduler.jobstores.mongo': {
'type': 'mongodb'
},
'apscheduler.jobstores.default': {
'type': 'sqlalchemy',
'url': 'sqlite:///jobs.sqlite'
},
'apscheduler.executors.default': {
'class': 'apscheduler.executors.pool:ThreadPoolExecutor',
'max_workers': '20'
},
'apscheduler.executors.processpool': {
'type': 'processpool',
'max_workers': '5'
},
'apscheduler.job_defaults.coalesce': 'false',
'apscheduler.job_defaults.max_instances': '3',
'apscheduler.timezone': 'UTC',
}
sched_method1 = BlockingScheduler() # uses overrides from Method1
sched_method2 = BlockingScheduler() # uses same overrides from Method2 but in an ini format
@sched_method1.scheduled_job('interval', seconds=10)
def timed_job():
print('This job is run every 10 seconds.')
@sched_method2.scheduled_job('cron', day_of_week='mon-fri', hour=10)
def scheduled_job():
print('This job is run every weekday at 10am.')
sched_method1.configure(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)
sched_method1.start()
sched_method2.configure(gconfig=gconfig)
sched_method2.start()
As of version 3.0.0, you can get the current route by calling:
this.context.router.location.pathname
Sample code is below:
var NavLink = React.createClass({
contextTypes: {
router: React.PropTypes.object
},
render() {
return (
<Link {...this.props}></Link>
);
}
});
You have a class on your CSS that is overwriting your width and height, the class reads as such:
.postItem img {
height: auto;
width: 450px;
}
Remove that and your width/height properties on the img
tag should work.
The @ symbol denotes an annotation type definition.
That means it is not really an interface, but rather a new annotation type -- to be used as a function modifier, such as @override.
See this javadocs entry on the subject.
Using subprocess.run
import subprocess
ps = subprocess.run(['ps', '-A'], check=True, capture_output=True)
processNames = subprocess.run(['grep', 'process_name'],
input=ps.stdout, capture_output=True)
print(processNames.stdout)
Tip: To create singleton class In Android Studio, right click in your project and open menu:
New -> Java Class -> Choose Singleton from dropdown menu
First of all, with the solution below, is necessary to understand that always the spring boot will read the application.properties
file. So the other's profile files only will complement and replace the properties defined before.
Considering the follow files:
application.properties
application-qa.properties
application-prod.properties
1) Very important. The application.properties
, and just this file, must have the follow line:
[email protected]@
2) Change what you want in the QA and PROD configuration files to see the difference between the environments.
3) By command line, start the spring boot app with any of this options:
It will start the app with the default application.properties
file:
mvn spring-boot:run
It will load the default application.properties
file and after the application-qa.properties
file, replacing and/or complementing the default configuration:
mvn spring-boot:run -Dspring.profiles.active=qa
The same here but with the production environment instead of QA:
mvn spring-boot:run -Dspring.profiles.active=prod
For completeness, if you wanted to use replaceFirst, try this:
public static String cap1stChar(String userIdea)
{
String betterIdea = userIdea;
if (userIdea.length() > 0)
{
String first = userIdea.substring(0,1);
betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
}
return betterIdea;
}//end cap1stChar
This is the most common technique I've seen:
function getUserIP() {
if( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')>0) {
$addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']);
return trim($addr[0]);
} else {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
}
else {
return $_SERVER['REMOTE_ADDR'];
}
}
Note that it does not guarantee it you will get always the correct user IP because there are many ways to hide it.
Based on Arthur Halma's answer, I did the following that works correctly with Apple's, Android & iOS mail.
define("EMAIL_DOMAIN", "yourdomain.com");
public function send_email_html($to, $from, $subject, $html) {
preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
$i = 0;
$paths = array();
foreach ($matches[1] as $img) {
$img_old = $img;
if(strpos($img, "http://") == false) {
$uri = parse_url($img);
$paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
$content_id = md5($img);
$html = str_replace($img_old,'cid:'.$content_id,$html);
$paths[$i++]['cid'] = $content_id;
}
}
$uniqid = md5(uniqid(time()));
$boundary = "--==_mimepart_".$uniqid;
$headers = "From: ".$from."\n".
'Reply-to: '.$from."\n".
'Return-Path: '.$from."\n".
'Message-ID: <'.$uniqid.'@'.EMAIL_DOMAIN.">\n".
'Date: '.gmdate('D, d M Y H:i:s', time())."\n".
'Mime-Version: 1.0'."\n".
'Content-Type: multipart/related;'."\n".
' boundary='.$boundary.";\n".
' charset=UTF-8'."\n".
'X-Mailer: PHP/' . phpversion();
$multipart = '';
$multipart .= "--$boundary\n";
$kod = 'UTF-8';
$multipart .= "Content-Type: text/html; charset=$kod\n";
$multipart .= "Content-Transfer-Encoding: 7-bit\n\n";
$multipart .= "$html\n\n";
foreach ($paths as $path) {
if (file_exists($path['path']))
$fp = fopen($path['path'],"r");
if (!$fp) {
return false;
}
$imagetype = substr(strrchr($path['path'], '.' ),1);
$file = fread($fp, filesize($path['path']));
fclose($fp);
$message_part = "";
switch ($imagetype) {
case 'png':
case 'PNG':
$message_part .= "Content-Type: image/png";
break;
case 'jpg':
case 'jpeg':
case 'JPG':
case 'JPEG':
$message_part .= "Content-Type: image/jpeg";
break;
case 'gif':
case 'GIF':
$message_part .= "Content-Type: image/gif";
break;
}
$message_part .= "; file_name = \"$path\"\n";
$message_part .= 'Content-ID: <'.$path['cid'].">\n";
$message_part .= "Content-Transfer-Encoding: base64\n";
$message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
$message_part .= chunk_split(base64_encode($file))."\n";
$multipart .= "--$boundary\n".$message_part."\n";
}
$multipart .= "--$boundary--\n";
mail($to, $subject, $multipart, $headers);
}
Hello sought a solution to make an Ajax form work with Google Tag Manager (GTM), the return false prevented the completion and submit the activation of the event in real time on google analytics solution was to change the return false by e.preventDefault (); that worked correctly follows the code:
$("#Contact-Form").submit(function(e) {
e.preventDefault();
...
});
I was playing around with C# code an I accidentally found the solution to your problem haha
This is the code for the Principal view:
`@model dynamic
@Html.Partial("_Partial", Model as IDictionary<string, object>)`
Then in the Partial view:
`@model dynamic
@if (Model != null) {
foreach (var item in Model)
{
<div>@item.text</div>
}
}`
It worked for me, I hope this will help you too!!
I'm going to heavily quote the Object documentation here, because I think it has some great explanations. I encourage you to read it, and also the documentation for these methods as they're overridden in other classes, like String.
Side note: if you want to try these out for yourself on different objects, use something like this:
class Object
def all_equals(o)
ops = [:==, :===, :eql?, :equal?]
Hash[ops.map(&:to_s).zip(ops.map {|s| send(s, o) })]
end
end
"a".all_equals "a" # => {"=="=>true, "==="=>true, "eql?"=>true, "equal?"=>false}
==
— generic "equality"At the Object level,
==
returns true only ifobj
andother
are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.
This is the most common comparison, and thus the most fundamental place where you (as the author of a class) get to decide if two objects are "equal" or not.
===
— case equalityFor class Object, effectively the same as calling
#==
, but typically overridden by descendants to provide meaningful semantics in case statements.
This is incredibly useful. Examples of things which have interesting ===
implementations:
So you can do things like:
case some_object
when /a regex/
# The regex matches
when 2..4
# some_object is in the range 2..4
when lambda {|x| some_crazy_custom_predicate }
# the lambda returned true
end
See my answer here for a neat example of how case
+Regex
can make code a lot cleaner. And of course, by providing your own ===
implementation, you can get custom case
semantics.
eql?
— Hash
equalityThe
eql?
method returns true ifobj
andother
refer to the same hash key. This is used byHash
to test members for equality. For objects of classObject
,eql?
is synonymous with==
. Subclasses normally continue this tradition by aliasingeql?
to their overridden==
method, but there are exceptions.Numeric
types, for example, perform type conversion across==
, but not acrosseql?
, so:1 == 1.0 #=> true 1.eql? 1.0 #=> false
So you're free to override this for your own uses, or you can override ==
and use alias :eql? :==
so the two methods behave the same way.
equal?
— identity comparisonUnlike
==
, theequal?
method should never be overridden by subclasses: it is used to determine object identity (that is,a.equal?(b)
iffa
is the same object asb
).
This is effectively pointer comparison.
How to fix Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150) in mysql.
alter your table and add an index to it..
ALTER TABLE users ADD INDEX index_name (index_column)
Now add the constraint
ALTER TABLE foreign_key_table
ADD CONSTRAINT foreign_key_name FOREIGN KEY (foreign_key_column)
REFERENCES primary_key_table (primary_key_column) ON DELETE NO ACTION
ON UPDATE CASCADE;
Note if you don't add an index it wont work.
After battling with it for about 6 hours I came up with the solution I hope this save a soul.
If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.
You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar
):
openssl genrsa -aes128 -passout pass:foobar 3072
However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.
A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:
openssl genrsa -aes128 -passout file:passphrase.txt 3072
Or supply the passphrase on standard input:
openssl genrsa -aes128 -passout stdin 3072
You can also used a named pipe with the file:
option, or a file descriptor.
To then obtain the matching public key, you need to use openssl rsa
, supplying the same passphrase with the -passin
parameter as was used to encrypt the private key:
openssl rsa -passin file:passphrase.txt -pubout
(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>
).
Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar
:
openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub
Make sure you're using right method: Post/Get, right content type and right parameters (data).
$.ajax({
type: "POST",
url: "/ajax.asmx/GetNews",
data: "{Lang:'tr'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) { generateNews(msg); }
})
Everything that interacts with the UI must be called in the UI thread (unless it is a frozen object). To do that, you can use the dispatcher.
var disp = /* Get the UI dispatcher, each WPF object has a dispatcher which you can query*/
disp.BeginInvoke(DispatcherPriority.Normal,
(Action)(() => /*Do your UI Stuff here*/));
I use BeginInvoke here, usually a backgroundworker doesn't need to wait that the UI updates. If you want to wait, you can use Invoke
. But you should be careful not to call BeginInvoke to fast to often, this can get really nasty.
By the way, The BackgroundWorker class helps with this kind of taks. It allows Reporting changes, like a percentage and dispatches this automatically from the Background thread into the ui thread. For the most thread <> update ui tasks the BackgroundWorker is a great tool.
You can run flutter clean
.
But that's most likely a problem with your IDE or similar, as flutter run creates a brand new apk. And hot reload push only modifications.
Try running your app using the command line flutter run
and then press r
or R
for respectively hot-reload and full-reload.
You just need to run:
$ set +o history
To see more, run:
$ man set
You can refer in this line - Difference between ASP.NET Core (.NET Core) and ASP.NET Core (.NET Framework)
Xamarin is not a debate at all. When you want to build mobile (iOS, Android, and Windows Mobile) apps using C#, Xamarin is your only choice.
The .NET Framework supports Windows and Web applications. Today, you can use Windows Forms, WPF, and UWP to build Windows applications in .NET Framework. ASP.NET MVC is used to build Web applications in .NET Framework.
.NET Core is the new open-source and cross-platform framework to build applications for all operating system including Windows, Mac, and Linux. .NET Core supports UWP and ASP.NET Core only. UWP is used to build Windows 10 targets Windows and mobile applications. ASP.NET Core is used to build browser based web applications.
you want more details refer this links
https://blogs.msdn.microsoft.com/dotnet/2016/07/15/net-core-roadmap/
https://docs.microsoft.com/en-us/dotnet/articles/standard/choosing-core-framework-server
If you do not want to include the brackets in the match, here's the regex: (?<=\[).*?(?=\])
The .
matches any character except for line terminators. The ?=
is a positive lookahead. A positive lookahead finds a string when a certain string comes after it. The ?<=
is a positive lookbehind. A positive lookbehind finds a string when a certain string precedes it. To quote this,
Look ahead positive (?=)
Find expression A where expression B follows:
A(?=B)
Look behind positive (?<=)
Find expression A where expression B precedes:
(?<=B)A
If your regex engine does not support lookaheads and lookbehinds, then you can use the regex \[(.*?)\]
to capture the innards of the brackets in a group and then you can manipulate the group as necessary.
The parentheses capture the characters in a group. The .*?
gets all of the characters between the brackets (except for line terminators, unless you have the s
flag enabled) in a way that is not greedy.
For Rails 4 you can put the following in an environment file:
# /config/environments/development.rb
config.active_record.logger = nil
The problem with the solution suggested is that it can break some performance features built into the SessionState if you are using an out-of-process session storage. (either "State Server Mode" or "SQL Server Mode"). In oop modes the session data needs to be serialized at the end of the page request and deserialized at the beginning of the page request, which can be costly. To improve the performance the SessionState attempts to only deserialize what is needed by only deserialize variable when it is accessed the first time, and it only re-serializes and replaces variable which were changed. If you have alot of session variable and shove them all into one class essentially everything in your session will be deserialized on every page request that uses session and everything will need to be serialized again even if only 1 property changed becuase the class changed. Just something to consider if your using alot of session and an oop mode.
In C++ the stack memory is where local variables get stored/constructed. The stack is also used to hold parameters passed to functions.
The stack is very much like the std::stack class: you push parameters onto it and then call a function. The function then knows that the parameters it expects can be found on the end of the stack. Likewise, the function can push locals onto the stack and pop them off it before returning from the function. (caveat - compiler optimizations and calling conventions all mean things aren't this simple)
The stack is really best understood from a low level and I'd recommend Art of Assembly - Passing Parameters on the Stack. Rarely, if ever, would you consider any sort of manual stack manipulation from C++.
Generally speaking, the stack is preferred as it is usually in the CPU cache, so operations involving objects stored on it tend to be faster. However the stack is a limited resource, and shouldn't be used for anything large. Running out of stack memory is called a Stack buffer overflow. It's a serious thing to encounter, but you really shouldn't come across one unless you have a crazy recursive function or something similar.
Heap memory is much as rskar says. In general, C++ objects allocated with new, or blocks of memory allocated with the likes of malloc end up on the heap. Heap memory almost always must be manually freed, though you should really use a smart pointer class or similar to avoid needing to remember to do so. Running out of heap memory can (will?) result in a std::bad_alloc.
It appears that the :include
functionality was changed with Rails 2.1. Rails used to do the join in all cases, but for performance reasons it was changed to use multiple queries in some circumstances. This blog post by Fabio Akita has some good information on the change (see the section entitled "Optimized Eager Loading").
// Remove active for all items.
$('.sidebar-menu li').removeClass('active');
// highlight submenu item
$('li a[href="' + this.location.pathname + '"]').parent().addClass('active');
// Highlight parent menu item.
$('ul a[href="' + this.location.pathname + '"]').parents('li').addClass('active')
Here is a snippet code through a chain of environments properties files are being loaded for different environments.
Properties file under your application resources ( src/main/resources ):-
1. application.properties
2. application-dev.properties
3. application-uat.properties
4. application-prod.properties
Ideally, application.properties contains all common properties which are accessible for all environments and environment related properties only works on specifies environment. therefore the order of loading these properties files will be in such way -
application.properties -> application.{spring.profiles.active}.properties.
Code snippet here :-
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class PropertiesUtils {
public static final String SPRING_PROFILES_ACTIVE = "spring.profiles.active";
public static void initProperties() {
String activeProfile = System.getProperty(SPRING_PROFILES_ACTIVE);
if (activeProfile == null) {
activeProfile = "dev";
}
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer
= new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[]
{new ClassPathResource("application.properties"),
new ClassPathResource("application-" + activeProfile + ".properties")};
propertySourcesPlaceholderConfigurer.setLocations(resources);
}
}
You should create the media
dir appended to what getLocalPath()
returns.
For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:
perl Makefile.PL INSTALL_BASE=/mydir/perl
Your group statement will group by group ID. For example, if you then write:
foreach (var group in groupedCustomerList)
{
Console.WriteLine("Group {0}", group.Key);
foreach (var user in group)
{
Console.WriteLine(" {0}", user.UserName);
}
}
that should work fine. Each group has a key, but also contains an IGrouping<TKey, TElement>
which is a collection that allows you to iterate over the members of the group. As Lee mentions, you can convert each group to a list if you really want to, but if you're just going to iterate over them as per the code above, there's no real benefit in doing so.
Use the System.getenv(String)
method, passing the name of the variable to read.
A fairly low-tech solution to this problem seems to be to declare the service (I'm using swarm on AWS and a yaml file) with your database files mounted to a persisted volume (here AWS EFS as denoted by the cloudstor:aws driver specification).
version: '3.3'
services:
database:
image: postgres:latest
volumes:
- postgresql:/var/lib/postgresql
- postgresql_data:/var/lib/postgresql/data
volumes:
postgresql:
driver: "cloudstor:aws"
postgresql_data:
driver: "cloudstor:aws"
A pleasant side-effect of persisting your configuration is that it also persists your databases (or was it the other way around) ;-)
[examine all threads backtraces to find the culprit]
Even fully expanded call stack can still hide the actual offending line of code from you when you use more than one thread!
Example: One thread is iterating ruby Hash, other thread is trying to modify it. BOOM! Exception! And the problem with the stack trace you get while trying to modify 'busy' hash is that it shows you chain of functions down to the place where you're trying to modify hash, but it does NOT show who's currently iterating it in parallel (who owns it)! Here's the way to figure that out by printing stack trace for ALL currently running threads. Here's how you do this:
# This solution was found in comment by @thedarkone on https://github.com/rails/rails/issues/24627
rescue Object => boom
thread_count = 0
Thread.list.each do |t|
thread_count += 1
err_msg += "--- thread #{thread_count} of total #{Thread.list.size} #{t.object_id} backtrace begin \n"
# Lets see if we are able to pin down the culprit
# by collecting backtrace for all existing threads:
err_msg += t.backtrace.join("\n")
err_msg += "\n---thread #{thread_count} of total #{Thread.list.size} #{t.object_id} backtrace end \n"
end
# and just print it somewhere you like:
$stderr.puts(err_msg)
raise # always reraise
end
The above code snippet is useful even just for educational purposes as it can show you (like x-ray) how many threads you actually have (versus how many you thought you have - quite often those two are different numbers ;)
Why dont you use?:
string[] ssizes = myStr.Split(' ', '\t');
Back references can find interesting solutions here. This regex:
([a-z]+).*(\1)
will find the longest repeated sequence.
This one will find a sequence of 3 letters that is repeated:
([a-z]{3}).*(\1)
The best way to do this would be to use the promise returning function as it is, like this
lookupValue(file).then(function(res) {
// Write the code which depends on the `res.val`, here
});
The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.
So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.
Using a table would be one (and easy) option.
Other options are all about setting fixed width on the and making it text-aligned to the right:
label {
width: 200px;
display: inline-block;
text-align: right;
}
or, as was pointed out, make them all float instead of inline.
Rollback... will prompt you to select a folder to rollback, ie, it will work on specific folders, and you can rollback to labels or changlists or dates. Back out works on the files in specific changelists.
If your terminal supports it, you can use ANSI escape codes to use color in your output. It generally works for Unix shell prompts; however, it doesn't work for Windows Command Prompt (Although, it does work for Cygwin). For example, you could define constants like these for the colors:
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
Then, you could reference those as necessary.
For example, using the above constants, you could make the following red text output on supported terminals:
System.out.println(ANSI_RED + "This text is red!" + ANSI_RESET);
Update: You might want to check out the Jansi library. It provides an API and has support for Windows using JNI. I haven't tried it yet; however, it looks promising.
Update 2: Also, if you wish to change the background color of the text to a different color, you could try the following as well:
public static final String ANSI_BLACK_BACKGROUND = "\u001B[40m";
public static final String ANSI_RED_BACKGROUND = "\u001B[41m";
public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m";
public static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m";
public static final String ANSI_BLUE_BACKGROUND = "\u001B[44m";
public static final String ANSI_PURPLE_BACKGROUND = "\u001B[45m";
public static final String ANSI_CYAN_BACKGROUND = "\u001B[46m";
public static final String ANSI_WHITE_BACKGROUND = "\u001B[47m";
For instance:
System.out.println(ANSI_GREEN_BACKGROUND + "This text has a green background but default text!" + ANSI_RESET);
System.out.println(ANSI_RED + "This text has red text but a default background!" + ANSI_RESET);
System.out.println(ANSI_GREEN_BACKGROUND + ANSI_RED + "This text has a green background and red text!" + ANSI_RESET);
Since you're using Spring Boot, I assume you'd prefer to rely on Spring's auto configuration where possible. To add additional custom configuration like your interceptors, just provide a configuration or bean of WebMvcConfigurerAdapter
.
Here's an example of a config class:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
HandlerInterceptor yourInjectedInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(...)
...
registry.addInterceptor(getYourInterceptor());
registry.addInterceptor(yourInjectedInterceptor);
// next two should be avoid -- tightly coupled and not very testable
registry.addInterceptor(new YourInterceptor());
registry.addInterceptor(new HandlerInterceptor() {
...
});
}
}
NOTE do not annotate this with @EnableWebMvc, if you want to keep Spring Boots auto configuration for mvc.
Sure there's an entity for tabs:
	
(The tab is ASCII character 9, or Unicode U+0009.)
However, just like literal tabs (ones you type in to your text editor), all tab characters are treated as whitespace by HTML parsers and collapsed into a single space except those within a <pre>
block, where literal tabs will be rendered as 8 spaces in a monospace font.
You can do this be using a new Subject
too:
Typescript:
let subject = new Subject();
get_categories(...) {
this.http.post(...).subscribe(
(response) => {
this.total = response.json();
subject.next();
}
);
return subject; // can be subscribed as well
}
get_categories(...).subscribe(
(response) => {
// ...
}
);
In this case the variable titled var
in the method Change
is assigned a reference to self.variable
, and you immediately assign a string to var
. It's no longer pointing to self.variable
. The following code snippet shows what would happen if you modify the data structure pointed to by var
and self.variable
, in this case a list:
>>> class PassByReference:
... def __init__(self):
... self.variable = ['Original']
... self.change(self.variable)
... print self.variable
...
... def change(self, var):
... var.append('Changed')
...
>>> q = PassByReference()
['Original', 'Changed']
>>>
I'm sure someone else could clarify this further.
In order for that to work $time
has to be a timestamp. You cannot pass in "10:00" or something like $time = date('H:i', '10:00');
which is what you seem to do, because then I get 0:30 and 1:30 as results too.
Try
$time = strtotime('10:00');
As an alternative, consider using DateTime (the below requires PHP 5.3 though):
$dt = DateTime::createFromFormat('H:i', '10:00'); // create today 10 o'clock
$dt->sub(new DateInterval('PT30M')); // substract 30 minutes
echo $dt->format('H:i'); // echo modified time
$dt->add(new DateInterval('PT1H')); // add 1 hour
echo $dt->format('H:i'); // echo modified time
or procedural if you don't like OOP
$dateTime = date_create_from_format('H:i', '10:00');
date_sub($dateTime, date_interval_create_from_date_string('30 minutes'));
echo date_format($dateTime, 'H:i');
date_add($dateTime, date_interval_create_from_date_string('1 hour'));
echo date_format($dateTime, 'H:i');
Loop like
foreach (GridViewRow row in grid.Rows)
{
if (((CheckBox)row.FindControl("chkboxid")).Checked)
{
//read the label
}
}
Yes, you can modify local variables from inside lambdas (in the way shown by the other answers), but you should not do it. Lambdas have been made for functional style of programming and this means: No side effects. What you want to do is considered bad style. It is also dangerous in case of parallel streams.
You should either find a solution without side effects or use a traditional for loop.
What you are looking for is probably this:
ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"
int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);
Let me know if this was helpful :)
Late to the party, but what about
things.stream()
.map(this::resolve)
.filter(Optional::isPresent)
.findFirst().get();
You can get rid of the last get() if you create a util method to convert optional to stream manually:
things.stream()
.map(this::resolve)
.flatMap(Util::optionalToStream)
.findFirst();
If you return stream right away from your resolve function, you save one more line.
In a terminal, run:
export PATH=/usr/local/bin:$PATH
brew link --force openssl
You may have to unlink openssl first if you get a warning: brew unlink openssl
This ensures we're linking the correct openssl for this situation. (and doesn't mess with .profile)
Hat tip to @Olaf's answer and @Felipe's comment. Some people - such as myself - may have some pretty messed up PATH vars.
Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.
I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.
EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/