The problem is that you have not included bootstrap.min.css
. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
You might want to add:
-webkit-appearance: none;
if you need it looking consistent on Mobile Safari...
This thread might be dead, but StyledMarker is available for API v3. Just bind the color change you want to the correct DOM event using the addDomListener() method. This example is pretty close to what you want to do. If you look at the page source, change:
google.maps.event.addDomListener(document.getElementById("changeButton"),"click",function() {
styleIcon.set("color","#00ff00");
styleIcon.set("text","Go");
});
to something like:
google.maps.event.addDomListener("mouseover",function() {
styleIcon.set("color","#00ff00");
styleIcon.set("text","Go");
});
That should be enough to get you moving along.
The Wikipedia page on DOM Events will also help you target the event that you want to capture on the client-side.
Good luck (if you still need it)
Assume your file looks like this and is named test.txt (space delimited):
1 2
3 4
5 6
7 8
Then:
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
with open("test.txt") as f:
data = f.read()
data = data.split('\n')
x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_title("Plot title...")
ax1.set_xlabel('your x label..')
ax1.set_ylabel('your y label...')
ax1.plot(x,y, c='r', label='the data')
leg = ax1.legend()
plt.show()
I find that browsing the gallery of plots on the matplotlib site helpful for figuring out legends and axes labels.
If you use EcmaScript version >= 5.1, you can implement a functional version of chunk()
using array.reduce() that has O(N) complexity:
function chunk(chunkSize, array) {_x000D_
return array.reduce(function(previous, current) {_x000D_
var chunk;_x000D_
if (previous.length === 0 || _x000D_
previous[previous.length -1].length === chunkSize) {_x000D_
chunk = []; // 1_x000D_
previous.push(chunk); // 2_x000D_
}_x000D_
else {_x000D_
chunk = previous[previous.length -1]; // 3_x000D_
}_x000D_
chunk.push(current); // 4_x000D_
return previous; // 5_x000D_
}, []); // 6_x000D_
}_x000D_
_x000D_
console.log(chunk(2, ['a', 'b', 'c', 'd', 'e']));_x000D_
// prints [ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e' ] ]
_x000D_
Explanation of each // nbr
above:
chunkSize
itemsCurrying based on chunkSize
:
var chunk3 = function(array) {
return chunk(3, array);
};
console.log(chunk3(['a', 'b', 'c', 'd', 'e']));
// prints [ [ 'a', 'b', 'c' ], [ 'd', 'e' ] ]
You can add the chunk()
function to the global Array
object:
Object.defineProperty(Array.prototype, 'chunk', {_x000D_
value: function(chunkSize) {_x000D_
return this.reduce(function(previous, current) {_x000D_
var chunk;_x000D_
if (previous.length === 0 || _x000D_
previous[previous.length -1].length === chunkSize) {_x000D_
chunk = [];_x000D_
previous.push(chunk);_x000D_
}_x000D_
else {_x000D_
chunk = previous[previous.length -1];_x000D_
}_x000D_
chunk.push(current);_x000D_
return previous;_x000D_
}, []);_x000D_
}_x000D_
});_x000D_
_x000D_
console.log(['a', 'b', 'c', 'd', 'e'].chunk(4));_x000D_
// prints [ [ 'a', 'b', 'c' 'd' ], [ 'e' ] ]
_x000D_
$ seq 4
1
2
3
4
$ seq 2 5
2
3
4
5
$ seq 4 2 12
4
6
8
10
12
$ seq -w 4 2 12
04
06
08
10
12
$ seq -s, 4 2 12
4,6,8,10,12
This error message just helped me a bunch, as I hadn't realized that I'd accidentally written my function using my testing example player
my_player.attributes[item]
instead of the correct way
self.attributes[item]
If you want or don't mind having all the leading and trailing whitespace from your string removed you can use the strip
method.
" hello ".strip #=> "hello"
"\tgoodbye\r\n".strip #=> "goodbye"
as mentioned here.
edit The original title for this question was different. My answer is for the original question.
A better(error-free) code would be like:
function isReallyNumber(data) {
return typeof data === 'number' && !isNaN(data);
}
This will handle empty strings as well. Another reason, isNaN("12")
equals to false
but "12"
is a string and not a number, so it should result to true
. Lastly, a bonus link which might interest you.
Command separators:
cls & dir
copy a b && echo Success
copy a b || echo Failure
At the 2nd line, the command after && only runs if the first command is successful.
At the 3rd line, the command after || only runs if the first command failed.
In my case I kept getting a 403.14 after I had setup the correct rewrite rules. It turns out that I had a directory that was the same name as one of my URL routes. Once I removed the IsDirectory rewrite rule my routes worked correctly. Is there a case where removing the directory negation may cause problems? I can't think of any in my case. The only case I can think of is if you can browse a directory with your app.
<rule name="fixhtml5mode" stopProcessing="true">
<match url=".*"/>
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
As an extra, you can take the Enum.Parse
answers already provided and put them in an easy-to-use static method in a helper class.
public static T ParseEnum<T>(string value)
{
return (T)Enum.Parse(typeof(T), value, ignoreCase: true);
}
And use it like so:
{
Content = ParseEnum<ContentEnum>(fileContentMessage);
};
Especially helpful if you have lots of (different) Enums to parse.
The GUI can be fickle at times. The error you got when using T-SQL is because you're trying to overwrite an existing database, but did not specify to overwrite/replace the existing database. The following might work:
Use Master
Go
RESTORE DATABASE Publications
FROM DISK = 'C:\Publications_backup_2012_10_15_010004_5648316.bak'
WITH
MOVE 'Publications' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS2008R2\MSSQL\DATA\Publications.mdf',--adjust path
MOVE 'Publications_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS2008R2\MSSQL\DATA\Publications.ldf'
, REPLACE -- Add REPLACE to specify the existing database which should be overwritten.
Use paste
.
df$x <- paste(df$n,df$s)
df
# n s b x
# 1 2 aa TRUE 2 aa
# 2 3 bb FALSE 3 bb
# 3 5 cc TRUE 5 cc
my two pence, using map in place of for-loop
var path = require('path'), fs = require('fs');
var findFiles = function(folder, pattern = /.*/, callback) {
var flist = [];
fs.readdirSync(folder).map(function(e){
var fname = path.join(folder, e);
var fstat = fs.lstatSync(fname);
if (fstat.isDirectory()) {
// don't want to produce a new array with concat
Array.prototype.push.apply(flist, findFiles(fname, pattern, callback));
} else {
if (pattern.test(fname)) {
flist.push(fname);
if (callback) {
callback(fname);
}
}
}
});
return flist;
};
// HTML files
var html_files = findFiles(myPath, /\.html$/, function(o) { console.log('look what we have found : ' + o} );
// All files
var all_files = findFiles(myPath);
Normally beans are POJO, so they have accessors anyway.
So the question is not "which one is better?", but simply "when to use field access?". And the answer is "when you don't need a setter/getter for the field!".
Actual Answer:
The default deserializer for enums uses .name()
to deserialize, so it's not using the @JsonValue
. So as @OldCurmudgeon pointed out, you'd need to pass in {"event": "FORGOT_PASSWORD"}
to match the .name()
value.
An other option (assuming you want the write and read json values to be the same)...
More Info:
There is (yet) another way to manage the serialization and deserialization process with Jackson. You can specify these annotations to use your own custom serializer and deserializer:
@JsonSerialize(using = MySerializer.class)
@JsonDeserialize(using = MyDeserializer.class)
public final class MyClass {
...
}
Then you have to write MySerializer
and MyDeserializer
which look like this:
MySerializer
public final class MySerializer extends JsonSerializer<MyClass>
{
@Override
public void serialize(final MyClass yourClassHere, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException
{
// here you'd write data to the stream with gen.write...() methods
}
}
MyDeserializer
public final class MyDeserializer extends org.codehaus.jackson.map.JsonDeserializer<MyClass>
{
@Override
public MyClass deserialize(final JsonParser parser, final DeserializationContext context) throws IOException, JsonProcessingException
{
// then you'd do something like parser.getInt() or whatever to pull data off the parser
return null;
}
}
Last little bit, particularly for doing this to an enum JsonEnum
that serializes with the method getYourValue()
, your serializer and deserializer might look like this:
public void serialize(final JsonEnum enumValue, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException
{
gen.writeString(enumValue.getYourValue());
}
public JsonEnum deserialize(final JsonParser parser, final DeserializationContext context) throws IOException, JsonProcessingException
{
final String jsonValue = parser.getText();
for (final JsonEnum enumValue : JsonEnum.values())
{
if (enumValue.getYourValue().equals(jsonValue))
{
return enumValue;
}
}
return null;
}
Try this:
@echo off
for /f "tokens=*" %%a in (input.txt) do (
echo line=%%a
)
pause
because of the tokens=*
everything is captured into %a
edit: to reply to your comment, you would have to do that this way:
@echo off
for /f "tokens=*" %%a in (input.txt) do call :processline %%a
pause
goto :eof
:processline
echo line=%*
goto :eof
:eof
Because of the spaces, you can't use %1
, because that would only contain the part until the first space. And because the line contains quotes, you can also not use :processline "%%a"
in combination with %~1
. So you need to use %*
which gets %1 %2 %3 ...
, so the whole line.
This does not want to be a "just-use-a-library" answer but just in case you're using Lodash you can use .clamp
:
_.clamp(yourInput, lowerBound, upperBound);
So that:
_.clamp(22, -10, 10); // => 10
Here is its implementation, taken from Lodash source:
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
Also, it's worth noting that Lodash makes single methods available as standalone modules, so in case you need only this method, you can install it without the rest of the library:
npm i --save lodash.clamp
Here is the Right way:-
axios.post('url', {"body":data}, {_x000D_
headers: {_x000D_
'Content-Type': 'application/json'_x000D_
}_x000D_
}_x000D_
)
_x000D_
The party's pretty much dead now, but here's an "improved" version of user166390 that made its way into my extension library. Apart from some details, I added a delegate to calculate the merged value.
/// <summary>
/// Merges a dictionary against an array of other dictionaries.
/// </summary>
/// <typeparam name="TResult">The type of the resulting dictionary.</typeparam>
/// <typeparam name="TKey">The type of the key in the resulting dictionary.</typeparam>
/// <typeparam name="TValue">The type of the value in the resulting dictionary.</typeparam>
/// <param name="source">The source dictionary.</param>
/// <param name="mergeBehavior">A delegate returning the merged value. (Parameters in order: The current key, The current value, The previous value)</param>
/// <param name="mergers">Dictionaries to merge against.</param>
/// <returns>The merged dictionary.</returns>
public static TResult MergeLeft<TResult, TKey, TValue>(
this TResult source,
Func<TKey, TValue, TValue, TValue> mergeBehavior,
params IDictionary<TKey, TValue>[] mergers)
where TResult : IDictionary<TKey, TValue>, new()
{
var result = new TResult();
var sources = new List<IDictionary<TKey, TValue>> { source }
.Concat(mergers);
foreach (var kv in sources.SelectMany(src => src))
{
TValue previousValue;
result.TryGetValue(kv.Key, out previousValue);
result[kv.Key] = mergeBehavior(kv.Key, kv.Value, previousValue);
}
return result;
}
As you noticed, these are Makefile {macros or variables}, not compiler options. They implement a set of conventions. (Macros is an old name for them, still used by some. GNU make doc calls them variables.)
The only reason that the names matter is the default make rules, visible via make -p
, which use some of them.
If you write all your own rules, you get to pick all your own macro names.
In a vanilla gnu make, there's no such thing as CCFLAGS. There are CFLAGS
, CPPFLAGS
, and CXXFLAGS
. CFLAGS
for the C compiler, CXXFLAGS
for C++, and CPPFLAGS
for both.
Why is CPPFLAGS
in both? Conventionally, it's the home of preprocessor flags (-D
, -U
) and both c and c++ use them. Now, the assumption that everyone wants the same define environment for c and c++ is perhaps questionable, but traditional.
P.S. As noted by James Moore, some projects use CPPFLAGS for flags to the C++ compiler, not flags to the C preprocessor. The Android NDK, for one huge example.
Your function worked for me after changing its declaration to this ...
Function processArr(Arr As Variant) As String
You could also consider a ParamArray
like this ...
Function processArr(ParamArray Arr() As Variant) As String
'Dim N As Variant
Dim N As Long
Dim finalStr As String
For N = LBound(Arr) To UBound(Arr)
finalStr = finalStr & Arr(N)
Next N
processArr = finalStr
End Function
And then call the function like this ...
processArr("foo", "bar")
This should be understood in the context of GitHub forks (where you fork a GitHub repo on GitHub before cloning that fork locally).
upstream
generally refers to the original repo that you have forkeddownstream
” and “upstream
”" for more on upstream
term) origin
is your fork: your own repo on GitHub, clone of the original repo of GitHubFrom the GitHub page:
When a repo is cloned, it has a default remote called
origin
that points to your fork on GitHub, not the original repo it was forked from.
To keep track of the original repo, you need to add another remote namedupstream
git remote add upstream git://github.com/<aUser>/<aRepo.git>
(with aUser/aRepo
the reference for the original creator and repository, that you have forked)
You will use upstream
to fetch from the original repo (in order to keep your local copy in sync with the project you want to contribute to).
git fetch upstream
(git fetch
alone would fetch from origin
by default, which is not what is needed here)
You will use origin
to pull and push since you can contribute to your own repository.
git pull
git push
(again, without parameters, 'origin' is used by default)
You will contribute back to the upstream
repo by making a pull request.
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
below will change link and banner every 10 seconds
<script>
var links = ["http://www.abc.com","http://www.def.com","http://www.ghi.com"];
var images = ["http://www.abc.com/1.gif","http://www.def.com/2.gif","http://www.ghi.com/3gif"];
var i = 0;
var renew = setInterval(function(){
if(links.length == i){
i = 0;
}
else {
document.getElementById("bannerImage").src = images[i];
document.getElementById("bannerLink").href = links[i];
i++;
}
},10000);
</script>
<a id="bannerLink" href="http://www.abc.com" onclick="void window.open(this.href); return false;">
<img id="bannerImage" src="http://www.abc.com/1.gif" width="694" height="83" alt="some text">
</a>
You might consider using a shell without history, like perhaps
/bin/sh << END
your commands without history
END
(perhaps /bin/dash
or /bin/sash
could be more appropriate than /bin/sh
)
or even better use the batch utility e.g
batch << EOB
your commands
EOB
The history would then contain sh
or batch
which is not very meaningful
The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203
The key function helped me and is very simple:
The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.
Example:
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
The above example will output:
fruit1<br />
fruit4<br />
fruit5<br />
Transparency is controlled by the alpha channel (AA
in #AARRGGBB
). Maximal value (255 dec, FF hex) means fully opaque. Minimum value (0 dec, 00 hex) means fully transparent. Values in between are semi-transparent, i.e. the color is mixed with the background color.
To get a fully transparent color set the alpha to zero. RR
, GG
and BB
are irrelevant in this case because no color will be visible. This means #00FFFFFF
("transparent White") is the same color as #00F0F8FF
("transparent AliceBlue").
To keep it simple one chooses black (#00000000
) or white (#00FFFFFF
) if the color does not matter.
In the table you linked to you'll find Transparent
defined as #00FFFFFF
.
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
This old question has a new answer. There are a few "async" solutions for PHP this days (which are equivalent to Python's multiprocess in the sense that they spawn new independent PHP processes rather than manage it at the framework level)
The two solutions I have seen are
Give them a try!
varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.
If you are still getting "find: missing argument to -exec" try wrapping the execute argument in quotes.
find <file path> -type f -exec "chmod 664 {} \;"
Many tricks work, but the Ajax request split the file name at 19 characters? Look at the output of the ajax request to see that:
The file name is okay to go into the href attribute, but the $(this).attr("href")
use
the text of the <a href='full/file/name' >
Split file name </a>
So the $(data).find("a:contains(.jpg)")
is not able to detect the extension.
I hope this is useful
open terminal and type the below command and hit enter
sudo /Library/PostgreSQL/9.X/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh
This works for me, hacked it once to see if it is possible, but never actually used in my program (GUI is so much nicer):
import time
f = '%4i %%'
len_to_clear = len(f)+1
clear = '\x08'* len_to_clear
print 'Progress in percent:'+' '*(len_to_clear),
for i in range(123):
print clear+f % (i*100//123),
time.sleep(0.4)
raw_input('\nDone')
My version: use data attributes and Vanilla JavaScript
<div class="test-checkbox">
Group One: <label>
<input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Eat" />Eat</label>
<label>
<input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Sleep" />Sleep</label>
<label>
<input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Play" />Play</label>
<br />
Group Two: <label>
<input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Fat" />Fat</label>
<label>
<input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Comfort" />Comfort</label>
<label>
<input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Happy" />Happy</label>
</div>
<script>
let cbxes = document.querySelectorAll('input[type="checkbox"][data-limit="only-one-in-a-group"]');
[...cbxes].forEach((cbx) => {
cbx.addEventListener('change', (e) => {
if (e.target.checked)
uncheckOthers(e.target);
});
});
function uncheckOthers (clicked) {
let name = clicked.getAttribute('name');
// find others in same group, uncheck them
[...cbxes].forEach((other) => {
if (other != clicked && other.getAttribute('name') == name)
other.checked = false;
});
}
</script>
The issue here is that input()
returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error.
To fix this, simply call int()
to convert your string to an integer:
int(input(...))
As a note, if you want to deal with decimal numbers, you will want to use one of float()
or decimal.Decimal()
(depending on your accuracy and speed needs).
Note that the more pythonic way of looping over a series of numbers (as opposed to a while
loop and counting) is to use range()
. For example:
def main():
print("Let me Retire Financial Calculator")
deposit = float(input("Please input annual deposit in dollars: $"))
rate = int(input ("Please input annual rate in percentage: %")) / 100
time = int(input("How many years until retirement?"))
value = 0
for x in range(1, time+1):
value = (value * rate) + deposit
print("The value of your account after" + str(x) + "years will be $" + str(value))
path = "/folderA/folderB/folderC/folderD/"
last = path.split('/').pop()
In case of Debug Running
~/Library/Developer/Xcode/DerivedData/{your app}/Build/Products/Debug/{Project Name}.app/Contents/MacOS
You can find standalone executable file(Mach-O 64-bit executable x86_64)
How do I convert a list of dictionaries to a pandas DataFrame?
The other answers are correct, but not much has been explained in terms of advantages and limitations of these methods. The aim of this post will be to show examples of these methods under different situations, discuss when to use (and when not to use), and suggest alternatives.
DataFrame()
, DataFrame.from_records()
, and .from_dict()
Depending on the structure and format of your data, there are situations where either all three methods work, or some work better than others, or some don't work at all.
Consider a very contrived example.
np.random.seed(0)
data = pd.DataFrame(
np.random.choice(10, (3, 4)), columns=list('ABCD')).to_dict('r')
print(data)
[{'A': 5, 'B': 0, 'C': 3, 'D': 3},
{'A': 7, 'B': 9, 'C': 3, 'D': 5},
{'A': 2, 'B': 4, 'C': 7, 'D': 6}]
This list consists of "records" with every keys present. This is the simplest case you could encounter.
# The following methods all produce the same output.
pd.DataFrame(data)
pd.DataFrame.from_dict(data)
pd.DataFrame.from_records(data)
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
orient='index'
/'columns'
Before continuing, it is important to make the distinction between the different types of dictionary orientations, and support with pandas. There are two primary types: "columns", and "index".
orient='columns'
Dictionaries with the "columns" orientation will have their keys correspond to columns in the equivalent DataFrame.
For example, data
above is in the "columns" orient.
data_c = [
{'A': 5, 'B': 0, 'C': 3, 'D': 3},
{'A': 7, 'B': 9, 'C': 3, 'D': 5},
{'A': 2, 'B': 4, 'C': 7, 'D': 6}]
pd.DataFrame.from_dict(data_c, orient='columns')
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
Note: If you are using pd.DataFrame.from_records
, the orientation is assumed to be "columns" (you cannot specify otherwise), and the dictionaries will be loaded accordingly.
orient='index'
With this orient, keys are assumed to correspond to index values. This kind of data is best suited for pd.DataFrame.from_dict
.
data_i ={
0: {'A': 5, 'B': 0, 'C': 3, 'D': 3},
1: {'A': 7, 'B': 9, 'C': 3, 'D': 5},
2: {'A': 2, 'B': 4, 'C': 7, 'D': 6}}
pd.DataFrame.from_dict(data_i, orient='index')
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
This case is not considered in the OP, but is still useful to know.
If you need a custom index on the resultant DataFrame, you can set it using the index=...
argument.
pd.DataFrame(data, index=['a', 'b', 'c'])
# pd.DataFrame.from_records(data, index=['a', 'b', 'c'])
A B C D
a 5 0 3 3
b 7 9 3 5
c 2 4 7 6
This is not supported by pd.DataFrame.from_dict
.
All methods work out-of-the-box when handling dictionaries with missing keys/column values. For example,
data2 = [
{'A': 5, 'C': 3, 'D': 3},
{'A': 7, 'B': 9, 'F': 5},
{'B': 4, 'C': 7, 'E': 6}]
# The methods below all produce the same output.
pd.DataFrame(data2)
pd.DataFrame.from_dict(data2)
pd.DataFrame.from_records(data2)
A B C D E F
0 5.0 NaN 3.0 3.0 NaN NaN
1 7.0 9.0 NaN NaN NaN 5.0
2 NaN 4.0 7.0 NaN 6.0 NaN
"What if I don't want to read in every single column"? You can easily specify this using the columns=...
parameter.
For example, from the example dictionary of data2
above, if you wanted to read only columns "A', 'D', and 'F', you can do so by passing a list:
pd.DataFrame(data2, columns=['A', 'D', 'F'])
# pd.DataFrame.from_records(data2, columns=['A', 'D', 'F'])
A D F
0 5.0 3.0 NaN
1 7.0 NaN 5.0
2 NaN NaN NaN
This is not supported by pd.DataFrame.from_dict
with the default orient "columns".
pd.DataFrame.from_dict(data2, orient='columns', columns=['A', 'B'])
ValueError: cannot use columns parameter with orient='columns'
Not supported by any of these methods directly. You will have to iterate over your data and perform a reverse delete in-place as you iterate. For example, to extract only the 0th and 2nd rows from data2
above, you can use:
rows_to_select = {0, 2}
for i in reversed(range(len(data2))):
if i not in rows_to_select:
del data2[i]
pd.DataFrame(data2)
# pd.DataFrame.from_dict(data2)
# pd.DataFrame.from_records(data2)
A B C D E
0 5.0 NaN 3 3.0 NaN
1 NaN 4.0 7 NaN 6.0
json_normalize
for Nested DataA strong, robust alternative to the methods outlined above is the json_normalize
function which works with lists of dictionaries (records), and in addition can also handle nested dictionaries.
pd.json_normalize(data)
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
pd.json_normalize(data2)
A B C D E
0 5.0 NaN 3 3.0 NaN
1 NaN 4.0 7 NaN 6.0
Again, keep in mind that the data passed to json_normalize
needs to be in the list-of-dictionaries (records) format.
As mentioned, json_normalize
can also handle nested dictionaries. Here's an example taken from the documentation.
data_nested = [
{'counties': [{'name': 'Dade', 'population': 12345},
{'name': 'Broward', 'population': 40000},
{'name': 'Palm Beach', 'population': 60000}],
'info': {'governor': 'Rick Scott'},
'shortname': 'FL',
'state': 'Florida'},
{'counties': [{'name': 'Summit', 'population': 1234},
{'name': 'Cuyahoga', 'population': 1337}],
'info': {'governor': 'John Kasich'},
'shortname': 'OH',
'state': 'Ohio'}
]
pd.json_normalize(data_nested,
record_path='counties',
meta=['state', 'shortname', ['info', 'governor']])
name population state shortname info.governor
0 Dade 12345 Florida FL Rick Scott
1 Broward 40000 Florida FL Rick Scott
2 Palm Beach 60000 Florida FL Rick Scott
3 Summit 1234 Ohio OH John Kasich
4 Cuyahoga 1337 Ohio OH John Kasich
For more information on the meta
and record_path
arguments, check out the documentation.
Here's a table of all the methods discussed above, along with supported features/functionality.
* Use orient='columns'
and then transpose to get the same effect as orient='index'
.
You can use a lambda:
Collectors.toMap(p -> p.getLast(), Function.identity())
or, more concisely, you can use a method reference using ::
:
Collectors.toMap(Person::getLast, Function.identity())
and instead of Function.identity
, you can simply use the equivalent lambda:
Collectors.toMap(Person::getLast, p -> p)
If you use Netbeans you should get hints whenever an anonymous class can be replaced by a lambda.
If you look at the output you receive from print()
and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b
):
b'{\n "note":"This file .....
If you fetch the URL using a tool such as curl -v
, you will see that the content type is
Content-Type: application/json; charset=utf-8
So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.
Change the last line of code to this:
info = json.loads(js.decode("utf-8"))
If you want some dynamic sizing in conjunction with a word-wrapping label you can do the following:
Handle the ClientSizeChanged event
for the panel, making the
label fill the space:
private void Panel2_ClientSizeChanged(object sender, EventArgs e)
{
label1.MaximumSize = new Size((sender as Control).ClientSize.Width - label1.Left, 10000);
}
Set Auto-Size
for the label to true
Dock
for the label to Fill
I had the same problem ("Uncaught TypeError: Cannot read property 'top' of undefined")
I tried every solution I could find and noting helped. But then I've spotted that my DIV had two IDs.
So, I removed second ID and it worked.
I just wish somebody told me to check my IDs earlier))
I'm using jQuery and JavaScript and it works fine for me:
var rege = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(rege.test($('#uemail').val())){ //do something }
if Matcher is initialized with str
, after the match, you can get the part after the match with
str.substring(matcher.end())
Sample Code:
final String str = "Some lame sentence that is awesome";
final Matcher matcher = Pattern.compile("sentence").matcher(str);
if(matcher.find()){
System.out.println(str.substring(matcher.end()).trim());
}
Output:
that is awesome
Starting with Ruby 2.4.0, you may use RegExp#match?
:
pattern.match?(string)
Regexp#match?
is explicitly listed as a performance enhancement in the release notes for 2.4.0, as it avoids object allocations performed by other methods such as Regexp#match
and =~
:
Regexp#match?
AddedRegexp#match?
, which executes a regexp match without creating a back reference object and changing$~
to reduce object allocation.
I'm not sure what server side technology you are using but try using a json array. A couple of options for you to try:
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay"
},
[
1436517454492,
1436517476993
]
If that doesn't work you may also try:
{
freelancer: {
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay"
},
skills : [
1436517454492,
1436517476993
]
}
man 1 nm
For example:
nm -gU /usr/local/Cellar/cairo/1.12.16/lib/cairo/libcairo-trace.0.dylib
I would EXPECT the first query to be quicker, mainly because you have an equivalence and an explicit JOIN. In my experience IN
is a very slow operator, since SQL normally evaluates it as a series of WHERE
clauses separated by "OR" (WHERE x=Y OR x=Z OR...
).
As with ALL THINGS SQL though, your mileage may vary. The speed will depend a lot on indexes (do you have indexes on both ID columns? That will help a lot...) among other things.
The only REAL way to tell with 100% certainty which is faster is to turn on performance tracking (IO Statistics is especially useful) and run them both. Make sure to clear your cache between runs!
The GIMP (GNU Image Manipulation Program). It's free, open source and runs on Windows and Linux (and maybe Mac?).
in my case the problem was into outdated "../bootstrap/cache/packages.php and services.php"
I have had to. drop those files and rerun composer install...
Erroneous data format for unserializing 'Symfony\Component\Routing\CompiledRoute'
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1
For applications such as games and embedded systems where memory and performance are both critical, float is usually the numeric type of choice as it is faster and half the size of a double. Integers used to be the weapon of choice, but floating point performance has overtaken integer in modern processors. Decimal is right out!
You will need to read the bytes
from that File
into a byte[]
and put that object into your JSONObject
.
You should also have a look at the following posts :
Hope this helps.
Just divide the number of td to 100%. Example, you have 4 td's:
<html>
<table>
<tr>
<td style="width:25%">This is a text</td>
<td style="width:25%">This is some text, this is some text</td>
<td style="width:25%">This is another text, this is another text</td>
<td style="width:25%">This is the last text, this is the last text</td>
</tr>
</table>
</html>
We use 25% in each td to maximize the 100% space of the entire table
You need to have a launch configuration inside Eclipse in order to adjust the JVM parameters.
After running your program with either F11 or Ctrl-F11, open the launch configurations in Run -> Run Configurations... and open your program under "Java Applications". Select the Arguments pane, where you will find "VM arguments".
This is where -Xss1024k
goes.
If you want the launch configuration to be a file in your workspace (so you can right click and run it), select the Common pane, and check the Save as -> Shared File checkbox and browse to the location you want the launch file. I usually have them in a separate folder, as we check them into CVS.
HTML
<img src="images/bg.jpg" id="bg" alt="">
CSS
#bg {
position: fixed;
top: 0;
left: 0;
/* Preserve aspet ratio */
min-width: 100%;
min-height: 100%;
}
I got this error even after uninstalling the original APK, which was mystifying. Finally I realized that I had set up multiple users on my Nexus 7 for testing and that the app was still installed for one of the other users. Once I uninstalled it for all users the error went away.
I think, you may want to try another approach with folding enabled.
In both ST2 and ST3, if you enable folding in User settings:
{
...(previous item)
"fold_buttons": true,
...(next item, thus the comma)
}
You can see the triangle folding button at the left side of the line where the start tag is. Click it to expand/fold. If you want to copy, fold and copy, you get all block.
The easiest way to do this is to use jQuery : jQuery UI combobox/autocomplete
I've found a couple other ways you can write these which are a bit more readable IMHO.
- name: check out a git repository
local_action:
module: git
repo: git://foosball.example.org/path/to/repo.git
dest: /local/path
OR
- name: check out a git repository
local_action: git
args:
repo: git://foosball.example.org/path/to/repo.git
dest: /local/path
I've tried a few solutions here and didn't find the one that writes into file and into console at the same time. So here is what I did (based on this answer)
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
def write(self, message):
with open ("logfile.log", "a", encoding = 'utf-8') as self.log:
self.log.write(message)
self.terminal.write(message)
def flush(self):
#this flush method is needed for python 3 compatibility.
#this handles the flush command by doing nothing.
#you might want to specify some extra behavior here.
pass
sys.stdout = Logger()
This solution uses more computing power, but reliably saves all of the data from stdout into logger file and uses less memeory. For my needs I've added time stamp into self.log.write(message) aswell. Works great.
"Knowing about sites which handles such massive traffic gives lots of pointers for architects etc. to keep in mind certain stuff while designing new sites"
I think you can probably learn a lot from the design of Facebook, just as you can from the design of any successful large software system. However, it seems to me that you should not keep the current design of Facebook in mind when designing new systems.
Why do you want to be able to handle the traffic that Facebook has to handle? Odds are that you will never have to, no matter how talented a programmer you may be. Facebook itself was not designed from the start for such massive scalability, which is perhaps the most important lesson to learn from it.
If you want to learn about a non-trivial software system I can recommend the book "Dissecting a C# Application" about the development of the SharpDevelop IDE. It is out of print, but it is available for free online. The book gives you a glimpse into a real application and provides insights about IDEs which are useful for a programmer.
For Oracle versions which does not support the WM_CONCAT, the following can be used
select "User", RTRIM(
XMLAGG (XMLELEMENT(e, department||',') ORDER BY department).EXTRACT('//text()') , ','
) AS departments
from yourtable
group by "User"
This one is much more powerful and flexible - you can specify both delimiters and sort order within each group as in listagg.
Use distinct-colors.
Written in javascript.
It generates a palette of visually distinct colors.
distinct-colors is highly configurable:
background-image: url(/images/poster.png);
background-position: center;
background-position-y: 50px;
background-repeat: no-repeat;
@John, Earlz and Nathan. The way I learned it at uni is: functions return values, methods don't. In some languages the syntax is/was actually different. Example (no specific language):
Method SetY(int y) ...
Function CalculateY(int x) As Integer ...
Most languages now use the same syntax for both versions, using void as a return type to say there actually isn't a return type. I assume it's because the syntax is more consistent and easier to change from method to function, and vice versa.
That format requires you to use either:
CASE ebv.db_no
WHEN 22978 THEN 'WECS 9500'
WHEN 23218 THEN 'WECS 9500'
WHEN 23219 THEN 'WECS 9500'
ELSE 'WECS 9520'
END as wecs_system
Otherwise, use:
CASE
WHEN ebv.db_no IN (22978, 23218, 23219) THEN 'WECS 9500'
ELSE 'WECS 9520'
END as wecs_system
Yup. :) You can use Hipify to convert CUDA code very easily to HIP code which can be compiled run on both AMD and nVidia hardware pretty good. Here are some links
Yes in SQl <> is the same as != which is not equal.....excepts for NULLS of course, in that case you need to use IS NULL or IS NOT NULL
For me, I had to remove the intellij internal sdk and started to use my local sdk. When I started to use the internal, the error was gone.
What seems to be confusing you is the fact that functions that are declared to be pass-by-reference (using the &
) aren't called using actual addresses, i.e. &a
.
The simple answer is that declaring a function as pass-by-reference:
void foo(int& x);
is all we need. It's then passed by reference automatically.
You now call this function like so:
int y = 5;
foo(y);
and y
will be passed by reference.
You could also do it like this (but why would you? The mantra is: Use references when possible, pointers when needed) :
#include <iostream>
using namespace std;
class CDummy {
public:
int isitme (CDummy* param);
};
int CDummy::isitme (CDummy* param)
{
if (param == this) return true;
else return false;
}
int main () {
CDummy a;
CDummy* b = &a; // assigning address of a to b
if ( b->isitme(&a) ) // Called with &a (address of a) instead of a
cout << "yes, &a is b";
return 0;
}
Output:
yes, &a is b
SELECT
*
FROM
primarytable P
WHERE
NOT EXISTS (SELECT * FROM secondarytable S
WHERE
P.PKCol = S.FKCol)
Generally, (NOT) EXISTS
is a better choice then (NOT) IN
or (LEFT) JOIN
Do this:
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
Context initialContext = new InitialContext(props);
Also add this to the libraries of the project:
C:\installs\glassfish\glassfish-4.1\glassfish\lib\gf-client.jar
adjust path accordingly
Try this in Swift :
var urlString = myUrl.absoluteString
Objective-C:
NSString *urlString = [myURL absoluteString];
Here is a solution without any loop or recursion but works for non-negative integers only (Python3):
def sum_digits(n):
if n > 0:
s = (n-1) // 9
return n-9*s
return 0
With Java 8:
String csv = String.join(",", ids);
With Java 7-, there is a dirty way (note: it works only if you don't insert strings which contain ", "
in your list) - obviously, List#toString
will perform a loop to create idList
but it does not appear in your code:
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String idList = ids.toString();
String csv = idList.substring(1, idList.length() - 1).replace(", ", ",");
Aah you just need to add a name parameter in the
FileBody constructor. ContentBody cbFile = new FileBody(file, "image/jpeg", "FILE_NAME");
Hope it helps.
In my case, it was due to Same Origin policies. To explain it further, MDN states the following:
If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.
Simple Solution
Here is a simple solution. No additional for loop required.
HTML part
<table ng-init="ResetTotalAmt()">
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr ng-repeat="product in cart.products">
<td ng-init="CalculateSum(product)">{{product.name}}</td>
<td>{{product.quantity}}</td>
<td>{{product.price * product.quantity}} €</td>
</tr>
<tr>
<td></td>
<td>Total :</td>
<td>{{cart.TotalAmt}}</td> // Here is the total value of my cart
</tr>
</table>
Script Part
$scope.cart.TotalAmt = 0;
$scope.CalculateSum= function (product) {
$scope.cart.TotalAmt += (product.price * product.quantity);
}
//It is enough to Write code $scope.cart.TotalAmt =0; in the function where the cart.products get allocated value.
$scope.ResetTotalAmt = function (product) {
$scope.cart.TotalAmt =0;
}
As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron
. Hence, do install it with:
yum install vixie-cron
And then start it with:
service crond start
To make it persistent, so that it starts on boot, use:
chkconfig crond on
On CentOS 7 you need to use cronie
:
yum install cronie
On CentOS 6 you can install vixie-cron
, but the real package is cronie
:
yum install vixie-cron
and
yum install cronie
In both cases you get the same output:
.../...
==================================================================
Package Arch Version Repository Size
==================================================================
Installing:
cronie x86_64 1.4.4-12.el6 base 73 k
Installing for dependencies:
cronie-anacron x86_64 1.4.4-12.el6 base 30 k
crontabs noarch 1.10-33.el6 base 10 k
exim x86_64 4.72-6.el6 epel 1.2 M
Transaction Summary
==================================================================
Install 4 Package(s)
At first, you need to add :
after the IP address to indicate the path is following:
scp magento.tar.gz [email protected]:/var/www
I don't think you need to sudo
the scp
. In this case it doesn't affect the remote machine, only the local command.
Then if your user
@xx.x.x.xx doesn't have write access to /var/www
then you need to do it in 2 times:
Copy to remote server in your home folder (:
represents your remote home folder, use :subfolder/
if needed, or :/home/user/
for full path):
scp magento.tar.gz [email protected]:
Then SSH and move the file:
ssh [email protected]
sudo mv magento.tar.gz /var/www
Tilde expansion in Bash:
http://bash-hackers.org/wiki/doku.php/syntax/expansion/tilde
I know this is somewhat older, but since the keywords "border inside" landed me directly here, I would like to share some findings that may be worth mentioning here. When I was adding a border on the hover state, i got the effects that OP is talking about. The border ads pixels to the dimension of the box which made it jumpy. There is two more ways one can deal with this that also work for IE7.
1) Have a border already attached to the element and simply change the color. This way the mathematics are already included.
div {
width:100px;
height:100px;
background-color: #aaa;
border: 2px solid #aaa; /* notice the solid */
}
div:hover {
border: 2px dashed #666;
}
2 ) Compensate your border with a negative margin. This will still add the extra pixels, but the positioning of the element will not be jumpy on
div {
width:100px;
height:100px;
background-color: #aaa;
}
div:hover {
margin: -2px;
border: 2px dashed #333;
}
Not Knowing all of your requirements. For example, are you trying to uniquely identify a computer from all of the computers in the world, or are you just trying to uniquely identify a computer from a set of users of your application. Also, can you create files on the system?
If you are able to create a file. You could create a file and use the creation time of the file as your unique id. If you create it in user space then it would uniquely identify a user of your application on a particular machine. If you created it somewhere global then it could uniquely identify the machine.
Again, as most things, How fast is fast enough.. or in this case, how unique is unique enough.
had a simliar problem with that connection exception. it is thrown either when the registry is not started yet (like in your case) or when the registry is already unexported (like in my case).
but a short comment to the difference between the 2 ways to start the registry:
Runtime.getRuntime().exec("rmiregistry 2020");
runs the rmiregistry.exe in javas bin-directory in a new process and continues parallel with your java code.
LocateRegistry.createRegistry(2020);
the rmi method call starts the registry, returns the reference to that registry remote object and then continues with the next statement.
in your case the registry is not started in time when you try to bind your object
REVERSE(SUBSTRING(REVERSE(ap_description),CHARINDEX('.',REVERSE(ap_description)),len(ap_description)))
worked better for me
You don't define the vector, url
, before trying to subset it. url
is also a function in the base package, so url[i]
is attempting to subset that function... which doesn't make sense.
You probably defined url
in your prior R session, but forgot to copy that code to your script.
if ( ( single conditional expression A )
&& ( single conditional expression B )
&& ( single conditional expression C )
)
{
opAllABC();
}
else
{
opNoneABC();
}
Formatting a multiple conditional expressions in an if-else statement this way:
// disable any single conditional test with just a pre-pended '//'
// set a break point before any individual test
// syntax '(1 &&' and '(0 ||' usually never creates any real code
if ( 1
&& ( single conditional expression A )
&& ( single conditional expression B )
&& ( 0
|| ( single conditional expression C )
|| ( single conditional expression D )
)
)
{
... ;
}
else
{
... ;
}
I did it this way: Just add the event to any control, set the control's tag, and add a conditional to handle the tooltip for the appropriate control/tag.
private void Info_MouseHover(object sender, EventArgs e)
{
Control senderObject = sender as Control;
string hoveredControl = senderObject.Tag.ToString();
// only instantiate a tooltip if the control's tag contains data
if (hoveredControl != "")
{
ToolTip info = new ToolTip
{
AutomaticDelay = 500
};
string tooltipMessage = string.Empty;
// add all conditionals here to modify message based on the tag
// of the hovered control
if (hoveredControl == "save button")
{
tooltipMessage = "This button will save stuff.";
}
info.SetToolTip(senderObject, tooltipMessage);
}
}
I always find it interesting to run some benchmarks to see the relative speed of the various ways of doing something.
Finding an array element at the start, middle or end will affect any linear searches but barely affect a search against a Set.
Converting an Array to a Set is going to cause a hit in processing time, so create the Set from an Array once, or start with a Set from the very beginning.
Here's the benchmark code:
# frozen_string_literal: true
require 'fruity'
require 'set'
ARRAY = (1..20_000).to_a
SET = ARRAY.to_set
DIVIDER = '-' * 20
def array_include?(elem)
ARRAY.include?(elem)
end
def array_member?(elem)
ARRAY.member?(elem)
end
def array_index(elem)
ARRAY.index(elem) >= 0
end
def array_find_index(elem)
ARRAY.find_index(elem) >= 0
end
def array_index_each(elem)
ARRAY.index { |each| each == elem } >= 0
end
def array_find_index_each(elem)
ARRAY.find_index { |each| each == elem } >= 0
end
def array_any_each(elem)
ARRAY.any? { |each| each == elem }
end
def array_find_each(elem)
ARRAY.find { |each| each == elem } != nil
end
def array_detect_each(elem)
ARRAY.detect { |each| each == elem } != nil
end
def set_include?(elem)
SET.include?(elem)
end
def set_member?(elem)
SET.member?(elem)
end
puts format('Ruby v.%s', RUBY_VERSION)
{
'First' => ARRAY.first,
'Middle' => (ARRAY.size / 2).to_i,
'Last' => ARRAY.last
}.each do |k, element|
puts DIVIDER, k, DIVIDER
compare do
_array_include? { array_include?(element) }
_array_member? { array_member?(element) }
_array_index { array_index(element) }
_array_find_index { array_find_index(element) }
_array_index_each { array_index_each(element) }
_array_find_index_each { array_find_index_each(element) }
_array_any_each { array_any_each(element) }
_array_find_each { array_find_each(element) }
_array_detect_each { array_detect_each(element) }
end
end
puts '', DIVIDER, 'Sets vs. Array.include?', DIVIDER
{
'First' => ARRAY.first,
'Middle' => (ARRAY.size / 2).to_i,
'Last' => ARRAY.last
}.each do |k, element|
puts DIVIDER, k, DIVIDER
compare do
_array_include? { array_include?(element) }
_set_include? { set_include?(element) }
_set_member? { set_member?(element) }
end
end
Which, when run on my Mac OS laptop, results in:
Ruby v.2.7.0
--------------------
First
--------------------
Running each test 65536 times. Test will take about 5 seconds.
_array_include? is similar to _array_index
_array_index is similar to _array_find_index
_array_find_index is faster than _array_any_each by 2x ± 1.0
_array_any_each is similar to _array_index_each
_array_index_each is similar to _array_find_index_each
_array_find_index_each is faster than _array_member? by 4x ± 1.0
_array_member? is faster than _array_detect_each by 2x ± 1.0
_array_detect_each is similar to _array_find_each
--------------------
Middle
--------------------
Running each test 32 times. Test will take about 2 seconds.
_array_include? is similar to _array_find_index
_array_find_index is similar to _array_index
_array_index is faster than _array_member? by 2x ± 0.1
_array_member? is faster than _array_index_each by 2x ± 0.1
_array_index_each is similar to _array_find_index_each
_array_find_index_each is similar to _array_any_each
_array_any_each is faster than _array_detect_each by 30.000000000000004% ± 10.0%
_array_detect_each is similar to _array_find_each
--------------------
Last
--------------------
Running each test 16 times. Test will take about 2 seconds.
_array_include? is faster than _array_find_index by 10.000000000000009% ± 10.0%
_array_find_index is similar to _array_index
_array_index is faster than _array_member? by 3x ± 0.1
_array_member? is faster than _array_find_index_each by 2x ± 0.1
_array_find_index_each is similar to _array_index_each
_array_index_each is similar to _array_any_each
_array_any_each is faster than _array_detect_each by 30.000000000000004% ± 10.0%
_array_detect_each is similar to _array_find_each
--------------------
Sets vs. Array.include?
--------------------
--------------------
First
--------------------
Running each test 65536 times. Test will take about 1 second.
_array_include? is similar to _set_include?
_set_include? is similar to _set_member?
--------------------
Middle
--------------------
Running each test 65536 times. Test will take about 2 minutes.
_set_member? is similar to _set_include?
_set_include? is faster than _array_include? by 1400x ± 1000.0
--------------------
Last
--------------------
Running each test 65536 times. Test will take about 4 minutes.
_set_member? is similar to _set_include?
_set_include? is faster than _array_include? by 3000x ± 1000.0
Basically the results tell me to use a Set for everything if I'm going to search for inclusion unless I can guarantee that the first element is the one I want, which isn't very likely. There's some overhead when inserting elements into a hash, but the search times are so much faster I don't think that should ever be a consideration. Again, if you need to search it, don't use an Array, use a Set. (Or a Hash.)
The smaller the Array, the faster the Array methods will run, but they're still not going to keep up, though in small arrays the difference might be tiny.
"First", "Middle" and "Last" reflect the use of first
, size / 2
and last
for ARRAY
for the element being searched for. That element will be used when searching the ARRAY
and SET
variables.
Minor changes were made for the methods that were comparing to > 0
because the test should be >= 0
for index
type tests.
More information about Fruity and its methodology is available in its README.
Do git help gitignore
You will get the help page with following line:
A line starting with # serves as a comment.
Another reason is maybe "access denided", maybe you can't access to the URI and received blocking response page for internal network access. If you are not sure your application zone need firewall rule, you try to connect from terminal,command line.
For GNU/Linux or Unix, you can try run like this command and see result is coming from blocking rule or really remote address: echo | nc -v yazilimcity.net 443
Here is what I generally use in Jupyter Notebook:
# Jupyter Notebook settings
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:95% !important; }</style>"))
%autosave 0
%matplotlib inline
%load_ext autoreload
%autoreload 2
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
# Imports for data analysis
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', 2500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_colwidth', 2000)
pd.set_option('display.width', 2000)
pd.set_option('display.float_format', lambda x: '%.3f' % x)
#size=25
size=15
params = {'legend.fontsize': 'large',
'figure.figsize': (20,8),
'axes.labelsize': size,
'axes.titlesize': size,
'xtick.labelsize': size*0.75,
'ytick.labelsize': size*0.75,
'axes.titlepad': 25}
plt.rcParams.update(params)
You could simply use:
select {
border: none;
outline: none;
scroll-behavior: smooth;
}
As the drop down list border is non editable you can not do anything with that but surely this will fix your initial outlook.
use jQuery's $.getJSON
$.getJSON('mydata.json', function(data) {
//do stuff with your data here
});
Use this for legacy code (PHP < 5.3). For up to date solution see jurka's answer below
You can use strtotime() to convert two dates to unix time and then calculate the number of seconds between them. From this it's rather easy to calculate different time periods.
$date1 = "2007-03-24";
$date2 = "2009-06-26";
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
printf("%d years, %d months, %d days\n", $years, $months, $days);
Edit: Obviously the preferred way of doing this is like described by jurka below. My code is generally only recommended if you don't have PHP 5.3 or better.
Several people in the comments have pointed out that the code above is only an approximation. I still believe that for most purposes that's fine, since the usage of a range is more to provide a sense of how much time has passed or remains rather than to provide precision - if you want to do that, just output the date.
Despite all that, I've decided to address the complaints. If you truly need an exact range but haven't got access to PHP 5.3, use the code below (it should work in PHP 4 as well). This is a direct port of the code that PHP uses internally to calculate ranges, with the exception that it doesn't take daylight savings time into account. That means that it's off by an hour at most, but except for that it should be correct.
<?php
/**
* Calculate differences between two dates with precise semantics. Based on PHPs DateTime::diff()
* implementation by Derick Rethans. Ported to PHP by Emil H, 2011-05-02. No rights reserved.
*
* See here for original code:
* http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/tm2unixtime.c?revision=302890&view=markup
* http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/interval.c?revision=298973&view=markup
*/
function _date_range_limit($start, $end, $adj, $a, $b, $result)
{
if ($result[$a] < $start) {
$result[$b] -= intval(($start - $result[$a] - 1) / $adj) + 1;
$result[$a] += $adj * intval(($start - $result[$a] - 1) / $adj + 1);
}
if ($result[$a] >= $end) {
$result[$b] += intval($result[$a] / $adj);
$result[$a] -= $adj * intval($result[$a] / $adj);
}
return $result;
}
function _date_range_limit_days($base, $result)
{
$days_in_month_leap = array(31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
$days_in_month = array(31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
_date_range_limit(1, 13, 12, "m", "y", &$base);
$year = $base["y"];
$month = $base["m"];
if (!$result["invert"]) {
while ($result["d"] < 0) {
$month--;
if ($month < 1) {
$month += 12;
$year--;
}
$leapyear = $year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0);
$days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month];
$result["d"] += $days;
$result["m"]--;
}
} else {
while ($result["d"] < 0) {
$leapyear = $year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0);
$days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month];
$result["d"] += $days;
$result["m"]--;
$month++;
if ($month > 12) {
$month -= 12;
$year++;
}
}
}
return $result;
}
function _date_normalize($base, $result)
{
$result = _date_range_limit(0, 60, 60, "s", "i", $result);
$result = _date_range_limit(0, 60, 60, "i", "h", $result);
$result = _date_range_limit(0, 24, 24, "h", "d", $result);
$result = _date_range_limit(0, 12, 12, "m", "y", $result);
$result = _date_range_limit_days(&$base, &$result);
$result = _date_range_limit(0, 12, 12, "m", "y", $result);
return $result;
}
/**
* Accepts two unix timestamps.
*/
function _date_diff($one, $two)
{
$invert = false;
if ($one > $two) {
list($one, $two) = array($two, $one);
$invert = true;
}
$key = array("y", "m", "d", "h", "i", "s");
$a = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $one))));
$b = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $two))));
$result = array();
$result["y"] = $b["y"] - $a["y"];
$result["m"] = $b["m"] - $a["m"];
$result["d"] = $b["d"] - $a["d"];
$result["h"] = $b["h"] - $a["h"];
$result["i"] = $b["i"] - $a["i"];
$result["s"] = $b["s"] - $a["s"];
$result["invert"] = $invert ? 1 : 0;
$result["days"] = intval(abs(($one - $two)/86400));
if ($invert) {
_date_normalize(&$a, &$result);
} else {
_date_normalize(&$b, &$result);
}
return $result;
}
$date = "1986-11-10 19:37:22";
print_r(_date_diff(strtotime($date), time()));
print_r(_date_diff(time(), strtotime($date)));
If it is a category page,you can get id of current category by:
$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;
If you want to get category id of any particular category on any page, try using :
$category_id = get_cat_ID('Category Name');
to get the object you do not need to use cURL (you are loading another dll into memory and have another dependency, unless you really need curl I'd stick with built in php functions), you can use one simple php file_get_contents(url) function: http://il1.php.net/manual/en/function.file-get-contents.php
$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");
$json_object = json_decode($unparsed_json);
then json_decode() parses JSON into a PHP object, or an array if you pass true
to the second parameter.
http://php.net/manual/en/function.json-decode.php
For example:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json)); // Object
var_dump(json_decode($json, true)); // Associative array
I ran into a situation where I needed to have an appendable string of unknown size. These are the benchmark results (python 2.7.3):
$ python -m timeit -s 's=""' 's+="a"'
10000000 loops, best of 3: 0.176 usec per loop
$ python -m timeit -s 's=[]' 's.append("a")'
10000000 loops, best of 3: 0.196 usec per loop
$ python -m timeit -s 's=""' 's="".join((s,"a"))'
100000 loops, best of 3: 16.9 usec per loop
$ python -m timeit -s 's=""' 's="%s%s"%(s,"a")'
100000 loops, best of 3: 19.4 usec per loop
This seems to show that '+=' is the fastest. The results from the skymind link are a bit out of date.
(I realize that the second example is not complete, the final list would need to be joined. This does show, however, that simply preparing the list takes longer than the string concat.)
I had the same problem but solved it running following:
$ adb shell
$ run-as {app-package-name}
$ cd /data/data/{app-package-name}
$ chmod 777 {file}
$ cp {file} /mnt/sdcard/
After this you can run
$ adb pull /mnt/sdcard/{file}
In my case (Mac OS Mojave), the key is to use the full path
$umount -f /Volumnes/fullpath/folder
There are some references and pointers in the comments on this page at PHP.net:
Torsten says
"Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier. If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements."
Jetboy says
"according to this: http://www.w3.org/TR/xhtml1/#C_8 the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.
Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document."
Use multiple datasource or realizing the separation of reading & writing.
you must have a knowledge of Class AbstractRoutingDataSource
which support dynamic datasource choose.
Here is my datasource.yaml
and I figure out how to resolve this case. You can refer to this project spring-boot + quartz. Hope this will help you.
dbServer:
default: localhost:3306
read: localhost:3306
write: localhost:3306
datasource:
default:
type: com.zaxxer.hikari.HikariDataSource
pool-name: default
continue-on-error: false
jdbc-url: jdbc:mysql://${dbServer.default}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
username: root
password: lh1234
connection-timeout: 30000
connection-test-query: SELECT 1
maximum-pool-size: 5
minimum-idle: 2
idle-timeout: 600000
destroy-method: shutdown
auto-commit: false
read:
type: com.zaxxer.hikari.HikariDataSource
pool-name: read
continue-on-error: false
jdbc-url: jdbc:mysql://${dbServer.read}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
username: root
password: lh1234
connection-timeout: 30000
connection-test-query: SELECT 1
maximum-pool-size: 5
minimum-idle: 2
idle-timeout: 600000
destroy-method: shutdown
auto-commit: false
write:
type: com.zaxxer.hikari.HikariDataSource
pool-name: write
continue-on-error: false
jdbc-url: jdbc:mysql://${dbServer.write}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
username: root
password: lh1234
connection-timeout: 30000
connection-test-query: SELECT 1
maximum-pool-size: 5
minimum-idle: 2
idle-timeout: 600000
destroy-method: shutdown
auto-commit: false
Ok, if anyone ever reads this: the best option is to add four
s at each extra level of indentation, it would seem!
so:
<select>_x000D_
<optgroup label="Level One">_x000D_
<option> A.1 </option>_x000D_
<optgroup label=" Level Two">_x000D_
<option> A.B.1 </option>_x000D_
</optgroup>_x000D_
<option> A.2 </option>_x000D_
</optgroup>_x000D_
</select>
_x000D_
Yes it's possible, as long as the datatypes are compatible. If they aren't, use a CONVERT() or CAST()
SELECT firstname + ' ' + lastname AS name FROM customers
This might not directly answer your question but for the sake of those that come with states like the below
state = {
currentstate:[
{
id: 1 ,
firstname: 'zinani',
sex: 'male'
}
]
}
Solution
const new_value = {
id: 2 ,
firstname: 'san',
sex: 'male'
}
Replace the current state with the new value
this.setState({ currentState: [...this.state.currentState, new_array] })
Unfortunately, the height
property in CSS is not as reliable as it should be. Therefore, Javascript will have to be used to set the height style of the element in question to the height of the users viewport. And yes, this can be done without absolute positioning...
<!DOCTYPE html>
<html>
<head>
<title>Test by Josh</title>
<style type="text/css">
* { padding:0; margin:0; }
#test { background:#aaa; height:100%; width:100%; }
</style>
<script type="text/javascript">
window.onload = function() {
var height = getViewportHeight();
alert("This is what it looks like before the Javascript. Click OK to set the height.");
if(height > 0)
document.getElementById("test").style.height = height + "px";
}
function getViewportHeight() {
var h = 0;
if(self.innerHeight)
h = window.innerHeight;
else if(document.documentElement && document.documentElement.clientHeight)
h = document.documentElement.clientHeight;
else if(document.body)
h = document.body.clientHeight;
return h;
}
</script>
</head>
<body>
<div id="test">
<h1>Test</h1>
</div>
</body>
</html>
A different way to handle such cases is to use formControl and subscribe to it's valueChanges
when your component is initialized, which will allow you to use rxjs operators for advanced requirements like performing http requests, apply a debounce until user finish writing a sentence, take last value and omit previous, ...
import {Component, OnInit} from '@angular/core';
import { FormControl } from '@angular/forms';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
@Component({
selector: 'some-selector',
template: `
<input type="text" [formControl]="searchControl" placeholder="search">
`
})
export class SomeComponent implements OnInit {
private searchControl: FormControl;
private debounce: number = 400;
ngOnInit() {
this.searchControl = new FormControl('');
this.searchControl.valueChanges
.pipe(debounceTime(this.debounce), distinctUntilChanged())
.subscribe(query => {
console.log(query);
});
}
}
You're looking for the /Y
switch.
StringBuilder sb = new StringBuilder("abcde");
sb.setCharAt(0, 'b');
sb.setCharAt(1, 'a');
String newString = sb.toString();
Or you can put in the CSS,
<style>
div#img {
background-image: url(“file.png");
color:yellow (this part doesn't matter;
height:100%;
width:100%;
}
</style>
If str
is null, undefined or 0, this code will set it to "hai"
function(nodeBox, str) {
str = str || "hai";
.
.
.
If you also need to pass 0, you can use:
function(nodeBox, str) {
if (typeof str === "undefined" || str === null) {
str = "hai";
}
.
.
.
You need to use cp -t /home/shantanu/tosend
in order to tell it that the argument is the target directory and not a source. You can then change it to -exec ... +
in order to get cp
to copy as many files as possible at once.
In Rails 4.02+ according to the docs there is no method like update_all
with 2 arguments. Instead one can use this code:
# Make sure no null value exist
MyModel.where(date_column: nil).update_all(date_column: Time.now)
# Change the column to not allow null
change_column :my_models, :date_column, :datetime, null: false
On Angular to update a component including its template, there is a straight forward solution to this, having an @Input
property on your ChildComponent and add to your @Component
decorator changeDetection: ChangeDetectionStrategy.OnPush
as follows:
import { ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'master',
templateUrl: templateUrl,
styleUrls:[styleUrl1],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent{
@Input() data: MyData;
}
This will do all the work of check if Input data have changed and re-render the component
To add that using Jquery:
$('#commentForm').submit(function(){ //listen for submit event
$.each(params, function(i,param){
$('<input />').attr('type', 'hidden')
.attr('name', param.name)
.attr('value', param.value)
.appendTo('#commentForm');
});
return true;
});
I had this problem - the other classes within my package were fine, but one class had the error against it. There was nothing wrong with the package declaration.
I fixed it by doing refactor->move
and moved the class to another package temporarily, then refactor->move
back to the original package.
I would suggest using String.format() if you need the value as a String
in your code.
For example, you can use String.format()
in the following way:
float myFloat = 2.001f;
String formattedString = String.format("%.02f", myFloat);
I came upon a similar issue recently and following Fabian's advice actually led me to the solution. Turns out with client certs you have to ensure two things:
The private key is actually being exported as part of the cert.
The application pool identity running the app has access to said private key.
In our case I had to:
The trusted root issue explained in other answers is a valid one, it was just not the issue in our case.
Try this:
var COUNTRY_ID = 'AL';
countries.results =
countries.results.filter(function(el){ return el.id != COUNTRY_ID; });
String[] elements = { "a", "a","a","a" };
for( int i=0; i<elements.length-1; i++)
{
String s1 = elements[i];
String s2 = elements[i+1];
}
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
In angular 1.4 +, in addition to adding the dependency
angular.module('myApp', ['ngRoute'])
,we also need to reference the separate angular-route.js file
<script src="angular.js">
<script src="angular-route.js">
A self join is simply when you join a table with itself. There is no SELF JOIN
keyword, you just write an ordinary join where both tables involved in the join are the same table. One thing to notice is that when you are self joining it is necessary to use an alias for the table otherwise the table name would be ambiguous.
It is useful when you want to correlate pairs of rows from the same table, for example a parent - child relationship. The following query returns the names of all immediate subcategories of the category 'Kitchen'.
SELECT T2.name
FROM category T1
JOIN category T2
ON T2.parent = T1.id
WHERE T1.name = 'Kitchen'
Here's a more concise answer for people that are looking for a quick reference as well as some examples using promises and async/await.
Start with the naive approach (that doesn't work) for a function that calls an asynchronous method (in this case setTimeout
) and returns a message:
function getMessage() {
var outerScopeVar;
setTimeout(function() {
outerScopeVar = 'Hello asynchronous world!';
}, 0);
return outerScopeVar;
}
console.log(getMessage());
undefined
gets logged in this case because getMessage
returns before the setTimeout
callback is called and updates outerScopeVar
.
The two main ways to solve it are using callbacks and promises:
Callbacks
The change here is that getMessage
accepts a callback
parameter that will be called to deliver the results back to the calling code once available.
function getMessage(callback) {
setTimeout(function() {
callback('Hello asynchronous world!');
}, 0);
}
getMessage(function(message) {
console.log(message);
});
Promises provide an alternative which is more flexible than callbacks because they can be naturally combined to coordinate multiple async operations. A Promises/A+ standard implementation is natively provided in node.js (0.12+) and many current browsers, but is also implemented in libraries like Bluebird and Q.
function getMessage() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Hello asynchronous world!');
}, 0);
});
}
getMessage().then(function(message) {
console.log(message);
});
jQuery Deferreds
jQuery provides functionality that's similar to promises with its Deferreds.
function getMessage() {
var deferred = $.Deferred();
setTimeout(function() {
deferred.resolve('Hello asynchronous world!');
}, 0);
return deferred.promise();
}
getMessage().done(function(message) {
console.log(message);
});
async/await
If your JavaScript environment includes support for async
and await
(like Node.js 7.6+), then you can use promises synchronously within async
functions:
function getMessage () {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Hello asynchronous world!');
}, 0);
});
}
async function main() {
let message = await getMessage();
console.log(message);
}
main();
First declare UIImageView and give it frame
UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake( 10.0f, 15.0f, 40.0f,40.0f )];
[imageView setBackgroundColor: [UIColor clearColor]];
[imageView setImage:[UIImage imageNamed:@"comments_profile_image.png"]];
[self.view addSubview: imageView];
PyDev can do it by either Ctrl+Shift+F if you have code formatter option set to do it, or by during saving:
Eclipse -> Window -> Preferences -> PyDev -> Editor -> Code Style -> Code Formatter:
I use at least these:
(As seen in: BASH FAQ entry #68: "How do I run a command, and have it abort (timeout) after N seconds?")
If you don't mind downloading something, use timeout
(sudo apt-get install timeout
) and use it like: (most Systems have it already installed otherwise use sudo apt-get install coreutils
)
timeout 10 ping www.goooooogle.com
If you don't want to download something, do what timeout does internally:
( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec ping www.goooooogle.com )
In case that you want to do a timeout for longer bash code, use the second option as such:
( cmdpid=$BASHPID;
(sleep 10; kill $cmdpid) \
& while ! ping -w 1 www.goooooogle.com
do
echo crap;
done )
It's treating the string application
as your URL.
This means your shell isn't parsing the command correctly.
My guess is that you copied the string from somewhere, and that when you pasted it, you got some characters that looked like regular quotes, but weren't.
Try retyping the command; you'll only get valid characters from your keyboard. I bet you'll get a much different result from what looks like the same query.
As this is probably a shell problem and not a 'curl' problem (you didn't build cURL yourself from source, did you?), it might be good to mention whether you're on Linux/Windows/etc.
Necromancing.
YES YOU CAN, and this is how.
A secret tip for those migrating large junks chunks of code:
The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:
In public class Startup
add a property
public IConfigurationRoot Configuration { get; }
And then add a singleton IHttpContextAccessor to DI in ConfigureServices.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
Then in Configure
public void Configure(
IApplicationBuilder app
,IHostingEnvironment env
,ILoggerFactory loggerFactory
)
{
add the DI Parameter IServiceProvider svp
, so the method looks like:
public void Configure(
IApplicationBuilder app
,IHostingEnvironment env
,ILoggerFactory loggerFactory
,IServiceProvider svp)
{
Next, create a replacement class for System.Web:
namespace System.Web
{
namespace Hosting
{
public static class HostingEnvironment
{
public static bool m_IsHosted;
static HostingEnvironment()
{
m_IsHosted = false;
}
public static bool IsHosted
{
get
{
return m_IsHosted;
}
}
}
}
public static class HttpContext
{
public static IServiceProvider ServiceProvider;
static HttpContext()
{ }
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
// var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));
// Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
// context.Response.WriteAsync("Test");
return context;
}
}
} // End Class HttpContext
}
Now in Configure, where you added the IServiceProvider svp
, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)
and set HostingEnvironment.IsHosted to true
System.Web.Hosting.HostingEnvironment.m_IsHosted = true;
this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
ServiceProvider = svp;
System.Web.HttpContext.ServiceProvider = svp;
System.Web.Hosting.HostingEnvironment.m_IsHosted = true;
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest
, CookieHttpOnly=false
});
Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in Application_Start
in global.asax.
I stress again, this only works if you actually added
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at github.com/aspnet, and do some testing.
Perhaps a more maintainable method would be adding this helper class
namespace System.Web
{
public static class HttpContext
{
private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;
public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
{
m_httpContextAccessor = httpContextAccessor;
}
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
return m_httpContextAccessor.HttpContext;
}
}
}
}
And then calling HttpContext.Configure in Startup->Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
System.Web.HttpContext.Configure(app.ApplicationServices.
GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>()
);
A few points:
Command-line parameters are
accessible via commandArgs()
, so
see help(commandArgs)
for an
overview.
You can use Rscript.exe
on all platforms, including Windows. It will support commandArgs()
. littler could be ported to Windows but lives right now only on OS X and Linux.
There are two add-on packages on CRAN -- getopt and optparse -- which were both written for command-line parsing.
Edit in Nov 2015: New alternatives have appeared and I wholeheartedly recommend docopt.
HTML5 comes with File API spec, which allows you to create applications that let the user interact with files locally; That means you can load files and render them in the browser without actually having to upload the files. Part of the File API is the FileReader interface which lets web applications asynchronously read the contents of files .
Here's a quick example that makes use of the FileReader
class to read an image as DataURL and renders a thumbnail by setting the src
attribute of an image tag to a data URL:
The html code:
<input type="file" id="files" />
<img id="image" />
The JavaScript code:
document.getElementById("files").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
// get loaded data and render thumbnail.
document.getElementById("image").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
};
Here's a good article on using the File APIs in JavaScript.
The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:
function handleFileSelect(evt) {_x000D_
var files = evt.target.files;_x000D_
_x000D_
// Loop through the FileList and render image files as thumbnails._x000D_
for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
// Only process image files._x000D_
if (!f.type.match('image.*')) {_x000D_
continue;_x000D_
}_x000D_
_x000D_
var reader = new FileReader();_x000D_
_x000D_
// Closure to capture the file information._x000D_
reader.onload = (function(theFile) {_x000D_
return function(e) {_x000D_
// Render thumbnail._x000D_
var span = document.createElement('span');_x000D_
span.innerHTML = _x000D_
[_x000D_
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
e.target.result,_x000D_
'" title="', escape(theFile.name), _x000D_
'"/>'_x000D_
].join('');_x000D_
_x000D_
document.getElementById('list').insertBefore(span, null);_x000D_
};_x000D_
})(f);_x000D_
_x000D_
// Read in the image file as a data URL._x000D_
reader.readAsDataURL(f);_x000D_
}_x000D_
}_x000D_
_x000D_
document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
Don't over complicate it. Just give the link a color using the tags. It will leave a constant color that won't change even if you click it. So in your case just set it to blue. If it is set to a particular color of blue just you want to copy, you can press "print scrn" on your keyboard, paste in paint, and using the color picker(shaped as a dropper) pick the color of the link and view the code in the color settings.
Guess @user3010492 tested it but I used this with fixed cell A5 --> $A$5 and fixed element of G7 --> $G7
=INDIRECT("'"&$A$5&"'!$G7")
Also works nested nicely in other formula if you enclose it in brackets.
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
You can use jQuery load method to get the contents and insert into an element.
Try this:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt");
});
});
You, can also add a call back to execute something once the load process is complete
e.g:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt", function(){
alert("Done Loading");
});
});
});
i use "Versions", quite easy, but not free .
Seems that currently SWIG is best solution for this:
http://www.swig.org/Doc2.0/Go.html
It supports inheritance and even allows to subclass C++ class with Go struct so when overridden methods are called in C++ code, Go code is fired.
Section about C++ in Go FAQ is updated and now mentions SWIG and no longer says "because Go is garbage-collected it will be unwise to do so, at least naively".
Most Git repositories use master
as the main (and default) branch - if you initialize a new Git repo via git init
, it will have master
checked out by default.
However, if you clone a repository, the default branch you have is whatever the remote's HEAD
points to (HEAD
is actually a symbolic ref that points to a branch name). So if the repository you cloned had a HEAD
pointed to, say, foo
, then your clone will just have a foo
branch.
The remote you cloned from might still have a master
branch (you could check with git ls-remote origin master
), but you wouldn't have created a local version of that branch by default, because git clone
only checks out the remote's HEAD
.
Assuming that you made the necessary changes in your php.ini files:
You can resolve the issue by adding the following line in your nginx.conf file found in the following path:
/etc/nginx/nginx.conf
then edit the file using vim text editor as follows:
vi /etc/nginx/nginx.conf
and add client_max_body_size with a large enough value, for example:
client_max_body_size 20MB;
After that make sure you save using :xi
or :wq
And then restart your nginx.
That's it.
Worked for me, hope this helps.
create procedure getDatedifference
(
@startdate datetime,
@enddate datetime
)
as
begin
declare @monthToShow int
declare @dayToShow int
--set @startdate='01/21/1934'
--set @enddate=getdate()
if (DAY(@startdate) > DAY(@enddate))
begin
set @dayToShow=0
if (month(@startdate) > month(@enddate))
begin
set @monthToShow= (12-month(@startdate)+ month(@enddate)-1)
end
else if (month(@startdate) < month(@enddate))
begin
set @monthToShow= ((month(@enddate)-month(@startdate))-1)
end
else
begin
set @monthToShow= 11
end
-- set @monthToShow= convert(int, DATEDIFF(mm,0,DATEADD(dd,DATEDIFF(dd,0,@enddate)- DATEDIFF(dd,0,@startdate),0)))-((convert(int,FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25))*12))-1
if(@monthToShow<0)
begin
set @monthToShow=0
end
declare @amonthbefore integer
set @amonthbefore=Month(@enddate)-1
if(@amonthbefore=0)
begin
set @amonthbefore=12
end
if (@amonthbefore in(1,3,5,7,8,10,12))
begin
set @dayToShow=31-DAY(@startdate)+DAY(@enddate)
end
if (@amonthbefore=2)
begin
IF (YEAR( @enddate ) % 4 = 0 AND YEAR( @enddate ) % 100 != 0) OR YEAR( @enddate ) % 400 = 0
begin
set @dayToShow=29-DAY(@startdate)+DAY(@enddate)
end
else
begin
set @dayToShow=28-DAY(@startdate)+DAY(@enddate)
end
end
if (@amonthbefore in (4,6,9,11))
begin
set @dayToShow=30-DAY(@startdate)+DAY(@enddate)
end
end
else
begin
--set @monthToShow=convert(int, DATEDIFF(mm,0,DATEADD(dd,DATEDIFF(dd,0,@enddate)- DATEDIFF(dd,0,@startdate),0)))-((convert(int,FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25))*12))
if (month(@enddate)< month(@startdate))
begin
set @monthToShow=12+(month(@enddate)-month(@startdate))
end
else
begin
set @monthToShow= (month(@enddate)-month(@startdate))
end
set @dayToShow=DAY(@enddate)-DAY(@startdate)
end
SELECT
FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25) as [yearToShow],
@monthToShow as monthToShow ,@dayToShow as dayToShow ,
convert(varchar,FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25)) +' Year ' + convert(varchar,@monthToShow) +' months '+convert(varchar,@dayToShow)+' days ' as age
return
end
For Swift 3.1, Swift 4 and Swift 5, if you only want change the font size for a label :
let myLabel : UILabel = ...
myLabel.font = myLabel.font.withSize(25)
Using column name worked for me.
sorted_df = df.sort_values(by=['Column_name'], ascending=True)
The "no version information available" means that the library version number is lower on the shared object. For example, if your major.minor.patch number is 7.15.5 on the machine where you build the binary, and the major.minor.patch number is 7.12.1 on the installation machine, ld will print the warning.
You can fix this by compiling with a library (headers and shared objects) that matches the shared object version shipped with your target OS. E.g., if you are going to install to RedHat 3.4.6-9 you don't want to compile on Debian 4.1.1-21. This is one of the reasons that most distributions ship for specific linux distro numbers.
Otherwise, you can statically link. However, you don't want to do this with something like PAM, so you want to actually install a development environment that matches your client's production environment (or at least install and link against the correct library versions.)
Advice you get to rename the .so files (padding them with version numbers,) stems from a time when shared object libraries did not use versioned symbols. So don't expect that playing with the .so.n.n.n naming scheme is going to help (much - it might help if you system has been trashed.)
You last option will be compiling with a library with a different minor version number, using a custom linking script: http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gnu-linker/scripts.html
To do this, you'll need to write a custom script, and you'll need a custom installer that runs ld against your client's shared objects, using the custom script. This requires that your client have gcc or ld on their production system.
I agree with the DialogResult
-Solution as the more straight forward one.
In VB.NET however, typecast is required to get the CloseReason
-Property
Private Sub MyForm_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
Dim eCast As System.Windows.Forms.FormClosingEventArgs
eCast = TryCast(e, System.Windows.Forms.FormClosingEventArgs)
If eCast.CloseReason = Windows.Forms.CloseReason.None Then
MsgBox("Button Pressed")
Else
MsgBox("ALT+F4 or [x] or other reason")
End If
End Sub
Opposite up is children(), but opposite in position is prepend(). Here a very good tutorial.
Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file sendmail.mc.
#Change to your mail config directory:
cd /etc/mail
#Make a auth subdirectory
mkdir auth
chmod 700 auth #maybe not, because I cannot apply cmd "cd auth" if I do so.
#Create a file with your auth information to the smtp server
cd auth
touch client-info
#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"
#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..
#Add the following lines to sendmail.mc. Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl
#run
sudo sendmailconfig
Try
apt-get -d install <packages>
It is documented in man apt-get
.
Just for clarification; the downloaded packages are located in the apt package cache at
/var/cache/apt/archives
Reversed order digit extractor (eg. for 23 will be 3 and 2):
while (number > 0)
{
int digit = number%10;
number /= 10;
//print digit
}
Normal order digit extractor (eg. for 23 will be 2 and 3):
std::stack<int> sd;
while (number > 0)
{
int digit = number%10;
number /= 10;
sd.push(digit);
}
while (!sd.empty())
{
int digit = sd.top();
sd.pop();
//print digit
}
Here is one way to do this without declaring aditional class:
public List<Product> GetProducts(int categoryID)
{
var query = from p in db.Products
where p.CategoryID == categoryID
select new { Name = p.Name };
var products = query.ToList().Select(r => new Product
{
Name = r.Name;
}).ToList();
return products;
}
However, this is only to be used if you want to combine multiple entities in a single entity. The above functionality (simple product to product mapping) is done like this:
public List<Product> GetProducts(int categoryID)
{
var query = from p in db.Products
where p.CategoryID == categoryID
select p;
var products = query.ToList();
return products;
}
Another variation you can try is(expanding @mnel's answer) if you have many temp'x'.
here "n" could be the number of temp variables present
rm(list = c(paste("temp",c(1:n),sep="")))
I just found the "-fae" parameter, which causes Maven to run all tests and not stop on failure.
I feel that MWV (Model View Whatever) or MV* is a more flexible term to describe some of the uniqueness of Angularjs in my opinion. It helped me to understand that it is more than a MVC (Model View Controller) JavaScript framework, but it still uses MVC as it has a Model View, and Controller.
It also can be considered as a MVP (Model View Presenter) pattern. I think of a Presenter as the user-interface business logic in Angularjs for the View. For example by using filters that can format data for display. It's not business logic, but display logic and it reminds me of the MVP pattern I used in GWT.
In addition, it also can be a MVVM (Model View View Model) the View Model part being the two-way binding between the two. Last of all it is MVW as it has other patterns that you can use as well as mentioned by @Steve Chambers.
I agree with the other answers that getting pedantic on these terms can be detrimental, as the point is to understand the concepts from the terms, but by the same token, fully understanding the terms helps one when they are designing their application code, knowing what goes where and why.
This would print the files in those directories line by line.
array=(ww/* ee/* qq/*)
printf "%s\n" "${array[@]}"
Assume a dataframe with 19 rows
index=range(0,19)
index
columns=['A']
test = pd.DataFrame(index=index, columns=columns)
Keeping Column A as a constant
test['A']=10
Keeping column b as a variable given by a loop
for x in range(0,19):
test.loc[[x], 'b'] = pd.Series([x], index = [x])
You can replace the first x in pd.Series([x], index = [x])
with any value
You can also try:
create table new_table as
select * from table1
union
select * from table2
Decouple the Java code from the Environment variable providing a more abstract variable reader that you realize with an EnvironmentVariableReader your code to test reads from.
Then in your test you can give an different implementation of the variable reader that provides your test values.
Dependency injection can help in this.
UPDATE table1 t1
SET t1.value =
(select t2.CODE from table2 t2
where t1.value = t2.DESC)
WHERE t1.UPDATETYPE='blah';
If you want to understand AutoResetEvent and ManualResetEvent you need to understand not threading but interrupts!
.NET wants to conjure up low-level programming the most distant possible.
An interrupts is something used in low-level programming which equals to a signal that from low became high (or viceversa). When this happens the program interrupt its normal execution and move the execution pointer to the function that handles this event.
The first thing to do when an interrupt happend is to reset its state, becosa the hardware works in this way:
This is the difference between ManualResetEvent and AutoResetEvent.
If a ManualResetEvent happen and I do not reset it, the next time it happens I will not be able to listen it.
I had a similar problem, looking for grep/pattern regex and the "matched pattern found" as output.
At the end I used egrep (same regex on grep -e or -G didn't give me the same result of egrep) with the option -o
so, I think that could be something similar to (I'm NOT a regex Master) :
egrep -o "the*|this{1}|thoroughly{1}" filename
For a sanity check, try creating a new Web Application Project, open the code behind for the Default.aspx page. Add a line in Page_Load to access your connection string.
It should have System.Configuration added as reference by default. You should also see the using statement at the top of your code file already.
My code behind file now looks like this and compiles with no problems.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
}
}
}
This assumes I have a connection string in my web.config with a name equal to "MyConnectionStringName" like so...
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="MyConnectionStringName"
connectionString="Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Yeah, it's elementary I know. But if you don't have any better ideas sometimes it helps to check against something really simple that you know should work.
This might come a little late...
I wrote this KalmanLocationManager for Android, which wraps the two most common location providers, Network and GPS, kalman-filters the data, and delivers updates to a LocationListener
(like the two 'real' providers).
I use it mostly to "interpolate" between readings - to receive updates (position predictions) every 100 millis for instance (instead of the maximum gps rate of one second), which gives me a better frame rate when animating my position.
Actually, it uses three kalman filters, on for each dimension: latitude, longitude and altitude. They're independent, anyway.
This makes the matrix math much easier: instead of using one 6x6 state transition matrix, I use 3 different 2x2 matrices. Actually in the code, I don't use matrices at all. Solved all equations and all values are primitives (double).
The source code is working, and there's a demo activity. Sorry for the lack of javadoc in some places, I'll catch up.
you can do it with _pull
.
_.pull(obj["subTopics"] , {"subTopicId":2, "number":32});
check the reference
To add on to what Alisson said you could check to see if a row is returned.
// Query stuff ...
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$row = $query->row();
return $row->campaign_id;
}
return null; // or whatever value you want to return for no rows found
The jsfiddle link to where i tried out your query http://jsfiddle.net/A8Dnv/1/ its working fine @Imrul as mentioned you are using C# on server side and you dont mind that either: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx
You want to use the stringizing operator:
#define STRING(s) #s
int main()
{
const char * cstr = STRING(abc); //cstr == "abc"
}
Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.
You only need to make sure that the button inputs have type="submit"
as in <input type="submit">
and <button type="submit">
and not type="button"
, which only renders a "dead" button purely for onclick
stuff and all.
E.g.
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" name="button1" value="Button 1" />
<input type="submit" name="button2" value="Button 2" />
<input type="submit" name="button3" value="Button 3" />
</form>
with
@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MyClass myClass = new MyClass();
if (request.getParameter("button1") != null) {
myClass.method1();
} else if (request.getParameter("button2") != null) {
myClass.method2();
} else if (request.getParameter("button3") != null) {
myClass.method3();
} else {
// ???
}
request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
}
}
Alternatively, use <button type="submit">
instead of <input type="submit">
, then you can give them all the same name, but an unique value. The value of the <button>
won't be used as label, you can just specify that yourself as child.
E.g.
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<button type="submit" name="button" value="button1">Button 1</button>
<button type="submit" name="button" value="button2">Button 2</button>
<button type="submit" name="button" value="button3">Button 3</button>
</form>
with
@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MyClass myClass = new MyClass();
String button = request.getParameter("button");
if ("button1".equals(button)) {
myClass.method1();
} else if ("button2".equals(button)) {
myClass.method2();
} else if ("button3".equals(button)) {
myClass.method3();
} else {
// ???
}
request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
}
}
Use JSON.stringify()
and JSON.parse()
as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (e.g. member name three|||bars
).
If you look in the AuthenticatesUsers trait you will see that in the sendLoginResponse method that there is a call made to $this->redirectPath()
. If you look at this method then you will discover that the redirectTo can either be a method or a variable.
This is what I now have in my auth controller.
public function redirectTo() {
$user = Auth::user();
switch(true) {
case $user->isInstructor():
return '/instructor';
case $user->isAdmin():
case $user->isSuperAdmin():
return '/admin';
default:
return '/account';
}
}
In my case, I don't need to set up anything further after installing Anaconda on Ubuntu
When I think of dummy variables I think of using them in the context of OLS regression, and I would do something like this:
import numpy as np
import pandas as pd
import statsmodels.api as sm
my_data = np.array([[5, 'a', 1],
[3, 'b', 3],
[1, 'b', 2],
[3, 'a', 1],
[4, 'b', 2],
[7, 'c', 1],
[7, 'c', 1]])
df = pd.DataFrame(data=my_data, columns=['y', 'dummy', 'x'])
just_dummies = pd.get_dummies(df['dummy'])
step_1 = pd.concat([df, just_dummies], axis=1)
step_1.drop(['dummy', 'c'], inplace=True, axis=1)
# to run the regression we want to get rid of the strings 'a', 'b', 'c' (obviously)
# and we want to get rid of one dummy variable to avoid the dummy variable trap
# arbitrarily chose "c", coefficients on "a" an "b" would show effect of "a" and "b"
# relative to "c"
step_1 = step_1.applymap(np.int)
result = sm.OLS(step_1['y'], sm.add_constant(step_1[['x', 'a', 'b']])).fit()
print result.summary()
Apache Commons collection classes is the solution.
MultiMap multiMapDemo = new MultiValueMap();
multiMapDemo .put("fruit", "Mango");
multiMapDemo .put("fruit", "Orange");
multiMapDemo.put("fruit", "Blueberry");
System.out.println(multiMap.get("fruit"));
// Mango Orange Blueberry
Maven Dependency
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 --
>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
Depending if you only need a couple attributes to be styled inline you can do something like this solution (and saves you from having to install a special package or create an extra element):
https://stackoverflow.com/a/42000085
<span class="something" datacustomattribute="">
Hello
</span>
.something::before {
content: attr(datascustomattribute);
position: absolute;
}
Note that the datacustomattribute
must start with data
and be all lowercase to satisfy React.
Here is what I use.
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
As @Dominic pointed out, throwing an uncaught error is better practice instead of calling process.exit([code]):
process.exitCode = 1;
throw new Error("my module xx condition failed");
You could implement a custom pipe for this that leverages the sort
method of arrays:
import { Pipe } from "angular2/core";
@Pipe({
name: "sort"
})
export class ArraySortPipe {
transform(array: Array<string>, args: string): Array<string> {
array.sort((a: any, b: any) => {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
return array;
}
}
And use then this pipe as described below. Don't forget to specify your pipe into the pipes
attribute of the component:
@Component({
(...)
template: `
<li *ngFor="list | sort"> (...) </li>
`,
pipes: [ ArraySortPipe ]
})
(...)
It's a simple sample for arrays with string values but you can have some advanced sorting processing (based on object attributes in the case of object array, based on sorting parameters, ...).
Here is a plunkr for this: https://plnkr.co/edit/WbzqDDOqN1oAhvqMkQRQ?p=preview.
Hope it helps you, Thierry
It is not a problem with Eclipse. If you are using the Properties class to read and store the properties file, the class will escape all special characters.
When saving properties to a stream or loading them from a stream, the ISO 8859-1 character encoding is used. For characters that cannot be directly represented in this encoding, Unicode escapes are used; however, only a single 'u' character is allowed in an escape sequence. The native2ascii tool can be used to convert property files to and from other character encodings.
Characters less than \u0020 and characters greater than \u007E are written as \uxxxx for the appropriate hexadecimal value xxxx.
In the Options, change the "Restore As" file name to the new database mdf and ldf. It is referencing the source database .mdf and .ldf files.
Linux :
In command line
mysql -u username -p databasename < path/example.sql
put your table in example.sql
Import / Export for single table:
Export table schema
mysqldump -u username -p databasename tableName > path/example.sql
This will create a file named example.sql
at the path mentioned and write the create table
sql command to create table tableName
.
Import data into table
mysql -u username -p databasename < path/example.sql
This command needs an sql file containing data in form of insert
statements for table tableName
. All the insert
statements will be executed and the data will be loaded.
You're misinterpreting what the onchange event does when applied to a textarea. It won't fire until it loses focus or you hit enter. Why not fire the function from an onchange on the select that fills in the text area?
Check out here for more on the onchange event: w3schools
Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit.
In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size.
You can find the official list here: http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx
All the platform-dependent types that changed with the transition from 32-bit to 64-bit end with _PTR (DWORD_PTR will be 32-bit on 32-bit Windows and 64-bit on 64-bit Windows).
Tables are iffy (at least, in IE) when it comes to fixing heights and not wrapping text. I think you'll find that the only solution is to put the text inside a div
element, like so:
td.container > div {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
overflow:hidden;_x000D_
}_x000D_
td.container {_x000D_
height: 20px;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="container">_x000D_
<div>This is a long line of text designed not to wrap _x000D_
when the container becomes too small.</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
This way, the div
's height is that of the containing cell and the text cannot grow the div
, keeping the cell/row the same height no matter what the window size is.
Since the OP does not ask for a specific DB, better use a standard compliant statement.
Only MERGE
is in SQL standard for deleting (or updating) rows while joining something on target table.
merge table1 t1
using (
select t2.ID
from table2 t2
) as d
on t1.ID = d.ID
when matched then delete;
MERGE
has a stricter semantic, protecting from some error cases which may go unnoticed with DELETE ... FROM
. It enforces 'uniqueness' of match : if many rows in the source (the statement inside using
) match the same row in the target, the merge must be canceled and an error must be raised by the SQL engine.
I would go with Lev, but it's worth pointing out that if you end up with more complex searches that using re.finditer may be worth bearing in mind (but re's often cause more trouble than worth - but sometimes handy to know)
test = "ooottat"
[ (i.start(), i.end()) for i in re.finditer('o', test)]
# [(0, 1), (1, 2), (2, 3)]
[ (i.start(), i.end()) for i in re.finditer('o+', test)]
# [(0, 3)]
After fetching a zillion times still added remotes didn't show up, although the blobs were in the pool. Turns out the --tags option shouldn't be given to git remote add
for whatever reason. You can manually remove it from the .git/config to make git fetch create the refs.
GROUP BY meetingID
HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2
This solution is basically pushing
List<Object>
data to Excel, It uses DataTable to achieve this, I implemented an extension method, so basically there are two things needed. 1. An Extension Method.
public static class ReportHelper
{
public static string ToExcel<T>(this IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
{
//table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
if (prop.Attributes[typeof(FGMS.Entity.Extensions.ReportHeaderAttribute)] != null)
{
table.Columns.Add(GetColumnHeader(prop), Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
}
//So it seems like when there is only one row of data the headers do not appear
//so adding a dummy blank row which fixed the issues
//Add a blank Row - Issue # 1471
DataRow blankRow = table.NewRow();
table.Rows.Add(blankRow);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
//row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
if (prop.Attributes[typeof(FGMS.Entity.Extensions.ReportHeaderAttribute)] != null)
{
row[GetColumnHeader(prop)] = prop.GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(row);
}
table.TableName = "Results";
var filePath = System.IO.Path.GetTempPath() + "\\" + System.Guid.NewGuid().ToString() + ".xls";
table.WriteXml(filePath);
return filePath;
}
private static string GetColumnHeader(PropertyDescriptor prop)
{
return ((FGMS.Entity.Extensions.ReportHeaderAttribute)(prop.Attributes[typeof(FGMS.Entity.Extensions.ReportHeaderAttribute)])).ReportHeaderText;
}
}
- Decorate your DTO classes with the Attribute
[ReportHeaderAttribute("Column Name")]
public class UserDTO
{
public int Id { get; set; }
public int SourceId { get; set; }
public string SourceName { get; set; }
[ReportHeaderAttribute("User Type")]
public string UsereType { get; set; }
[ReportHeaderAttribute("Address")]
public string Address{ get; set; }
[ReportHeaderAttribute("Age")]
public int Age{ get; set; }
public bool IsActive { get; set; }
[ReportHeaderAttribute("Active")]
public string IsActiveString
{
get
{
return IsActive ? "Yes" : "No";
}
}}
Everything that needs to be a column in the Excel has to be decorated with [ReportHeaderAttribute("Column Name")]
Then Simply
Var userList = Service.GetUsers() //Returns List of UserDTO;
var excelFilePath = userList.ToExcel();
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(excelFilePath, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/vnd.ms-excel");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "UserList.xls" };
return result;
downloading the email via the POP3 protocol is the easy part of the task. The protocol is quite simple and the only hard part could be advanced authentication methods if you don't want to send a clear text password over the network (and cannot use the SSL encrypted communication channel). See RFC 1939: Post Office Protocol - Version 3 and RFC 1734: POP3 AUTHentication command for details.
The hard part comes when you have to parse the received email, which means parsing MIME format in most cases. You can write quick&dirty MIME parser in a few hours or days and it will handle 95+% of all incoming messages. Improving the parser so it can parse almost any email means:
Debugging a robust MIME parser takes months of work. I know, because I was watching my friend writing one such parser for the component mentioned below and was writing a few unit tests for it too ;-)
Back to the original question.
Following code taken from our POP3 Tutorial page and links would help you:
//
// create client, connect and log in
Pop3 client = new Pop3();
client.Connect("pop3.example.org");
client.Login("username", "password");
// get message list
Pop3MessageCollection list = client.GetMessageList();
if (list.Count == 0)
{
Console.WriteLine("There are no messages in the mailbox.");
}
else
{
// download the first message
MailMessage message = client.GetMailMessage(list[0].SequenceNumber);
...
}
client.Disconnect();
This works for me
FOR /F "tokens=3" %%a in ('robocopy ^|find "Started"') DO SET TODAY=%%a
autoSize for column width set as bellow. It works for me.
$spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
Create custom directive
masterApp.directive('ngRenderCallback', function() {
return {
restrict: "A",
link: function ($scope, element, attrs) {
setTimeout(function(){
$scope[attrs.ngEl] = element[0];
$scope.$eval(attrs.ngRenderCallback);
}, 30);
}
}
});
code for html template
<div ng-render-callback="fnRenderCarousel('carouselA')" ng-el="carouselA"></div>
function in controller
$scope.fnRenderCarousel = function(elName){
$($scope[elName]).carousel();
}
If you've got ther JSON data coming in as a string (e.g. '[{"id":1,"name":"Charles"},{"id":8,"name":"John"},{"id":13,"name":"Sally"}]')
Then I'd use JSON.net and use Linq to JSON to get the values out...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request["items"] != null)
{
var items = Request["items"].ToString(); // Get the JSON string
JArray o = JArray.Parse(items); // It is an array so parse into a JArray
var a = o.SelectToken("[0].name").ToString(); // Get the name value of the 1st object in the array
// a == "Charles"
}
}
}
The ASPX code will look something like this:
<asp:RadioButtonList ID="rblist1" runat="server">
<asp:ListItem Text ="Item1" Value="1" />
<asp:ListItem Text ="Item2" Value="2" />
<asp:ListItem Text ="Item3" Value="3" />
<asp:ListItem Text ="Item4" Value="4" />
</asp:RadioButtonList>
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />
And the code behind:
protected void Button1_Click(object sender, EventArgs e)
{
string selectedValue = rblist1.SelectedValue;
Response.Write(selectedValue);
}