1) Right Click on **Solution Explorer**
2) Go to the **Properties**
3) Expand **Common Properties**
4) Select **Start Up Project**
5) click the radio button (**Single Start_up Project**)
6) select your Project name
7) Then Debug Your project
Try this simple program:
public class HashMapGetKey {
public static void main(String args[]) {
// create hash map
HashMap map = new HashMap();
// populate hash map
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
// get keyset value from map
Set keyset=map.keySet();
// check key set values
System.out.println("Key set values are: " + keyset);
}
}
If you're looking for a more reliable regex, check out RegexLib. Here's the page you'd probably be interested in:
http://regexlib.com/Search.aspx?k=url
As for the error messages showing while the person is still typing, change the event from keydown
to blur
and then it will only check once the person moves to the next element.
First is you have to understand the difference between MyISAM
and InnoDB
Engines. And this is clearly stated on this link. You can use this sql statement if you want to convert InnoDB to MyISAM:
ALTER TABLE t1 ENGINE=MyISAM;
When your first argument is null, they're basically the same except that the null coalescing won't output an E_NOTICE
when you have an undefined variable. The PHP 7.0 migration docs has this to say:
The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
Here's some example code to demonstrate this:
<?php
$a = null;
print $a ?? 'b'; // b
print "\n";
print $a ?: 'b'; // b
print "\n";
print $c ?? 'a'; // a
print "\n";
print $c ?: 'a'; // Notice: Undefined variable: c in /in/apAIb on line 14
print "\n";
$b = array('a' => null);
print $b['a'] ?? 'd'; // d
print "\n";
print $b['a'] ?: 'd'; // d
print "\n";
print $b['c'] ?? 'e'; // e
print "\n";
print $b['c'] ?: 'e'; // Notice: Undefined index: c in /in/apAIb on line 33
print "\n";
The lines that have the notice are the ones where I'm using the shorthand ternary operator as opposed to the null coalescing operator. However, even with the notice, PHP will give the same response back.
Execute the code: https://3v4l.org/McavC
Of course, this is always assuming the first argument is null
. Once it's no longer null, then you end up with differences in that the ??
operator would always return the first argument while the ?:
shorthand would only if the first argument was truthy, and that relies on how PHP would type-cast things to a boolean.
So:
$a = false ?? 'f'; // false
$b = false ?: 'g'; // 'g'
would then have $a
be equal to false
and $b
equal to 'g'
.
This is my preferred solution:
var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty
Best practice ever
Create Interface named with PreferenceManager:
// Interface to save values in shared preferences and also for retrieve values from shared preferences
public interface PreferenceManager {
SharedPreferences getPreferences();
Editor editPreferences();
void setString(String key, String value);
String getString(String key);
void setBoolean(String key, boolean value);
boolean getBoolean(String key);
void setInteger(String key, int value);
int getInteger(String key);
void setFloat(String key, float value);
float getFloat(String key);
}
How to use with Activity / Fragment:
public class HomeActivity extends AppCompatActivity implements PreferenceManager{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout_activity_home);
}
@Override
public SharedPreferences getPreferences(){
return getSharedPreferences("SP_TITLE", Context.MODE_PRIVATE);
}
@Override
public SharedPreferences.Editor editPreferences(){
return getPreferences().edit();
}
@Override
public void setString(String key, String value) {
editPreferences().putString(key, value).commit();
}
@Override
public String getString(String key) {
return getPreferences().getString(key, "");
}
@Override
public void setBoolean(String key, boolean value) {
editPreferences().putBoolean(key, value).commit();
}
@Override
public boolean getBoolean(String key) {
return getPreferences().getBoolean(key, false);
}
@Override
public void setInteger(String key, int value) {
editPreferences().putInt(key, value).commit();
}
@Override
public int getInteger(String key) {
return getPreferences().getInt(key, 0);
}
@Override
public void setFloat(String key, float value) {
editPreferences().putFloat(key, value).commit();
}
@Override
public float getFloat(String key) {
return getPreferences().getFloat(key, 0);
}
}
Note: Replace your key of SharedPreference with SP_TITLE.
Examples:
Store string in shareperence:
setString("my_key", "my_value");
Get string from shareperence:
String strValue = getString("my_key");
Hope this will help you.
I think this is similar to what the last podcast discussed. The "Be liberal in what you accept" means that extra work had to be put into the Javascript parser to fix cases where semicolons were left out. Now we have a boatload of pages out there floating around with bad syntax, that might break one day in the future when some browser decides to be a little more stringent on what it accepts. This type of rule should also apply to HTML and CSS. You can write broken HTML and CSS, but don't be surprise when you get weird and hard to debug behaviors when some browser doesn't properly interpret your incorrect code.
Basically the scope of workspace(s) is divided in two points.
First point (and primary) is the eclipse it self and is related with the settings and metadata configurations (plugin ctr). Each time you create a project, eclipse collects all the configurations and stores them on that workspace and if somehow in the same workspace a conflicting project is present you might loose some functionality or even stability of eclipse it self.
And second (secondary) the point of development strategy one can adopt. Once the primary scope is met (and mastered) and there's need for further adjustments regarding project relations (as libraries, perspectives ctr) then initiate separate workspace(s) could be appropriate based on development habits or possible language/frameworks "behaviors". DLTK for examples is a beast that should be contained in a separate cage. Lots of complains at forums for it stopped working (properly or not at all) and suggested solution was to clean the settings of the equivalent plugin from the current workspace.
Personally, I found myself lean more to language distinction when it comes to separate workspaces which is relevant to known issues that comes with the current state of the plugins are used. Preferably I keep them in the minimum numbers as this is leads to less frustration when the projects are become... plenty and version control is not the only version you keep your projects. Finally, loading speed and performance is an issue that might come up if lots of (unnecessary) plugins are loaded due to presents of irrelevant projects. Bottom line; there is no one solution to every one, no master blue print that solves the issue. It's something that grows with experience, Less is more though!
According to the documentation:
Thrown to indicate that the code has attempted to cast an Object
to a subclass
of which it is not an instance. For example, the following code generates a ClassCastException
:
Object x = new Integer(0);
System.out.println((String)x);
well, why don't you (get rid of sidebar and) squeeze the table so it is without show/hide effect? It looks odd to me now. The table is too robust.
Otherwise I think scunliffe's suggestion should do it. Or if you wish, you can just set the exact width of table and set either percentage or pixel width for table cells.
As per the documentation: FROM (Transact-SQL):
<join_type> ::=
[ { INNER | { { LEFT | RIGHT | FULL } [ OUTER ] } } [ <join_hint> ] ]
JOIN
The keyword OUTER
is marked as optional (enclosed in square brackets). In this specific case, whether you specify OUTER
or not makes no difference. Note that while the other elements of the join clause is also marked as optional, leaving them out will make a difference.
For instance, the entire type-part of the JOIN
clause is optional, in which case the default is INNER
if you just specify JOIN
. In other words, this is legal:
SELECT *
FROM A JOIN B ON A.X = B.Y
Here's a list of equivalent syntaxes:
A LEFT JOIN B A LEFT OUTER JOIN B
A RIGHT JOIN B A RIGHT OUTER JOIN B
A FULL JOIN B A FULL OUTER JOIN B
A INNER JOIN B A JOIN B
Also take a look at the answer I left on this other SO question: SQL left join vs multiple tables on FROM line?.
Setting .value
to the value of one of the options works on all vaguely-current browsers. On very old browsers, you used to have to set the selectedIndex
:
document.getElementById("select").selectedIndex = 0;
If neither that nor your original code is working, I wonder if you might be using IE and have something else on the page creating something called "select"? (Either as a name
or as a global variable?) Because some versions of IE have a problem where they conflate namespaces. Try changing the select's id
to "fluglehorn" and if that works, you know that's the problem.
Swift 4
let dateFormatter : DateFormatter = DateFormatter()
// dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.dateFormat = "yyyy-MMM-dd HH:mm:ss"
let date = Date()
let dateString = dateFormatter.string(from: date)
let interval = date.timeIntervalSince1970
OUTPUT
2018-May-01 10:41:31
Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.
import UIKit
// MARK: Local Constants
private let changeSegueId = "MasterToChange"
private let bookSegueId = "MasterToBook"
The steps are as follows :
WAMP\bin\php\(your version of php)\
php.ini
extension=php_curl.dll
WAMP\bin\Apache\(your version of apache)\bin\
php.ini
extension=php_curl.dll
You can find some resources related to developing web services client using Apache axis2 here.
http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html
Below posts gives good explanations about developing web services using Apache axis2.
http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/
You can't use Bootstrap Jquery based Javascript components in React app, as anything that tries to manipulate DOM outside React is considered bad practice. Here you can read more info about it.
1) Recommended. You can include raw CSS files of Bootstrap as the other answers specify.
2) Take a look at react-bootstrap library. It is exclusively written for React.
3) For Bootstrap 4 there is reactstrap
These days I generally avoid Bootstrap libraries which provide ready to use components (above-mentioned react-bootstrap or reactstrap and so on). As you are becoming dependent on the props they take (you can't add custom behavior inside them) and you lose control over DOM that these components produce.
So either use only Bootstrap CSS or leave Bootstrap out. A general rule of thumb is: If are not sure whether you need it, you don't need it. I've seen a lot of applications which include Bootstrap, but using the only small amount of CSS of it and sometimes the most of this CSS is overridden by custom styles.
A classic "or" would be |
. For example, ab|de
would match either side of the expression.
However, for something like your case you might want to use the ?
quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:
\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+
This pattern will match:
\d+
: One or more numbers.\s+
: One or more whitespaces.[A-Z\s]+
: One or more uppercase characters or space characters\s+
: One or more whitespaces.[A-Z][A-Za-z\s]+
: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.If you'd like a more static check, e.g. indeed only match ABC
and A ABC
, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):
\d (?:ABC|A ABC) Street
Or another alternative using a quantifier:
\d (?:A )?ABC Street
I got by doing several tests until one worked, so: res/color/button_dark_text.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#000000" /> <!-- pressed -->
<item android:state_focused="true"
android:color="#000000" /> <!-- focused -->
<item android:color="#FFFFFF" /> <!-- default -->
</selector>
res/layout/view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EXIT"
android:textColor="@color/button_dark_text" />
</LinearLayout>
Just change it to
var appointmentNoShow = from a in appointments
from p in properties
from c in clients
where a.Id == p.OID &&
(a.Start.Date >= startDate.Date && a.Start.Date <= endDate)
Found on dotnet-snippets.de
With reflection this works and sets the real RootFolder!
using System;
using System.Reflection;
using System.Windows.Forms;
namespace YourNamespace
{
public class RootFolderBrowserDialog
{
#region Public Properties
/// <summary>
/// The description of the dialog.
/// </summary>
public string Description { get; set; } = "Chose folder...";
/// <summary>
/// The ROOT path!
/// </summary>
public string RootPath { get; set; } = "";
/// <summary>
/// The SelectedPath. Here is no initialization possible.
/// </summary>
public string SelectedPath { get; private set; } = "";
#endregion Public Properties
#region Public Methods
/// <summary>
/// Shows the dialog...
/// </summary>
/// <returns>OK, if the user selected a folder or Cancel, if no folder is selected.</returns>
public DialogResult ShowDialog()
{
var shellType = Type.GetTypeFromProgID("Shell.Application");
var shell = Activator.CreateInstance(shellType);
var folder = shellType.InvokeMember(
"BrowseForFolder", BindingFlags.InvokeMethod, null,
shell, new object[] { 0, Description, 0, RootPath, });
if (folder is null)
{
return DialogResult.Cancel;
}
else
{
var folderSelf = folder.GetType().InvokeMember(
"Self", BindingFlags.GetProperty, null,
folder, null);
SelectedPath = folderSelf.GetType().InvokeMember(
"Path", BindingFlags.GetProperty, null,
folderSelf, null) as string;
// maybe ensure that SelectedPath is set
return DialogResult.OK;
}
}
#endregion Public Methods
}
}
You can use an IF to test:
check:
@[ "${var}" ] || ( echo ">> var is not set"; exit 1 )
Result:
$ make check
>> var is not set
Makefile:2: recipe for target 'check' failed
make: *** [check] Error 1
Regexes can also limit the number of characters.
r = re.compile("^[a-z]{1,15}$")
gives you a regex that only matches if the input is entirely lowercase ASCII letters and 1 to 15 characters long.
python -c 'import os; print (os.path.getsize("... filename ..."))'
portable, all flavours of python, avoids variation in stat dialects
The simplest is to call stop propagation on an event handler. $event
works the same in Angular 2, and contains the ongoing event (by it a mouse click, mouse event, etc.):
(click)="onEvent($event)"
on the event handler, we can there stop the propagation:
onEvent(event) {
event.stopPropagation();
}
cat names.txt|while read line; do
echo "$line";
done
The closest you can get to an asynchronous constructor is by waiting for it to finish executing if it hasn't already in all of its methods:
class SomeClass {
constructor() {
this.asyncConstructor = (async () => {
// Perform asynchronous operations here
})()
}
async someMethod() {
await this.asyncConstructor
// Perform normal logic here
}
}
Suppose your dataframe is as follows:
>>> df
A B C ID
0 1 3 2 p
1 4 3 2 q
2 4 0 9 r
set_index
to set ID
columns as the dataframe index. df.set_index("ID", drop=True, inplace=True)
orient=index
parameter to have the index as dictionary keys. dictionary = df.to_dict(orient="index")
The results will be as follows:
>>> dictionary
{'q': {'A': 4, 'B': 3, 'D': 2}, 'p': {'A': 1, 'B': 3, 'D': 2}, 'r': {'A': 4, 'B': 0, 'D': 9}}
column_order= ["A", "B", "C"] # Determine your preferred order of columns
d = {} # Initialize the new dictionary as an empty dictionary
for k in dictionary:
d[k] = [dictionary[k][column_name] for column_name in column_order]
Here is how you get the execution path of the application:
var path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
MSDN has a full reference on how to determine the Executing Application's Path.
Note that the value in path
will be in the form of file:\c:\path\to\bin\folder
, so before using the path you may need to strip the file:\
off the front. E.g.:
path = path.Substring(6);
var ind=0;
foreach(string s in sList){
if(s.equals("ok")){
return true;
}
ind++;
}
if (ind==sList.length){
return false;
}
Did you took a look at this? http://developer.yahoo.com/yui/history/
Change <?php echo $proxy ?>
to ' . $proxy . '
.
You use <?php
when you're outputting HTML by leaving PHP mode with ?>
. When you using echo
, you have to use concatenation, or wrap your string in double quotes and use interpolation.
Display errors could be turned off in the php.ini
or your Apache configuration file.
You can turn it on in the script:
error_reporting(E_ALL);
ini_set('display_errors', '1');
You should see the same messages in the PHP error log.
With a regular expression and the function gsub()
:
group <- c("12357e", "12575e", "197e18", "e18947")
group
[1] "12357e" "12575e" "197e18" "e18947"
gsub("e", "", group)
[1] "12357" "12575" "19718" "18947"
What gsub
does here is to replace each occurrence of "e"
with an empty string ""
.
See ?regexp
or gsub
for more help.
See this table.
A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.
A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.
do a :
git branch
if git show you something like :
* (no branch)
master
Dbranch
You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with
git checkout master
Now you should be able to delete the Dbranch.
Here's a Swift 4 UIView extension based on the answer from @Dima.
extension UIView {
func snapshotImage() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
drawHierarchy(in: bounds, afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
If I understand correctly, you want flex-2-child to fill the height and width of its parent, so that the red area is fully covered by the green?
If so, you just need to set flex-2 to use Flexbox:
.flex-2 {
display: flex;
}
Then tell flex-2-child to become flexible:
.flex-2-child {
flex: 1;
}
See http://jsfiddle.net/2ZDuE/10/
The reason is that flex-2-child is not a Flexbox item, but its parent is.
I've ended up here looking for "how to mock a function based on input arguments" and I finally solved this creating a simple aux function:
def mock_responses(responses, default_response=None):
return lambda input: responses[input] if input in responses else default_response
Now:
my_mock.foo.side_effect = mock_responses(
{
'x': 42,
'y': [1,2,3]
})
my_mock.goo.side_effect = mock_responses(
{
'hello': 'world'
},
default_response='hi')
...
my_mock.foo('x') # => 42
my_mock.foo('y') # => [1,2,3]
my_mock.foo('unknown') # => None
my_mock.goo('hello') # => 'world'
my_mock.goo('ey') # => 'hi'
Hope this will help someone!
Export a certificate from a keystore:
keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks
According to highest two answers, I have a little fix:
<span class="btn btn-info btn-minier popover-info" data-rel="popover"
data-placement="bottom" data-html="true" title=""
data-content="popover-content"
data-original-title="popover-title">
<i class="ace-icon fa fa-info smaller-100"></i>
</span>
$('[data-rel=popover]').popover({html: true});
$(document).on("shown.bs.popover", '[data-rel=popover]', function () {
$('[data-rel="popover"][popover-show="1"]').popover('hide');
$(this).attr('popover-show', '1');
});
$(document).on("hidden.bs.popover", '[data-rel=popover]', function () {
if ($(this).attr('popover-show') === '0') {
// My important fix: using bootstrap 3.4.1, if hide popover by .popover('hide') and click to show, popover internal treat it is already shown and dispatch hidden event immediately without popover anything.
$(this).popover('toggle');
} else {
$(this).attr('popover-show', '0');
}
});
$('html').on('click', function (e) {
if (typeof $(e.target).data('original-title') == 'undefined'
&& typeof $(e.target).parent().data('original-title') == 'undefined'
&& !$(e.target).parents().is('.popover.in')) {
$('[data-rel="popover"][popover-show="1"]').popover('hide');
}
});
EDIT based on comments:
If you have line breaks in your result set and want to remove them, make your query this way:
SELECT
REPLACE(REPLACE(YourColumn1,CHAR(13),' '),CHAR(10),' ')
,REPLACE(REPLACE(YourColumn2,CHAR(13),' '),CHAR(10),' ')
,REPLACE(REPLACE(YourColumn3,CHAR(13),' '),CHAR(10),' ')
--^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
--only add the above code to strings that are having line breaks, not to numbers or dates
FROM YourTable...
WHERE ...
This will replace all the line breaks with a space character.
Run this to "get" all characters permitted in a char() and varchar():
;WITH AllNumbers AS
(
SELECT 1 AS Number
UNION ALL
SELECT Number+1
FROM AllNumbers
WHERE Number+1<256
)
SELECT Number AS ASCII_Value,CHAR(Number) AS ASCII_Char FROM AllNumbers
OPTION (MAXRECURSION 256)
OUTPUT:
ASCII_Value ASCII_Char
----------- ----------
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 !
34 "
35 #
36 $
37 %
38 &
39 '
40 (
41 )
42 *
43 +
44 ,
45 -
46 .
47 /
48 0
49 1
50 2
51 3
52 4
53 5
54 6
55 7
56 8
57 9
58 :
59 ;
60 <
61 =
62 >
63 ?
64 @
65 A
66 B
67 C
68 D
69 E
70 F
71 G
72 H
73 I
74 J
75 K
76 L
77 M
78 N
79 O
80 P
81 Q
82 R
83 S
84 T
85 U
86 V
87 W
88 X
89 Y
90 Z
91 [
92 \
93 ]
94 ^
95 _
96 `
97 a
98 b
99 c
100 d
101 e
102 f
103 g
104 h
105 i
106 j
107 k
108 l
109 m
110 n
111 o
112 p
113 q
114 r
115 s
116 t
117 u
118 v
119 w
120 x
121 y
122 z
123 {
124 |
125 }
126 ~
127
128 €
129
130 ‚
131 ƒ
132 „
133 …
134 †
135 ‡
136 ˆ
137 ‰
138 Š
139 ‹
140 Œ
141
142 Ž
143
144
145 ‘
146 ’
147 “
148 ”
149 •
150 –
151 —
152 ˜
153 ™
154 š
155 ›
156 œ
157
158 ž
159 Ÿ
160
161 ¡
162 ¢
163 £
164 ¤
165 ¥
166 ¦
167 §
168 ¨
169 ©
170 ª
171 «
172 ¬
173
174 ®
175 ¯
176 °
177 ±
178 ²
179 ³
180 ´
181 µ
182 ¶
183 ·
184 ¸
185 ¹
186 º
187 »
188 ¼
189 ½
190 ¾
191 ¿
192 À
193 Á
194 Â
195 Ã
196 Ä
197 Å
198 Æ
199 Ç
200 È
201 É
202 Ê
203 Ë
204 Ì
205 Í
206 Î
207 Ï
208 Ð
209 Ñ
210 Ò
211 Ó
212 Ô
213 Õ
214 Ö
215 ×
216 Ø
217 Ù
218 Ú
219 Û
220 Ü
221 Ý
222 Þ
223 ß
224 à
225 á
226 â
227 ã
228 ä
229 å
230 æ
231 ç
232 è
233 é
234 ê
235 ë
236 ì
237 í
238 î
239 ï
240 ð
241 ñ
242 ò
243 ó
244 ô
245 õ
246 ö
247 ÷
248 ø
249 ù
250 ú
251 û
252 ü
253 ý
254 þ
255 ÿ
(255 row(s) affected)
You should use single-quotes for string delimiters. The single-quote is the standard SQL string delimiter, and double-quotes are identifier delimiters (so you can use special words or characters in the names of tables or columns).
In MySQL, double-quotes work (nonstandardly) as a string delimiter by default (unless you set ANSI
SQL mode). If you ever use another brand of SQL database, you'll benefit from getting into the habit of using quotes standardly.
Another handy benefit of using single-quotes is that the literal double-quote characters within your string don't need to be escaped:
select * from tablename where fields like '%string "hi" %';
One thing to note:
I have had issues with websockets and corporate firewalls. (Using HTTPS helps but not always.)
See https://github.com/LearnBoost/socket.io/wiki/Socket.IO-and-firewall-software https://github.com/sockjs/sockjs-client/issues/94
I assume there aren't as many issues with Server-Sent Events. But I don't know.
That said, WebSockets are tons of fun. I have a little web game that uses websockets (via Socket.IO) (http://minibman.com)
Thanks Rafe, this takes into account the issues your replyers posted.
public static double GetMedian(double[] sourceNumbers) {
//Framework 2.0 version of this method. there is an easier way in F4
if (sourceNumbers == null || sourceNumbers.Length == 0)
throw new System.Exception("Median of empty array not defined.");
//make sure the list is sorted, but use a new array
double[] sortedPNumbers = (double[])sourceNumbers.Clone();
Array.Sort(sortedPNumbers);
//get the median
int size = sortedPNumbers.Length;
int mid = size / 2;
double median = (size % 2 != 0) ? (double)sortedPNumbers[mid] : ((double)sortedPNumbers[mid] + (double)sortedPNumbers[mid - 1]) / 2;
return median;
}
UINavigationItem* item = [[UINavigationItem alloc] initWithTitle:@"title text"];
...
[bar pushNavigationItem:item animated:YES];
[item release];
This code worked.
docker ps -a
This command saves modified container state into a new image user/test_image
docker commit $CONTAINER_ID user/test_image
docker run -ti --entrypoint=sh user/test_image
Entrypoint argument description: https://docs.docker.com/engine/reference/run/#/entrypoint-default-command-to-execute-at-runtime
Steps above just start a stopped container with the same filesystem state. That is great for a quick investigation. But environment variables, network configuration, attached volumes and other staff is not inherited, you should specify all these arguments explicitly.
Steps to start a stopped container have been borrowed from here: (last comment) https://github.com/docker/docker/issues/18078
class TeacherSchedule < ActiveRecord::Base
validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end
http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of
This should answer Greg's question.
If you're looking for a space, that would be " "
(one space).
If you're looking for one or more, it's " *"
(that's two spaces and an asterisk) or " +"
(one space and a plus).
If you're looking for common spacing, use "[ X]"
or "[ X][ X]*"
or "[ X]+"
where X
is the physical tab character (and each is preceded by a single space in all those examples).
These will work in every* regex engine I've ever seen (some of which don't even have the one-or-more "+"
character, ugh).
If you know you'll be using one of the more modern regex engines, "\s"
and its variations are the way to go. In addition, I believe word boundaries match start and end of lines as well, important when you're looking for words that may appear without preceding or following spaces.
For PHP specifically, this page may help.
From your edit, it appears you want to remove all non valid characters The start of this is (note the space inside the regex):
$newtag = preg_replace ("/[^a-zA-Z0-9 ]/", "", $tag);
# ^ space here
If you also want trickery to ensure there's only one space between each word and none at the start or end, that's a little more complicated (and probably another question) but the basic idea would be:
$newtag = preg_replace ("/ +/", " ", $tag); # convert all multispaces to space
$newtag = preg_replace ("/^ /", "", $tag); # remove space from start
$newtag = preg_replace ("/ $/", "", $tag); # and end
Try this. Make a new class
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/").permitAll();
}
}
Basically this tells Spring to allow access to every url. @Configuration
tells spring it's a configuration class
You can make your pattern case insensitive by doing:
Pattern p = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);
Try to use r.hasNext() instead of r.hasNextLine():
while(r.hasNext()) {
scan = r.next();
Like this:
DateTime.Now.ToString("MMMM yyyy")
For more information, see DateTime Format Strings.
I took Michael Berkowski's answer a step (or two) farther and created a more flexible function allowing any lookup field and any target field. For fun I threw splat (*) capability in there incase someone might want to do a replace all. jQuery is NOT needed. checkAllRows allows the option to break from the search on found for performance or the previously mentioned replace all.
function setVal(update) {
/* Included to show an option if you care to use jQuery
var defaults = { jsonRS: null, lookupField: null, lookupKey: null,
targetField: null, targetData: null, checkAllRows: false };
//update = $.extend({}, defaults, update); */
for (var i = 0; i < update.jsonRS.length; i++) {
if (update.jsonRS[i][update.lookupField] === update.lookupKey || update.lookupKey === '*') {
update.jsonRS[i][update.targetField] = update.targetData;
if (!update.checkAllRows) { return; }
}
}
}
var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Username':'Albert','FatherName':'Einstein'}]
With your data you would use like:
var update = {
jsonRS: jsonObj,
lookupField: "Id",
lookupKey: 2,
targetField: "Username",
targetData: "Thomas",
checkAllRows: false
};
setVal(update);
And Bob's your Uncle. :) [Works great]
The link you gave does actually describe the differences, but it's buried at the bottom of the page:
http://www.cplusplus.com/reference/cstdio/fopen/
Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.
The conversion could be to normalize \r\n
to \n
(or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.
(Can't comment yet with enough reputation , let me add a sidenote)
Just in case your output need to be fixed length of 3-digit , i.e. for number run up to 1000 or more (reserved fixed length), don't forget to add mod 1000 on it .
yourNumber=1001;
yourString= yourNumber.ToString("D3"); // "1001"
yourString= (yourNumber%1000).ToString("D3"); // "001" truncated to 3-digit as expected
Trail sample on Fiddler https://dotnetfiddle.net/qLrePt
Sequelize methods return promises, and there is no delete()
method. Sequelize uses destroy()
instead.
Model.destroy({
where: {
some_field: {
//any selection operation
// for example [Op.lte]:new Date()
}
}
}).then(result => {
//some operation
}).catch(error => {
console.log(error)
})
Documentation for more details: https://www.codota.com/code/javascript/functions/sequelize/Model/destroy
I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.
openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text
One thing I've noticed is that whenever you are editing the list (adding items for example) as well as filtering for it, then inside the @Override getView
method, you shouldn't use filteredData.get(position)
, as it throws an IndexOutOfBounds
exception.
Instead, what worked for me, was using the getItem(position)
method, which belongs to the ArrayAdapter
class.
We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:
Create a new function with your information for the infoWindow in it:
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
Then call the function with the array ID and the marker you want to create:
addInfoWindow(marker, hotels[i][3]);
A more elegant way is to assign the whole array at once:
Sub PrintArray(Data, SheetName, StartRow, StartCol)
Dim Rng As Range
With Sheets(SheetName)
Set Rng = .Range(.Cells(StartRow, StartCol), _
.Cells(UBound(Data, 1) - LBound(Data, 1) + StartRow, _
UBound(Data, 2) - LBound(Data, 2) + StartCol))
End With
Rng.Value2 = Data
End Sub
But watch out: it only works up to a size of about 8,000 cells. Then Excel throws a strange error. The maximum size isn't fixed and differs very much from Excel installation to Excel installation.
I did a test on MS SQL 2005 using the following tables: A 400K rows, B 26K rows and C 450 rows.
The estimated query plan indicated that the basic inner join would be 3 times slower than the nested sub-queries, however when actually running the query, the basic inner join was twice as fast as the nested queries, The basic inner join took 297ms on very minimal server hardware.
What database are you using, and what times are you seeing? I'm thinking if you are seeing poor performance then it is probably an index problem.
It’s just <b>
instead of <bold>
:
Some <b>text</b> that I want bolded.
Note that <b>
just changes the appearance of the text. If you want to render it bold because you want to express a strong emphasis, you should better use the <strong>
element.
Have you try changing your project name in package.json
and execute command git init
to reinitialize the existing Git, instead?
Your existing Git history will still exist.
Try this :
$('.close-button').on('click', function(){
$('.element').removeClass('grown');
$('.element').addClass('spot');
});
$('.element').on('click', function(){
$(this).removeClass('spot');
$(this).addClass('grown');
});
I hope I understood your question.
I needed to figure out the system host IP address for the emulator "Nox App Player". Here is how I figured out it was 172.17.100.2
.
ip link show
command to show all network interfaces. Of particular interest was the eth1 interfaceifconfig eth1
command, shows net as 172.17.100.15/255.255.255.0
172.17.100.1
, got a hit on `172.17.100.2'. Not sure if a firewall would interfere but it didn't in my caseMaybe this can help someone else figure it out for other emulators.
in my case using angular
in my HTTP interceptor , i set
with Credentials: true.
in the header of the request
Using LINQ to manipulate data in DataSet/DataTable
var results = from myRow in tblCurrentStock.AsEnumerable()
where myRow.Field<string>("item_name").ToUpper().StartsWith(tbSearchItem.Text.ToUpper())
select myRow;
DataView view = results.AsDataView();
Usually, deleting the current emulator that doesn't work anymore and creating it again will solve the issue. I've had it 5 minutes ago and that's how I solved it.
Just try " gcc filename.c -lm" while compiling the program ...it worked for me
We can simply do this.
select *
from
table1 t, CRM_VCM_CURRENT_LEAD_STATUS c
WHERE t.CM_PLAN_ID = c.CRM_VCM_CURRENT_LEAD_STATUS
and t.Individual_ID = c.Individual_ID
What worked for me was setting aspnet:MaxHttpCollectionKeys to a high value on appSettings tag on the inetpub VirtualDirectories\443\web.config file:
<configuration>
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="100000" />
</appSettings>
</configuration>
You can match those three groups separately, and make sure that they all present. Also, [^\w]
seems a bit too broad, but if that's what you want you might want to replace it with \W
.
You'll need at least PHP Version 5.4 to implement this solution without exploding into a variable on one line and concatenating on the next, but an easy one liner would be:
$_SERVER["HTTP_HOST"].explode('?', $_SERVER["REQUEST_URI"], 2)[0];
Server Variables: http://php.net/manual/en/reserved.variables.server.php
Array Dereferencing: https://wiki.php.net/rfc/functionarraydereferencing
const int * ptr;
means that the pointed data is constant and immutable but the pointer is not.
int * const ptr;
means that the pointer is constant and immutable but the pointed data is not.
The topic is quite old, yet I struggled with the same issue today while compiling cegui 0.7.1 (openVibe prerequisite).
What worked for me was to set: LDFLAGS="-Wl,--no-as-needed"
in the Makefile.
I've also tried -ldl
for LDFLAGS
but to no avail.
Downloading Wget is not necessary; the .NET Framework has web client classes built in.
$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")
It seems to me that if a collection has a mode, then its elements can be mapped one-to-one with the natural numbers. So, the problem of finding the mode reduces to producing such a mapping, finding the mode of the mapped values, then mapping back to some of the items in the collection. (Dealing with NA
occurs at the mapping phase).
I have a histogram
function that operates on a similar principal. (The special functions and operators used in the code presented herein should be defined in Shapiro and/or the neatOveRse. The portions of Shapiro and neatOveRse duplicated herein are so duplicated with permission; the duplicated snippets may be used under the terms of this site.) R pseudocode for histogram
is
.histogram <- function (i)
if (i %|% is.empty) integer() else
vapply2(i %|% max %|% seqN, `==` %<=% i %O% sum)
histogram <- function(i) i %|% rmna %|% .histogram
(The special binary operators accomplish piping, currying, and composition) I also have a maxloc
function, which is similar to which.max
, but returns all the absolute maxima of a vector. R pseudocode for maxloc
is
FUNloc <- function (FUN, x, na.rm=F)
which(x == list(identity, rmna)[[na.rm %|% index.b]](x) %|% FUN)
maxloc <- FUNloc %<=% max
minloc <- FUNloc %<=% min # I'M THROWING IN minloc TO EXPLAIN WHY I MADE FUNloc
Then
imode <- histogram %O% maxloc
and
x %|% map %|% imode %|% unmap
will compute the mode of any collection, provided appropriate map
-ping and unmap
-ping functions are defined.
In Access VBA I've used this to turn off all the dialogs when running a bunch of updates:
DoCmd.SetWarnings False
After running all the updates, the last step in my VBA script is:
DoCmd.SetWarnings True
Hope this helps.
The below code works fine but I am not sure about the radio button and dropdown list
$( '#form_id' ).submit( function( event ) {
event.preventDefault();
//validate fields
var fail = false;
var fail_log = '';
var name;
$( '#form_id' ).find( 'select, textarea, input' ).each(function(){
if( ! $( this ).prop( 'required' )){
} else {
if ( ! $( this ).val() ) {
fail = true;
name = $( this ).attr( 'name' );
fail_log += name + " is required \n";
}
}
});
//submit if fail never got set to true
if ( ! fail ) {
//process form here.
} else {
alert( fail_log );
}
});
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "SexDrugsRocknroll";
char dest[5] = { 0 }; // 4 chars + terminator */
int len = strlen(src);
int i = 0;
while (i*4 < len) {
strncpy(dest, src+(i*4), 4);
i++;
printf("loop %d : %s\n", i, dest);
}
}
The question title asks how to host material icons offline but the body clarifies that the objective is to use the material icons offline (emphasis mine).
Using your own copy of the material icons files is a valid approach/implementation. Another, for those that can use a service worker is to let the service worker take care of it. That way you don't have the hassle of obtaining a copy and keeping it up to date.
For example, generate a service worker using Workbox, using the simplest approach of running workbox-cli and accepting the defaults, then append the following text to the generated service worker:
workboxSW.router.registerRoute('https://fonts.googleapis.com/(.*)',
workboxSW.strategies.cacheFirst({
cacheName: 'googleapis',
cacheExpiration: {
maxEntries: 20
},
cacheableResponse: {statuses: [0, 200]}
})
);
You can then check it was cached in Chrome using F12 > Application > Storage > IndexedDB and look for an entry with googleapis in the name.
Yes, docker has restart policies such as docker run --restart=always
that will handle this. This is also available in the compose.yml config file as restart: always
.
In my experience, using a PYTHONPATH variable at all is usually the wrong approach, because it does not play nicely with VENV on windows. PYTHON on loading will prepare the path by prepending PYTHONPATH to the path, which can result in your carefully prepared Venv preferentially fetching global site packages.
Instead of using PYTHON path, include a pythonpath.pth file in the relevant site-packages directory (although beware custom pythons occasionally look for them in different locations, e.g. enthought looks in the same directory as python.exe for its .pth files) with each virtual environment. This will act like a PYTHONPATH only it will be specific to the python installation, so you can have a separate one for each python installation/environment. Pycharm integrates strongly with VENV if you just go to yse the VENV's python as your python installation.
See e.g. this SO question for more details on .pth files....
((DefaultTableModel)jTable3.getModel()).setNumRows(0); // delet all table row
Try This:
You cannot calculate the differences separately ... what difference would that yield for 7:59 and 8:00 o'clock? Try
import time
time.time()
which gives you the seconds since the start of the epoch.
You can then get the intermediate time with something like
timestamp1 = time.time()
# Your code here
timestamp2 = time.time()
print "This took %.2f seconds" % (timestamp2 - timestamp1)
Just replace the "\n
" with "".
In vi/Vim for every line in the document:
%s/>\n_/>_/g
If you want to confirm every replacement:
%s/>\n_/>_/gc
Use a color with an alpha value like #33------
, and set it as background of your editText using the XML attribute android:background=" "
.
255 * 0.2 = 51 ? in hex 33
overthink suggested using the setup in the pom:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
... other stuff ...
</configuration>
</plugin>
</plgins>
</build>
...
First i thought this still won't attach the javadoc and sources (as i tried unsuccessfully with that -DdownloadSources option before).
But surprise - the .classpath file IS getting its sources and javadoc attached when using the POM variant!
CSS only solution for modern browsers
@keyframes slidein {
0% {margin-left:1500px;}
100% {margin-left:0px;}
}
.note {
animation-name: slidein;
animation-duration: .9s;
display: block;
}
Use is_same
:
#include <type_traits>
template <typename T>
void foo()
{
if (std::is_same<T, animal>::value) { /* ... */ } // optimizable...
}
Usually, that's a totally unworkable design, though, and you really want to specialize:
template <typename T> void foo() { /* generic implementation */ }
template <> void foo<animal>() { /* specific for T = animal */ }
Note also that it's unusual to have function templates with explicit (non-deduced) arguments. It's not unheard of, but often there are better approaches.
I have done it this way:
<?php
$PHPtext = "Your PHP alert!";
?>
var JavaScriptAlert = <?php echo json_encode($PHPtext); ?>;
alert(JavaScriptAlert); // Your PHP alert!
Most likely you need to download and include the TypeScript declaration file for jQuery—jquery.d.ts
—in your project.
Option 1: Install the @types package (Recommended for TS 2.0+)
In the same folder as your package.json file, run the following command:
npm install --save-dev @types/jquery
Then the compiler will resolve the definitions for jquery automatically.
Option 2: Download Manually (Not Recommended)
Download it here.
Option 3: Using Typings (Pre TS 2.0)
If you're using typings then you can include it this way:
// 1. Install typings
npm install typings -g
// 2. Download jquery.d.ts (run this command in the root dir of your project)
typings install dt~jquery --global --save
After setting up the definition file, import the alias ($
) in the desired TypeScript file to use it as you normally would.
import $ from "jquery";
// or
import $ = require("jquery");
You may need to compile with --allowSyntheticDefaultImports
—add "allowSyntheticDefaultImports": true
in tsconfig.json.
Also Install the Package?
If you don't have jquery installed, you probably want to install it as a dependency via npm (but this is not always the case):
npm install --save jquery
For me this worked:
int imgCarMarginRightPx = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, definedValueInDp, res.getDisplayMetrics());
MarginLayoutParams lp = (MarginLayoutParams) imgCar.getLayoutParams();
lp.setMargins(0,0,imgCarMarginRightPx,0);
imgCar.setLayoutParams(lp);
I had the same issue and tried many of the solutions listed above.
I then remembered that I have multiple versions of Python installed AND I use the PyCharm IDE (which is where I was getting this error message), so the solution in my case was:
In PyCharm:
go to File>Settings>Project>Python Interpreter
click "+" (install)
locate Pillow from the list and install it
Hope this helps anyone who may be in a similar situation!
Don't use GitHub as a Maven Repository.
Edit: This option gets a lot of down votes, but no comments as to why. This is the correct option regardless of the technical capabilities to actually host on GitHub. Hosting on GitHub is wrong for all the reasons outlined below and without comments I can't improve the answer to clarify your issues.
Best Option - Collaborate with the Original Project
The best option is to convince the original project to include your changes and stick with the original.
Alternative - Maintain your own Fork
Since you have forked an open source library, and your fork is also open source, you can upload your fork to Maven Central (read Guide to uploading artifacts to the Central Repository) by giving it a new groupId
and maybe a new artifactId
.
Only consider this option if you are willing to maintain this fork until the changes are incorporated into the original project and then you should abandon this one.
Really consider hard whether a fork is the right option. Read the myriad Google results for 'why not to fork'
Reasoning
Bloating your repository with jars increases download size for no benefit
A jar is an output
of your project, it can be regenerated at any time from its inputs
, and your GitHub repo should contain only inputs
.
Don't believe me? Then check Google results for 'dont store binaries in git'.
GitHub's help Working with large files will tell you the same thing. Admittedly jar's aren't large but they are larger than the source code and once a jar has been created by a release they have no reason to be versioned - that is what a new release is for.
Defining multiple repos in your pom.xml slows your build down by Number of Repositories times Number of Artifacts
Stephen Connolly says:
If anyone adds your repo they impact their build performance as they now have another repo to check artifacts against... It's not a big problem if you only have to add one repo... But the problem grows and the next thing you know your maven build is checking 50 repos for every artifact and build time is a dog.
That's right! Maven needs to check every artifact (and its dependencies) defined in your pom.xml against every Repository you have defined, as a newer version might be available in any of those repositories.
Try it out for yourself and you will feel the pain of a slow build.
The best place for artifacts is in Maven Central, as its the central place for jars, and this means your build will only ever check one place.
You can read some more about repositories at Maven's documentation on Introduction to Repositories
I have always preferred using the TryParse()
methods because it is going to spit back success or failure to convert without having to worry about exceptions.
Have you tried..
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
If you are consuming a trusted source you can skip the verify.
I think your issue may be in the url pattern. Changing
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
and
<form action="/Register" method="post">
may fix your problem
I added the following to my htaccess file, which did the trick:
BrowserMatch MSIE ie
Header set X-UA-Compatible "IE=Edge,chrome=1" env=ie
I created a game framework sometime ago to work on Android and Desktop, the desktop part that handle sound maybe can be used as inspiration to what you need.
Here is the code for reference.
package com.athanazio.jaga.desktop.sound;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class Sound {
AudioInputStream in;
AudioFormat decodedFormat;
AudioInputStream din;
AudioFormat baseFormat;
SourceDataLine line;
private boolean loop;
private BufferedInputStream stream;
// private ByteArrayInputStream stream;
/**
* recreate the stream
*
*/
public void reset() {
try {
stream.reset();
in = AudioSystem.getAudioInputStream(stream);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
line = getLine(decodedFormat);
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
line.close();
din.close();
in.close();
} catch (IOException e) {
}
}
Sound(String filename, boolean loop) {
this(filename);
this.loop = loop;
}
Sound(String filename) {
this.loop = false;
try {
InputStream raw = Object.class.getResourceAsStream(filename);
stream = new BufferedInputStream(raw);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// byte[] buffer = new byte[1024];
// int read = raw.read(buffer);
// while( read > 0 ) {
// out.write(buffer, 0, read);
// read = raw.read(buffer);
// }
// stream = new ByteArrayInputStream(out.toByteArray());
in = AudioSystem.getAudioInputStream(stream);
din = null;
if (in != null) {
baseFormat = in.getFormat();
decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, baseFormat
.getSampleRate(), 16, baseFormat.getChannels(),
baseFormat.getChannels() * 2, baseFormat
.getSampleRate(), false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
line = getLine(decodedFormat);
}
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
private SourceDataLine getLine(AudioFormat audioFormat)
throws LineUnavailableException {
SourceDataLine res = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
res = (SourceDataLine) AudioSystem.getLine(info);
res.open(audioFormat);
return res;
}
public void play() {
try {
boolean firstTime = true;
while (firstTime || loop) {
firstTime = false;
byte[] data = new byte[4096];
if (line != null) {
line.start();
int nBytesRead = 0;
while (nBytesRead != -1) {
nBytesRead = din.read(data, 0, data.length);
if (nBytesRead != -1)
line.write(data, 0, nBytesRead);
}
line.drain();
line.stop();
line.close();
reset();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Just change moveCamera to animateCamera like below
Googlemap.animateCamera(CameraUpdateFactory.newLatLngZoom(locate, 16F))
Here's what I would do:
for file in *.[Jj][Pp][Gg] ;do
echo mv -vi \"$file\" `jhead $file|
grep Date|
cut -b 16-|
sed -e 's/:/-/g' -e 's/ /_/g' -e 's/$/.jpg/g'` ;
done
Then if that looks ok, add | sh
to the end. So:
for file in *.[Jj][Pp][Gg] ;do
echo mv -vi \"$file\" `jhead $file|
grep Date|
cut -b 16-|
sed -e 's/:/-/g' -e 's/ /_/g' -e 's/$/.jpg/g'` ;
done | sh
Have you tried this?:
countif(rangethatyouhave, not(""))
I don't think you need to open the code editor, you can just do it in the spreadsheet itself.
Python 3.6+:
from datetime import date
today = date.today()
text = "Today it is " + today.strftime(f"%A %B {today.day}, %Y")
I know this is an old question. Yet it's surprising that no good answer was given.
First of all the question is completely valid without mentioning the framework. The CONTEXT is a PHP language equivalence. Although there are many ways to get the query string parameters in Python, the framework variables are just conveniently populated. In PHP, $_GET
and $_POST
are also convenience variables. They are parsed from QUERY_URI and php://input respectively.
In Python, these functions would be os.getenv('QUERY_STRING')
and sys.stdin.read()
. Remember to import os and sys modules.
We have to be careful with the word "CGI" here, especially when talking about two languages and their commonalities when interfacing with a web server. 1. CGI, as a protocol, defines the data transport mechanism in the HTTP protocol. 2. Python can be configured to run as a CGI-script in Apache. 3. The CGI module in Python offers some convenience functions.
Since the HTTP protocol is language-independent, and that Apache's CGI extension is also language-independent, getting the GET and POST parameters should bear only syntax differences across languages.
Here's the Python routine to populate a GET dictionary:
GET={}
args=os.getenv("QUERY_STRING").split('&')
for arg in args:
t=arg.split('=')
if len(t)>1: k,v=arg.split('='); GET[k]=v
and for POST:
POST={}
args=sys.stdin.read().split('&')
for arg in args:
t=arg.split('=')
if len(t)>1: k, v=arg.split('='); POST[k]=v
You can now access the fields as following:
print GET.get('user_id')
print POST.get('user_name')
I must also point out that the CGI module doesn't work well. Consider this HTTP request:
POST / test.py?user_id=6
user_name=Bob&age=30
Using CGI.FieldStorage().getvalue('user_id')
will cause a null pointer exception because the module blindly checks the POST data, ignoring the fact that a POST request can carry GET parameters too.
That's not possible. localhost
always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.
If you want to access it e.g. in a browser, connect to it using the local IP instead:
http://192.168.180.1:8000
This is just an example of course, you can find out the actual IP by issuing an ifconfig
command on a shell in the guest operating system.
PHP syntax is little different in case of concatenation from JavaScript.
Instead of (+) plus
a (.) period
is used for string concatenation.
<?php
$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
$selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
$selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;
?>
It depends on the likelihood of a semicolon ending up near your &
, causing it to display something quite different.
For example, when dealing with input from users (say, if you include the user-provided subject of a forum post in your title tags), you never know where they might be putting random semicolons, and it might randomly display strange entities. So always escape in that situation.
For your own static html, sure, you could skip it, but it's so trivial to include proper escaping, that there's no good reason to avoid it.
we can use Outputstream to output our Object to internal memory. And convert to string then save in preference. For example:
mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = mPrefs.edit();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutput;
try {
objectOutput = new ObjectOutputStream(arrayOutputStream);
objectOutput.writeObject(object);
byte[] data = arrayOutputStream.toByteArray();
objectOutput.close();
arrayOutputStream.close();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(out, Base64.DEFAULT);
b64.write(data);
b64.close();
out.close();
ed.putString(key, new String(out.toByteArray()));
ed.commit();
} catch (IOException e) {
e.printStackTrace();
}
when we need to extract Object from Preference. Use the code as below
byte[] bytes = mPrefs.getString(indexName, "{}").getBytes();
if (bytes.length == 0) {
return null;
}
ByteArrayInputStream byteArray = new ByteArrayInputStream(bytes);
Base64InputStream base64InputStream = new Base64InputStream(byteArray, Base64.DEFAULT);
ObjectInputStream in;
in = new ObjectInputStream(base64InputStream);
MyObject myObject = (MyObject) in.readObject();
Internet Explorer doesn't fully support Flexbox due to:
Partial support is due to large amount of bugs present (see known issues).
Screenshot and infos taken from caniuse.com
Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.
display: flex
and flex-direction: column
will not properly calculate their flexed childrens' sizes if the container has min-height
but no explicit height
property. See bug.flex
is 0 0 auto
rather than 0 1 auto
as defined in the latest spec.min-height
is used. See bug.Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.
align-items: center
overflow their containermin-height
on a flex container won't apply to its flex itemsflex
shorthand declarations with unitless flex-basis
values are ignoredflex
items don't always preserve intrinsic aspect ratiosflex-basis
doesn't account for box-sizing: border-box
flex-basis
doesn't support calc()
align-items: baseline
doesn't work with nested flex containersflex-flow: column wrap
do not contain their itemsmargin: auto
on the cross axisflex-basis
cannot be animatedmax-width
is usedIt looks like you're trying to use an image to submit a form... in that case use
<input type="image" src="...">
If you really want to use an anchor then you have to use javascript:
<a href="#" onclick="document.forms['myFormName'].submit(); return false;">...</a>
shopList = []
maxLengthList = 6
while len(shopList) < maxLengthList:
item = input("Enter your Item to the List: ")
shopList.append(item)
print shopList
print "That's your Shopping List"
print shopList
Just backgrounding your script (./myscript &
) will not daemonize it. See http://www.faqs.org/faqs/unix-faq/programmer/faq/, section 1.7, which describes what's necessary to become a daemon. You must disconnect it from the terminal so that SIGHUP
does not kill it. You can take a shortcut to make a script appear to act like a daemon;
nohup ./myscript 0<&- &>/dev/null &
will do the job. Or, to capture both stderr and stdout to a file:
nohup ./myscript 0<&- &> my.admin.log.file &
However, there may be further important aspects that you need to consider. For example:
chdir("/")
(or cd /
inside your script), and fork so that the parent exits, and thus the original descriptor is closed.umask 0
. You may not want to depend on the umask of the caller of the daemon.For an example of a script that takes all of these aspects into account, see Mike S' answer.
yes you can do it. write this code on your typescript component and enjoy!
import { Location } from '@angular/common'
import { Component, Input } from '@angular/core'
@Component({
selector: 'return_page',
template: `<button mat-button (click)="onReturn()">Back</button>`,
})
export class ReturnPageComponent {
constructor(private location: Location) { }
onReturn() {
this.location.back();
}
}
This works perfectly fine with me. It takes label and format the value.
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
let label = data.labels[tooltipItem.index];
let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return ' ' + label + ': ' + value + ' %';
}
}
}
}
Best Query For comma separated in This Query we Convert Rows To Column ...
SELECT listagg(BL_PRODUCT_DESC, ', ') within
group( order by BL_PRODUCT_DESC) PROD
FROM GET_PRODUCT
-- WHERE BL_PRODUCT_DESC LIKE ('%WASH%')
WHERE Get_Product_Type_Id = 6000000000007
Yes, ArrayList is an ordered collection and it maintains the insertion order.
Check the code below and run it:
public class ListExample {
public static void main(String[] args) {
List<String> myList = new ArrayList<String>();
myList.add("one");
myList.add("two");
myList.add("three");
myList.add("four");
myList.add("five");
System.out.println("Inserted in 'order': ");
printList(myList);
System.out.println("\n");
System.out.println("Inserted out of 'order': ");
// Clear the list
myList.clear();
myList.add("four");
myList.add("five");
myList.add("one");
myList.add("two");
myList.add("three");
printList(myList);
}
private static void printList(List<String> myList) {
for (String string : myList) {
System.out.println(string);
}
}
}
Produces the following output:
Inserted in 'order':
one
two
three
four
five
Inserted out of 'order':
four
five
one
two
three
For detailed information, please refer to documentation: List (Java Platform SE7)
You have at least two issues in your code:
ng-change="getScoreData(Score)
Angular doesn't see getScoreData
method that refers to defined service
getScoreData: function (Score, callback)
We don't need to use callback since GET
returns promise. Use then
instead.
Here is a working example (I used random address only for simulation):
HTML
<select ng-model="score"
ng-change="getScoreData(score)"
ng-options="score as score.name for score in scores"></select>
<pre>{{ScoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {
$scope.scores = [{
name: 'Bukit Batok Street 1',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
}, {
name: 'London 8',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
}];
$scope.getScoreData = function(score) {
ScoreDataService.getScoreData(score).then(function(result) {
$scope.ScoreData = result;
}, function(result) {
alert("Error: No data returned");
});
};
});
fessmodule.$inject = ['$scope', 'ScoreDataService'];
fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {
var factory = {
getScoreData: function(score) {
console.log(score);
var data = $http({
method: 'GET',
url: score.URL
});
return data;
}
}
return factory;
}]);
Demo Fiddle
You can remove that configuration with:
git config --global --unset core.gitproxy
To find case Insensitive string use this,
var thename = "Andrew";
db.collection.find({"name":/^thename$/i})
I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.
Following is one liner for accepted answer ... (for one line lovers ..)
def search_dict(my_dict,searchFor):
s_val = [[ k if searchFor in v else None for v in my_dict[k]] for k in my_dict]
return s_val
JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.
prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.
You can also do:
(from u in table
orderby u.Status descending
select u).Take(1);
If you are just going to substitute it into a URL I suppose one field would do - so you can form a URL like
http://maps.google.co.uk/maps?q=12.345678,12.345678&z=6
but as it is two pieces of data I would store them in separate fields
Clip.exe is an executable in Windows to set the clipboard. Note that this does not work for other operating systems other than Windows, which still sucks.
/// <summary>
/// Sets clipboard to value.
/// </summary>
/// <param name="value">String to set the clipboard to.</param>
public static void SetClipboard(string value)
{
if (value == null)
throw new ArgumentNullException("Attempt to set clipboard with null");
Process clipboardExecutable = new Process();
clipboardExecutable.StartInfo = new ProcessStartInfo // Creates the process
{
RedirectStandardInput = true,
FileName = @"clip",
};
clipboardExecutable.Start();
clipboardExecutable.StandardInput.Write(value); // CLIP uses STDIN as input.
// When we are done writing all the string, close it so clip doesn't wait and get stuck
clipboardExecutable.StandardInput.Close();
return;
}
With the command:
sudo apt-get remove --purge mysql\*
you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).
You can list all installed mysql packages with the command:
sudo dpkg -l | grep -i mysql
For more cleanup of the package cache, you can use the command:
sudo apt-get clean
Also, remember to use the command:
sudo updatedb
Otherwise the "locate" command will display old data.
To install mysql again, use the following command:
sudo apt-get install libmysqlclient-dev mysql-client
This will install the mysql client, libmysql and its headers files.
To install the mysql server, use the command:
sudo apt-get install mysql-server
select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b
where table_name='YOUR_TABLE' and a.table_name = b.name;
This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value
). Else, if default partition is defined, it would go there.
EDIT:
I presume, your TABLE DDL would be like this.
CREATE TABLE HE0_DT_INF_INTERFAZ_MES
(
COD_PAIS NUMBER,
FEC_DATA NUMBER,
INTERFAZ VARCHAR2(100)
)
partition BY RANGE(COD_PAIS, FEC_DATA)
(
PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
);
Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);
That is first COD_PAIS <= 98
and Also FEC_DATA < 20091024
Combinations And Result:
98, 20091024 FAIL
98, 20091023 PASS
99, ******** FAIL
97, ******** PASS
< 98, ******** PASS
So the below INSERT
fails with ORA-14400; because (98,20091024)
in INSERT
is EQUAL to the one in DDL
but NOT less than it.
SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
VALUES(98, 20091024, 'CTA'); 2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
*
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition
But, we I attempt (97,20091024), it goes through
SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
2 VALUES(97, 20091024, 'CTA');
1 row created.
You're missing service name:
SQL> connect username/password@hostname:port/SERVICENAME
EDIT
If you can connect to the database from other computer try running there:
select sys_context('USERENV','SERVICE_NAME') from dual
and
select sys_context('USERENV','SID') from dual
Well in general:
List<String> names = new ArrayList<String>();
names.add("john");
names.add("ann");
String[] namesArr = new String[names.size()];
for (int i = 0; i < names.size(); i++) {
namesArr[i] = names.get(i);
}
Or better yet, using built in:
List<String> names = new ArrayList<String>();
String[] namesArr = names.toArray(new String[names.size()]);
IntelliJ IDEA does not have an action to add imports. Rather it has the ability to do such as you type. If you enable the "Add unambiguous imports on the fly" in Settings > Editor > General > Auto Import, IntelliJ IDEA will add them as you type without the need for any shortcuts. You can also add classes and packages to exclude from auto importing to make a class you use heavily, that clashes with other classes of the same name, unambiguous.
For classes that are ambiguous (or is you prefer to have the "Add unambiguous imports on the fly" option turned off), just type the name of the class (just the name is OK, no need to fully qualify). Use code completion and select the particular class you want:
Notice the fully qualified names to the right. When I select the one I want and hit enter, IDEA will automatically add the import statement. This works the same if I was typing the name of a constructor. For static methods, you can even just keep typing the method you want. In the following screenshot, no "StringUtils" class is imported yet.
Alternatively, type the class name and then hit Alt+Enter or ?+Enter to "Show intention actions and quick-fixes" and then select the import option.
Although I've never used it, I think the Eclipse Code Formatter third party plug-in will do what you want. It lists "emulates Eclipse's imports optimizing" as a feature. See its instructions for more information. But in the end, I suspect you'll find the built in IDEA features work fine once you get use to their paradigm. In general, IDEA uses a "develop by intentions" concept. So rather than interrupting my development work to add an import statement, I just type the class I want (my intention) and IDEA automatically adds the import statement for the class for me.
angular:
MethodName(stringValue: any): Observable<any> {
let params = new HttpParams();
params = params.append('categoryName', stringValue);
return this.http.post('yoururl', '', {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
params: params,
responseType: "json"
})
}
api:
[HttpPost("[action]")]
public object Method(string categoryName)
Try the heredoc-based solution:
echo <<<HTML
<div>
<h3><a href="#">First</a></h3>
<div>Lorem ipsum dolor sit amet.</div>
</div>
<div>
HTML;
A bit clunky, but this works for me right now to set background and text colors. I found it here.
UIView * firstView = alertController.view.subviews.firstObject;
UIView * nextView = firstView.subviews.firstObject;
nextView.backgroundColor = [UIColor blackColor];
This is a general rambling on Parallelism in SQL Server, it might not answer your question directly.
From Books Online, on MAXDOP:
Sets the maximum number of processors the query processor can use to execute a single index statement. Fewer processors may be used depending on the current system workload.
See Rickie Lee's blog on parallelism and CXPACKET wait type. It's quite interesting.
Generally, in an OLTP database, my opinion is that if a query is so costly it needs to be executed on several processors, the query needs to be re-written into something more efficient.
Why you get better results adding MAXDOP(1)? Hard to tell without the actual execution plans, but it might be so simple as that the execution plan is totally different that without the OPTION, for instance using a different index (or more likely) JOINing differently, using MERGE or HASH joins.
With the new syntax of RxJS 5.5+, this becomes as the following:
// RxJS 6
import { EMPTY, empty, of } from "rxjs";
// rxjs 5.5+ (<6)
import { empty } from "rxjs/observable/empty";
import { of } from "rxjs/observable/of";
empty(); // deprecated use EMPTY
EMPTY;
of({});
Just one thing to keep in mind, EMPTY
completes the observable, so it won't trigger next
in your stream, but only completes. So if you have, for instance, tap
, they might not get trigger as you wish (see an example below).
Whereas of({})
creates an Observable
and emits next with a value of {}
and then it completes the Observable
.
E.g.:
EMPTY.pipe(
tap(() => console.warn("i will not reach here, as i am complete"))
).subscribe();
of({}).pipe(
tap(() => console.warn("i will reach here and complete"))
).subscribe();
This is the cleanest solution I have found (Internet Explorer 9+) and adds a fix for the "off by .5 pixel" issue by using transform-style
that other answers had omitted.
.parent-element {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}
.element {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
Here is a way how to send message in WhatsApp in KOTLIN
private fun sendMessage(phone: String, message: String) {
val pm = requireActivity().packageManager
val i = Intent(Intent.ACTION_VIEW)
try {
val url = "https://api.whatsapp.com/send?phone=$phone&text=" + URLEncoder.encode(
message,
"UTF-8"
)
i.setPackage("com.whatsapp")
i.data = Uri.parse(url)
if (i.resolveActivity(pm) != null) {
context?.startActivity(i)
}
} catch (e: PackageManager.NameNotFoundException) {
Toast.makeText(requireContext(), "WhatsApp not Installed", Toast.LENGTH_SHORT).show()
}
}
Neither is good.
Behaviour should be configured independent of the actual markup. For instance, in jQuery you might do something like
$('#the-element').click(function () { /* perform action here */ });
in a separate <script>
block.
The advantage of this is that it
Furthermore, it degrades gracefully (but so would using the onclick
event) since you can provide the link tags with a href
in case the user doesn’t have JavaScript enabled.
Of course, these arguments still count if you’re not using jQuery or another JavaScript library (but why do that?).
To create a DLL File, click on New project, then select Class Library.
Enter your code into the class file that was automatically created for you and then click Build Solution from the Debug menu.
Now, look in your directory: ../debug/release/YOURDLL.dll
There it is! :)
P.S. DLL files cannot be run just like normal applciation (exe) files. You'll need to create a separate project (probably a win forms app) and then add your dll file to that project as a "Reference", you can do this by going to the Solution explorer, right clicking your project Name and selecting Add Reference then browsing to whereever you saved your dll file.
For more detail please click HERE
For C++11, vector.data()
will do the trick.
Some people like to use the Paint
, CellPainting
or CellFormatting
events, but note that changing a style in these events causes recursive calls. If you use DataBindingComplete
it will execute only once. The argument for CellFormatting
is that it is called only on visible cells, so you don't have to format non-visible cells, but you format them multiple times.
You can also compare with double value
BigDecimal a= new BigDecimal("1.1"); BigDecimal b =new BigDecimal("1.1");
System.out.println(a.doubleValue()==b.doubleValue());
Try:
self.request.get('sports_played', allow_multiple=True)
or
self.request.POST.getall('sports_played')
More specifically:
When you are reading data from the checkbox array, make sure array has:
len>0
In this case:
len(self.request.get('array', allow_multiple=True)) > 0
What's the difference: See other answers.
When use +
instead of %20
? Use +
if, for some reason, you want to make the URL query string (?.....
) or hash fragment (#....
) more readable. Example: You can actually read this:
https://www.google.se/#q=google+doesn%27t+encode+:+and+uses+%2B+instead+of+spaces
(%2B
= +)
But the following is a lot harder to read: (at least to me)
I would think +
is unlikely to break anything, since Google uses +
(see the 1st link above) and they've probably thought about this. I'm going to use +
myself just because readable + Google thinks it's OK.
It depends on what you mean by "empty". If you just want a zero-length string, then your example will work.
This will also work:
buffer[0] = '\0';
If you want to zero the entire contents of the string, you can do it this way:
memset(buffer,0,strlen(buffer));
but this will only work for zeroing up to the first NULL character.
If the string is a static array, you can use:
memset(buffer,0,sizeof(buffer));
std::atomic
exists because many ISAs have direct hardware support for it
What the C++ standard says about std::atomic
has been analyzed in other answers.
So now let's see what std::atomic
compiles to to get a different kind of insight.
The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and std::atomic
basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.
This support allows for faster alternatives to more general methods such as std::mutex
, which can make more complex multi-instruction sections atomic, at the cost of being slower than std::atomic
because std::mutex
it makes futex
system calls in Linux, which is way slower than the userland instructions emitted by std::atomic
, see also: Does std::mutex create a fence?
Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.
main.cpp
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
size_t niters;
#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif
void threadMain() {
for (size_t i = 0; i < niters; ++i) {
#if LOCK
__asm__ __volatile__ (
"lock incq %0;"
: "+m" (global),
"+g" (i) // to prevent loop unrolling
:
:
);
#else
__asm__ __volatile__ (
""
: "+g" (i) // to prevent he loop from being optimized to a single add
: "g" (global)
:
);
global++;
#endif
}
}
int main(int argc, char **argv) {
size_t nthreads;
if (argc > 1) {
nthreads = std::stoull(argv[1], NULL, 0);
} else {
nthreads = 2;
}
if (argc > 2) {
niters = std::stoull(argv[2], NULL, 0);
} else {
niters = 10;
}
std::vector<std::thread> threads(nthreads);
for (size_t i = 0; i < nthreads; ++i)
threads[i] = std::thread(threadMain);
for (size_t i = 0; i < nthreads; ++i)
threads[i].join();
uint64_t expect = nthreads * niters;
std::cout << "expect " << expect << std::endl;
std::cout << "global " << global << std::endl;
}
Compile, run and disassemble:
comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out $common
g++ -o main_std_atomic.out -DSTD_ATOMIC $common
g++ -o main_lock.out -DLOCK $common
./main_fail.out 4 100000
./main_std_atomic.out 4 100000
./main_lock.out 4 100000
gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out
Extremely likely "wrong" race condition output for main_fail.out
:
expect 400000
global 100000
and deterministic "right" output of the others:
expect 400000
global 400000
Disassembly of main_fail.out
:
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: mov 0x29b5(%rip),%rcx # 0x5140 <niters>
0x000000000000278b <+11>: test %rcx,%rcx
0x000000000000278e <+14>: je 0x27b4 <threadMain()+52>
0x0000000000002790 <+16>: mov 0x29a1(%rip),%rdx # 0x5138 <global>
0x0000000000002797 <+23>: xor %eax,%eax
0x0000000000002799 <+25>: nopl 0x0(%rax)
0x00000000000027a0 <+32>: add $0x1,%rax
0x00000000000027a4 <+36>: add $0x1,%rdx
0x00000000000027a8 <+40>: cmp %rcx,%rax
0x00000000000027ab <+43>: jb 0x27a0 <threadMain()+32>
0x00000000000027ad <+45>: mov %rdx,0x2984(%rip) # 0x5138 <global>
0x00000000000027b4 <+52>: retq
Disassembly of main_std_atomic.out
:
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: cmpq $0x0,0x29b4(%rip) # 0x5140 <niters>
0x000000000000278c <+12>: je 0x27a6 <threadMain()+38>
0x000000000000278e <+14>: xor %eax,%eax
0x0000000000002790 <+16>: lock addq $0x1,0x299f(%rip) # 0x5138 <global>
0x0000000000002799 <+25>: add $0x1,%rax
0x000000000000279d <+29>: cmp %rax,0x299c(%rip) # 0x5140 <niters>
0x00000000000027a4 <+36>: ja 0x2790 <threadMain()+16>
0x00000000000027a6 <+38>: retq
Disassembly of main_lock.out
:
Dump of assembler code for function threadMain():
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: cmpq $0x0,0x29b4(%rip) # 0x5140 <niters>
0x000000000000278c <+12>: je 0x27a5 <threadMain()+37>
0x000000000000278e <+14>: xor %eax,%eax
0x0000000000002790 <+16>: lock incq 0x29a0(%rip) # 0x5138 <global>
0x0000000000002798 <+24>: add $0x1,%rax
0x000000000000279c <+28>: cmp %rax,0x299d(%rip) # 0x5140 <niters>
0x00000000000027a3 <+35>: ja 0x2790 <threadMain()+16>
0x00000000000027a5 <+37>: retq
Conclusions:
the non-atomic version saves the global to a register, and increments the register.
Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of 100000
.
std::atomic
compiles to lock addq
. The LOCK prefix makes the following inc
fetch, modify and update memory atomically.
our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic
, except that our inc
is used instead of add
. Not sure why GCC chose add
, considering that our INC generated a decoding 1 byte smaller.
ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?
Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.
You need two server blocks.
Put these into your config file eg /etc/nginx/sites-available/sitename
Let's say you decide to have http://example.com as the main address to use.
Your config file should look like this:
server {
listen 80;
listen [::]:80;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
server {
listen 80;
listen [::]:80;
server_name example.com;
# this is the main server block
# insert ALL other config or settings in this server block
}
The first server block will hold the instructions to redirect any requests with the 'www' prefix. It listens to requests for the URL with 'www' prefix and redirects.
It does nothing else.
The second server block will hold your main address — the URL you want to use. All other settings go here like root
, index
, location
, etc. Check the default file for these other settings you can include in the server block.
The server needs two DNS A records.
Name: @ IPAddress: your-ip-address (for the example.com URL)
Name: www IPAddress: your-ip-address (for the www.example.com URL)
For ipv6 create the pair of AAAA records using your-ipv6-address.
What is the exact error you get? Is it like the following?
>>> datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z")
ValueError: time data did not match format: data=2008-08-12T12:20:30.656234Z fmt=%Y-%m-%dT%H:%M:%S.Z
If yes, you can split your input string on ".", and then add the microseconds to the datetime you got.
Try this:
>>> def gt(dt_str):
dt, _, us= dt_str.partition(".")
dt= datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
us= int(us.rstrip("Z"), 10)
return dt + datetime.timedelta(microseconds=us)
>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)
No need to extract the month and year.Just need to use the unix_timestamp(date String,format String) function.
For Example:
select yourdate_column
from your_table
where unix_timestamp(yourdate_column, 'yyyy-MM-dd') >= unix_timestamp('2014-06-02', 'yyyy-MM-dd')
and unix_timestamp(yourdate_column, 'yyyy-MM-dd') <= unix_timestamp('2014-07-02','yyyy-MM-dd')
order by yourdate_column limit 10;
max-age When an intermediate cache is forced, by means of a max-age=0 directive, to revalidate its own cache entry, and the client has supplied its own validator in the request, the supplied validator might differ from the validator currently stored with the cache entry. In this case, the cache MAY use either validator in making its own request without affecting semantic transparency. However, the choice of validator might affect performance. The best approach is for the intermediate cache to use its own validator when making its request. If the server replies with 304 (Not Modified), then the cache can return its now validated copy to the client with a 200 (OK) response. If the server replies with a new entity and cache validator, however, the intermediate cache can compare the returned validator with the one provided in the client's request, using the strong comparison function. If the client's validator is equal to the origin server's, then the intermediate cache simply returns 304 (Not Modified). Otherwise, it returns the new entity with a 200 (OK) response. If a request includes the no-cache directive, it SHOULD NOT include min-fresh, max-stale, or max-age.
courtesy: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4
Don't accept this as answer - I will have to read it to understand the true usage of it :)
Add condition in Click event to restrict the clickable area .
$('#thing').click(function(e) {
if (e.clientX > $(this).offset().left + 90 &&
e.clientY < $(this).offset().top + 10) {
// action when clicking on after-element
// your code here
}
});
It's been a moment that this question is asked, but this doesn't mean that we can't share other answers in 2020. Here is an awesome plugin with jquery:jQuery Lazy
The basic usage of Lazy:
HTML
<!-- load background images of other element types -->
<div class="lazy" data-src="path/to/image.jpg"></div>
enter code here
JS
$('.lazy').Lazy({
// your configuration goes here
scrollDirection: 'vertical',
effect: 'fadeIn',
visibleOnly: true,
onError: function(element) {
console.log('error loading ' + element.data('src'));
}
});
and your background images are lazy loading. That's all!
To see real examples and more details check this link lazy-doc.
We need a JSON file which we need to export in the controller of angularjs and we should be able to call from the HTML file. We will look at both. But before we start, we need to first add two files in our angular library. Those two files are json-export-excel.js and filesaver.js. Moreover, we need to include the dependency in the angular module. So the first two steps can be summarised as follows -
1) Add json-export.js and filesaver.js in your angular library.
2) Include the dependency of ngJsonExportExcel in your angular module.
var myapp = angular.module('myapp', ['ngJsonExportExcel'])
Now that we have included the necessary files we can move on to the changes which need to be made in the HTML file and the controller. We assume that a json is being created on the controller either manually or by making a call to the backend.
HTML :
Current Page as Excel
All Pages as Excel
In the application I worked, I brought paginated results from the backend. Therefore, I had two options for exporting to excel. One for the current page and one for all data. Once the user selects an option, a call goes to the controller which prepares a json (list). Each object in the list forms a row in the excel.
Read more at - https://www.oodlestechnologies.com/blogs/Export-to-excel-using-AngularJS
You can also use the transform: scale("")
option.
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
It will be better to Create a New role, then grant execute, select ... etc permissions to this role and finally assign users to this role.
Create role
CREATE ROLE [db_SomeExecutor]
GO
Grant Permission to this role
GRANT EXECUTE TO db_SomeExecutor
GRANT INSERT TO db_SomeExecutor
to Add users database>security> > roles > databaseroles>Properties > Add ( bottom right ) you can search AD users and add then
OR
EXEC sp_addrolemember 'db_SomeExecutor', 'domainName\UserName'
Please refer this post
In my case, I was using a fixed size header for each section but with a dynamically cell size in each header. The cell's height, depends on the label's height.
Working with:
tableView.estimatedRowHeight = SomeNumber
tableView.rowHeight = UITableViewAutomaticDimension
Works but when using:
tableView.reloadSections(IndexSet(integer: sender.tag) , with: .automatic)
when a lot of headers are not collapsed, creates a lot of bugs such as header duplication (header type x below the same type) and weird animations when the framework reloads with animation, even when using with type .none
(FYI, a fixed header height and cell height works).
The solution is making the use of heightForRowAt
callback and calculate the height of the label by your self (plus the animation looks a lot better). Remember that the height is being called first.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
let object = dataDetailsController.getRowObject(forIndexPath: indexPath)
let label = UILabel(frame: tableView.frame)
let font = UIFont(name: "HelveticaNeue-Bold", size: 25)
label.text = object?.name
label.font = font
label.numberOfLines = 0
label.textAlignment = .center
label.sizeToFit()
let size = label.frame.height
return Float(size) == 0 ? 34 : size
}
That's a great question. I think @Diederik has a good answer, although it's unfortunate that Cocoa doesn't have a mechanism for exactly what you want to do.
NSInputStream
allows you to read chunks of N bytes (very similar to java.io.BufferedReader
), but you have to convert it to an NSString
on your own, then scan for newlines (or whatever other delimiter) and save any remaining characters for the next read, or read more characters if a newline hasn't been read yet. (NSFileHandle
lets you read an NSData
which you can then convert to an NSString
, but it's essentially the same process.)
Apple has a Stream Programming Guide that can help fill in the details, and this SO question may help as well if you're going to be dealing with uint8_t*
buffers.
If you're going to be reading strings like this frequently (especially in different parts of your program) it would be a good idea to encapsulate this behavior in a class that can handle the details for you, or even subclassing NSInputStream
(it's designed to be subclassed) and adding methods that allow you to read exactly what you want.
For the record, I think this would be a nice feature to add, and I'll be filing an enhancement request for something that makes this possible. :-)
Edit: Turns out this request already exists. There's a Radar dating from 2006 for this (rdar://4742914 for Apple-internal people).
Make sure you are not facing a "cross module" problem
If the component which is using the pipe, doesn't belong to the module which has declared the pipe component "globally" then the pipe is not found and you get this error message.
In my case I've declared the pipe in a separate module and imported this pipe module in any other module having components using the pipe.
I have declared a that the component in which you are using the pipe is
the Pipe Module
import { NgModule } from '@angular/core';
import { myDateFormat } from '../directives/myDateFormat';
@NgModule({
imports: [],
declarations: [myDateFormat],
exports: [myDateFormat],
})
export class PipeModule {
static forRoot() {
return {
ngModule: PipeModule,
providers: [],
};
}
}
Usage in another module (e.g. app.module)
// Import APPLICATION MODULES
...
import { PipeModule } from './tools/PipeModule';
@NgModule({
imports: [
...
, PipeModule.forRoot()
....
],
With Ubuntu, I had the same problem. I solved it by changing file /dev/kvm
permission to 777:
sudo chmod 777 /dev/kvm
I'm using cymysql with python3 on a raspberry pi I simply installed by: sudo pip3 install cython sudo pip3 install cymysql where cython is not necessary but should make cymysql faster
So far it works like a charm and very similar to MySQLdb
Just put a '!' in front of the boolean expression
What image do you want to hide? Assuming all images, the following should work:
$("img").hide();
Otherwise, using selectors, you could find all images that are child elements of the containing div, and hide those.
However, i strongly recommend you read the Jquery docs, you could have figured it out yourself: http://docs.jquery.com/Main_Page
Here is a practical addition to the answers of PierreBdR and Moe:
dir()
seems to be enough.For old-style classes, we can at least do what a standard module does to support tab completion: in addition to dir()
, look for __class__
, and then to go for its __bases__
:
# code borrowed from the rlcompleter module
# tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3]' )
# or: from rlcompleter import get_class_members
def get_class_members(klass):
ret = dir(klass)
if hasattr(klass,'__bases__'):
for base in klass.__bases__:
ret = ret + get_class_members(base)
return ret
def uniq( seq ):
""" the 'set()' way ( use dict when there's no set ) """
return list(set(seq))
def get_object_attrs( obj ):
# code borrowed from the rlcompleter module ( see the code for Completer::attr_matches() )
ret = dir( obj )
## if "__builtins__" in ret:
## ret.remove("__builtins__")
if hasattr( obj, '__class__'):
ret.append('__class__')
ret.extend( get_class_members(obj.__class__) )
ret = uniq( ret )
return ret
(Test code and output are deleted for brevity, but basically for new-style objects we seem to have the same results for get_object_attrs()
as for dir()
, and for old-style classes the main addition to the dir()
output seem to be the __class__
attribute.)
If you're using SASS you could also use this mixin:
@mixin headings {
h1, h2, h3,
h4, h5, h6 {
@content;
}
}
Use it like so:
@include headings {
font: 32px/42px trajan-pro-1, trajan-pro-2;
}
Edit: My personal favourite way of doing this by optionally extending a placeholder selector on each of the heading elements.
h1, h2, h3,
h4, h5, h6 {
@extend %headings !optional;
}
Then I can target all headings like I would target any single class, for example:
.element > %headings {
color: red;
}
I found the answer is git reset --merge
- it clears the conflicted cherry-pick attempt.
This worked for me
var files=data.Contents;
files = files.sort(function(a,b){
return a.LastModified - b. LastModified;
});
OR use Lodash to sort the array
files = _.orderBy(files,'LastModified','asc');
You can get them using the Query String:
$idArray = explode('&',$_SERVER["QUERY_STRING"]);
This will give you:
$idArray[0] = "id=1";
$idArray[1] = "id=2";
$idArray[2] = "id=3";
Then
foreach ($idArray as $index => $avPair)
{
list($ignore, $value) = explode("=", $avPair);
$id[$index] = $value;
}
This will give you
$id[0] = "1";
$id[1] = "2";
$id[2] = "3";
Faced the same error. In my case , what i did wrong was that i injected the service(named DataService in my case) inside the constructor within the Component but I simply forgot to import it within the component.
constructor(private dataService:DataService ) {
console.log("constructor called");
}
I missed the below import code.
import { DataService } from '../../services/data.service';
This is an old thread, but I thought I should post my solution. I faced the same problem recently and the way I solved it is by following a three-step approach as outlined below which is very simple without any complex CSS.
(NOTE : Of course, for modern browsers, using the values of table or table-row or table-cell for display CSS attribute would solve the problem. But the approach I used will work equally well in modern and older browsers since it does not use these values for display CSS attribute.)
3-STEP SIMPLE APPROACH
For table with divs only so you get cells and rows just like in a table element use the following approach.
.table
class).row
class).cell
class).table {display:block; }_x000D_
.row { display:block;}_x000D_
.cell {display:inline-block;}
_x000D_
<h2>Table below using table element</h2>_x000D_
<table cellspacing="0" >_x000D_
<tr>_x000D_
<td>Mike</td>_x000D_
<td>36 years</td>_x000D_
<td>Architect</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Sunil</td>_x000D_
<td>45 years</td>_x000D_
<td>Vice President aas</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jason</td>_x000D_
<td>27 years</td>_x000D_
<td>Junior Developer</td>_x000D_
</tr>_x000D_
</table>_x000D_
<h2>Table below is using Divs only</h2>_x000D_
<div class="table">_x000D_
<div class="row">_x000D_
<div class="cell">_x000D_
Mike_x000D_
</div>_x000D_
<div class="cell">_x000D_
36 years_x000D_
</div>_x000D_
<div class="cell">_x000D_
Architect_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="cell">_x000D_
Sunil_x000D_
</div>_x000D_
<div class="cell">_x000D_
45 years_x000D_
</div>_x000D_
<div class="cell">_x000D_
Vice President_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="cell">_x000D_
Jason_x000D_
</div>_x000D_
<div class="cell">_x000D_
27 years_x000D_
</div>_x000D_
<div class="cell">_x000D_
Junior Developer_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
UPDATE 1
To get around the effect of same width not being maintained across all cells of a column as mentioned by thatslch
in a comment, one could adopt either of the two approaches below.
Specify a width for cell
class
cell {display:inline-block; width:340px;}
Use CSS of modern browsers as below.
.table {display:table; } .row { display:table-row;} .cell {display:table-cell;}
Versions of sed
that support the -i
option for editing a file in place write to a temporary file and then rename the file.
Alternatively, you can just use ed
. For example, to change all occurrences of foo
to bar
in the file file.txt
, you can do:
echo ',s/foo/bar/g; w' | tr \; '\012' | ed -s file.txt
Syntax is similar to sed
, but certainly not exactly the same.
Even if you don't have a -i
supporting sed
, you can easily write a script to do the work for you. Instead of sed -i 's/foo/bar/g' file
, you could do inline file sed 's/foo/bar/g'
. Such a script is trivial to write. For example:
#!/bin/sh
IN=$1
shift
trap 'rm -f "$tmp"' 0
tmp=$( mktemp )
<"$IN" "$@" >"$tmp" && cat "$tmp" > "$IN" # preserve hard links
should be adequate for most uses.
Replace each hex digit with the corresponding 4 binary digits:
1 - 0001
2 - 0010
...
a - 1010
b - 1011
...
f - 1111
I got the same error but I solved by using regsvr32.exe in C:\Windows\SysWOW64. Because we use x64 system. So if your machine is also x64, the ocx/dll must registered also with regsvr32 x64 version
Yet another approach is using window.scrollBy
function scroll(pxPerFrame, duration) {_x000D_
if (!pxPerFrame || !duration) return;_x000D_
const end = new Date().getTime() + duration;_x000D_
step(); _x000D_
_x000D_
function step() {_x000D_
window.scrollBy(0, pxPerFrame);_x000D_
if (new Date().getTime() < end) {_x000D_
window.setTimeout(step, 1000 / 60);_x000D_
} else {_x000D_
console.log('done scrolling'); _x000D_
}_x000D_
}_x000D_
}
_x000D_
body {_x000D_
width: 200px;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
<p>_x000D_
<button onclick="scroll(-5, 3000)">_x000D_
scroll(-5, 3000)_x000D_
</button>_x000D_
</p>
_x000D_
If you are using the source command on Windows remember to use f:/myfolder/mysubfolder/file.sql
and not f:\myfolder\mysubfolder\file.sql
After facing a similar issue, below is what I did :
To the CORS filter, I added corsFilter.getAllowedOrigins().add("http://localhost:4200");
.
Basically, you should add the URL which you want to allow Cross-Origin Resource Sharing. Ans you can also use "*"
instead of any specific URL to allow any URL.
public class RestApplication
extends Application
{
private Set<Object> singletons = new HashSet<Object>();
public MessageApplication()
{
singletons.add(new CalculatorService()); //CalculatorService is your specific service you want to add/use.
CorsFilter corsFilter = new CorsFilter();
// To allow all origins for CORS add following, otherwise add only specific urls.
// corsFilter.getAllowedOrigins().add("*");
System.out.println("To only allow restrcited urls ");
corsFilter.getAllowedOrigins().add("http://localhost:4200");
singletons = new LinkedHashSet<Object>();
singletons.add(corsFilter);
}
@Override
public Set<Object> getSingletons()
{
return singletons;
}
}
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<!-- Auto scan rest service -->
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.app.RestApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
The most important code which I was missing when I was getting this issue was, I was not adding my class extending javax.ws.rs.Application i.e RestApplication to the init-param of <servlet-name>resteasy-servlet</servlet-name>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.app.RestApplication</param-value>
</init-param>
And therefore my Filter was not able to execute and thus the application was not allowing CORS from the URL specified.
This is a feature, not a bug.
See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.
There isn't any built-in way to handle this (although actionpack might have a helper for that). I would advise something like this
def to_boolean(s)
s and !!s.match(/^(true|t|yes|y|1)$/i)
end
# or (as Pavling pointed out)
def to_boolean(s)
!!(s =~ /^(true|t|yes|y|1)$/i)
end
What works as well is to use 0 and non-0 instead of false/true literals:
def to_boolean(s)
!s.to_i.zero?
end
The problem is in the line,
int([x[age1]])
What you want is
x = int(age1)
You also need to convert the int to a string for the output...
print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."
The complete script looks like,
name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
x = 0
x = int(age1)
twentyone = 21 - x
print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."
You can use C#'s null coalescing operator
return accountNumber ?? string.Empty;
exponent
is a 1D array. This means that exponent[0]
is a scalar, and exponent[0][i]
is trying to access it as if it were an array.
Did you mean to say:
L = identity(len(l))
for i in xrange(len(l)):
L[i][i] = exponent[i]
or even
L = diag(exponent)
?
Static classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.
As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.
The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.
Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.
One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,
public class Foo
{
public static Foo New(string fooString)
{
ProxyGenerator generator = new ProxyGenerator();
return (Foo)generator.CreateClassProxy
(typeof(Foo), new object[] { fooString }, new Interceptor());
}
This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.
If you made it to the bottom of the list. Save some php code and just bring everything back from the DB as you need like this:
$items = Standard::find()->select(['name'])->indexBy('s_id')->column();
You can select elements with multiple classes like so:
$("element.firstClass.anotherClass");
Simply chain the next class onto the first one, without a space (spaces mean "children of").
If you have a keyboard layout that requires you to also press the shift key (i.e. cmd + shift + 7 on a German keyboard), the shortcut won't work and open the help menu, instead.
Apple's "Think Different" in its fullest extent ...
You can define your own shortcut to make it work, if you go to Xcode > Preferences > Key Bindings:
Simpler way:
if grep "$filename" my_list.txt > /dev/null
then
... found
else
... not found
fi
Tip: send to /dev/null
if you want command's exit status, but not outputs.
I met with the same error. After struggling, I found that it was due to "Space" in the folder name.
For example :
Earlier My folder name was : "Qt Projects"
Later I changed it to : "QtProjects"
and my issue was resolved.
Its very simple but sometimes a major issue.
The File
class represents the "idea" of a file, not an actual handle to use for I/O. This is why the File
class has a .exists()
method, to tell you if the file exists or not. (How can you have a File
object that doesn't exist?)
By contrast, constructing a new FileInputStream(new File("/my/file"))
gives you an actual stream to read bytes from.
MongoDB needs data directory to store data.
Default path is /data/db
When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx
permission to user.
If you want to change the path of your data directory then you should specify it while starting mongod server like,
mongod --dbpath /data/<path> --port <port no>
This should help you start your mongod server with custom path and port.
$('#slick-slider').slick('refresh'); //Working for slick 1.8.1
I had exactly the same problem and this worked for me. Add ng-model-update
and ng-keyup
and you're good to go! Here is the docs
<input type="text" name="userName"
ng-model="user.name"
ng-change="update()"
ng-model-options="{ updateOn: 'blur' }"
ng-keyup="cancel($event)" />
You don't need to use java variables. To include system env variables add the following to your application.properties
file:
spring.datasource.url = ${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/"nameofDB"
spring.datasource.username = ${OPENSHIFT_MYSQL_DB_USERNAME}
spring.datasource.password = ${OPENSHIFT_MYSQL_DB_PASSWORD}
But the way suggested by @Stefan Isele is more preferable, because in this case you have to declare just one env variable: spring.profiles.active
. Spring will read the appropriate property file automatically by application-{profile-name}.properties
template.
What you are asking is thoroughly covered by Eric Lippert in his blog post Closing over the loop variable considered harmful and its sequel.
For me, the most convincing argument is that having new variable in each iteration would be inconsistent with for(;;)
style loop. Would you expect to have a new int i
in each iteration of for (int i = 0; i < 10; i++)
?
The most common problem with this behavior is making a closure over iteration variable and it has an easy workaround:
foreach (var s in strings)
{
var s_for_closure = s;
query = query.Where(i => i.Prop == s_for_closure); // access to modified closure
My blog post about this issue: Closure over foreach variable in C#.
In my app FileProvider works just fine, and I am able to attach internal files stored in files directory to email clients like Gmail,Yahoo etc.
In my manifest as mentioned in the Android documentation I placed:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.package.name.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
And as my files were stored in the root files directory, the filepaths.xml were as follows:
<paths>
<files-path path="." name="name" />
Now in the code:
File file=new File(context.getFilesDir(),"test.txt");
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Test");
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[] {"email-address you want to send the file to"});
Uri uri = FileProvider.getUriForFile(context,"com.package.name.fileprovider",
file);
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(uri);
shareIntent .putParcelableArrayListExtra(Intent.EXTRA_STREAM,
uris);
try {
context.startActivity(Intent.createChooser(shareIntent , "Email:").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
catch(ActivityNotFoundException e) {
Toast.makeText(context,
"Sorry No email Application was found",
Toast.LENGTH_SHORT).show();
}
}
This worked for me.Hope this helps :)
As other comments here pointed out, you'll need to uncomment disable_overscan=1
in /boot/config.txt
if you are using NOOBS (this is what im using), you'll find in the end of the file a set of default settings that has disable_overscan=0
attribute. you'll need to change its value to 1, and re-boot.
Set this to False on your web.config
<compilation debug="false" targetFramework="4.6.1" />
I am using docker-compose to build the Kafka container using wurstmeister/kafka
image. Adding KAFKA_ADVERTISED_PORT: 9092
property to my docker-compose
file solved this error for me.