Use splatting.
$CurlArgument = '-u', '[email protected]:yyyy',
'-X', 'POST',
'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
'--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument
The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):
Mikhail,
The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.
Good luck with your implementation.
I resolved by removing @Basic(optional = false) property or just update boolean @Basic(optional = true)
This exists in @ManyToOne relation. I solved this issue by just using CascadeType.MERGE instead of CascadeType.PERSIST or CascadeType.ALL. Hope it helps you.
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="updated_by", referencedColumnName = "id")
private Admin admin;
Solution:
@ManyToOne(cascade = CascadeType.MERGE)
@JoinColumn(name="updated_by", referencedColumnName = "id")
private Admin admin;
Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a. C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name. Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.
For sending data to a service you can use:
Intent intent = new Intent(getApplicationContext(), YourService.class);
intent.putExtra("SomeData","ItValue");
startService(intent);
And after in service in onStartCommand() get data from intent.
For sending data or event from a service to an application (for one or more activities):
private void sendBroadcastMessage(String intentFilterName, int arg1, String extraKey) {
Intent intent = new Intent(intentFilterName);
if (arg1 != -1 && extraKey != null) {
intent.putExtra(extraKey, arg1);
}
sendBroadcast(intent);
}
This method is calling from your service. You can simply send data for your Activity.
private void someTaskInYourService(){
//For example you downloading from server 1000 files
for(int i = 0; i < 1000; i++) {
Thread.sleep(5000) // 5 seconds. Catch in try-catch block
sendBroadCastMessage(Events.UPDATE_DOWNLOADING_PROGRESSBAR, i,0,"up_download_progress");
}
For receiving an event with data, create and register method registerBroadcastReceivers() in your activity:
private void registerBroadcastReceivers(){
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int arg1 = intent.getIntExtra("up_download_progress",0);
progressBar.setProgress(arg1);
}
};
IntentFilter progressfilter = new IntentFilter(Events.UPDATE_DOWNLOADING_PROGRESS);
registerReceiver(broadcastReceiver,progressfilter);
For sending more data, you can modify method sendBroadcastMessage();
. Remember: you must register broadcasts in onResume() & unregister in onStop() methods!
UPDATE
Please don't use my type of communication between Activity & Service. This is the wrong way. For a better experience please use special libs, such us:
1) EventBus from greenrobot
2) Otto from Square Inc
P.S. I'm only using EventBus from greenrobot in my projects,
Lets say I want to start the service on an event - onItemClicked() of a button. The Receiver mechanism would not work in that case because :-
a) I passed the Receiver to the service (as in Intent extra) from onItemClicked()
b) Activity moves to the background. In onPause() I set the receiver reference within the ResultReceiver to null to avoid leaking the Activity.
c) Activity gets destroyed.
d) Activity gets created again. However at this point the Service will not be able to make a callback to the Activity as that receiver reference is lost.
The mechanism of a limited broadcast or a PendingIntent seems to be more usefull in such scenarios- refer to Notify activity from service
Let's define "object" in Javascript. According to the MDN docs, every value is either an object or a primitive:
primitive, primitive value
A data that is not an object and does not have any methods. JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined.
What's a primitive?
3
'abc'
true
null
undefined
What's an object (i.e. not a primitive)?
Object.prototype
Object.prototype
Function.prototype
Object
Function
function C(){}
-- user-defined functionsC.prototype
-- the prototype property of a user-defined function: this is not C
s prototype
new C()
-- "new"-ing a user-defined functionMath
Array.prototype
{"a": 1, "b": 2}
-- objects created using literal notationnew Number(3)
-- wrappers around primitivesObject.create(null)
Object.create(null)
How to check whether a value is an object
instanceof
by itself won't work, because it misses two cases:
// oops: isObject(Object.prototype) -> false
// oops: isObject(Object.create(null)) -> false
function isObject(val) {
return val instanceof Object;
}
typeof x === 'object'
won't work, because of false positives (null
) and false negatives (functions):
// oops: isObject(Object) -> false
function isObject(val) {
return (typeof val === 'object');
}
Object.prototype.toString.call
won't work, because of false positives for all of the primitives:
> Object.prototype.toString.call(3)
"[object Number]"
> Object.prototype.toString.call(new Number(3))
"[object Number]"
So I use:
function isObject(val) {
if (val === null) { return false;}
return ( (typeof val === 'function') || (typeof val === 'object') );
}
@Daan's answer also seems to work:
function isObject(obj) {
return obj === Object(obj);
}
because, according to the MDN docs:
The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object, otherwise, it will return an object of a type that corresponds to the given value. If the value is an object already, it will return the value.
A third way that seems to work (not sure if it's 100%) is to use Object.getPrototypeOf
which throws an exception if its argument isn't an object:
// these 5 examples throw exceptions
Object.getPrototypeOf(null)
Object.getPrototypeOf(undefined)
Object.getPrototypeOf(3)
Object.getPrototypeOf('abc')
Object.getPrototypeOf(true)
// these 5 examples don't throw exceptions
Object.getPrototypeOf(Object)
Object.getPrototypeOf(Object.prototype)
Object.getPrototypeOf(Object.create(null))
Object.getPrototypeOf([])
Object.getPrototypeOf({})
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));
//Output : C
items.forEach(item->{
System.out.println(item);
System.out.println(item.toLowerCase());
}
});
I found a great code for you:
HTML
<form class="form-wrapper cf">
<input type="text" placeholder="Search here..." required>
<button type="submit">Search</button>
</form>
CSS
/*Clearing Floats*/
.cf:before, .cf:after {
content:"";
display:table;
}
.cf:after {
clear:both;
}
.cf {
zoom:1;
}
/* Form wrapper styling */
.form-wrapper {
width: 450px;
padding: 15px;
margin: 150px auto 50px auto;
background: #444;
background: rgba(0,0,0,.2);
border-radius: 10px;
box-shadow: 0 1px 1px rgba(0,0,0,.4) inset, 0 1px 0 rgba(255,255,255,.2);
}
/* Form text input */
.form-wrapper input {
width: 330px;
height: 20px;
padding: 10px 5px;
float: left;
font: bold 15px 'lucida sans', 'trebuchet MS', 'Tahoma';
border: 0;
background: #eee;
border-radius: 3px 0 0 3px;
}
.form-wrapper input:focus {
outline: 0;
background: #fff;
box-shadow: 0 0 2px rgba(0,0,0,.8) inset;
}
.form-wrapper input::-webkit-input-placeholder {
color: #999;
font-weight: normal;
font-style: italic;
}
.form-wrapper input:-moz-placeholder {
color: #999;
font-weight: normal;
font-style: italic;
}
.form-wrapper input:-ms-input-placeholder {
color: #999;
font-weight: normal;
font-style: italic;
}
/* Form submit button */
.form-wrapper button {
overflow: visible;
position: relative;
float: right;
border: 0;
padding: 0;
cursor: pointer;
height: 40px;
width: 110px;
font: bold 15px/40px 'lucida sans', 'trebuchet MS', 'Tahoma';
color: #fff;
text-transform: uppercase;
background: #d83c3c;
border-radius: 0 3px 3px 0;
text-shadow: 0 -1px 0 rgba(0, 0 ,0, .3);
}
.form-wrapper button:hover {
background: #e54040;
}
.form-wrapper button:active,
.form-wrapper button:focus {
background: #c42f2f;
outline: 0;
}
.form-wrapper button:before { /* left arrow */
content: '';
position: absolute;
border-width: 8px 8px 8px 0;
border-style: solid solid solid none;
border-color: transparent #d83c3c transparent;
top: 12px;
left: -6px;
}
.form-wrapper button:hover:before {
border-right-color: #e54040;
}
.form-wrapper button:focus:before,
.form-wrapper button:active:before {
border-right-color: #c42f2f;
}
.form-wrapper button::-moz-focus-inner { /* remove extra button spacing for Mozilla Firefox */
border: 0;
padding: 0;
}
Laravel 5.8 Step 1: Go to the path routes/api.php add: Route::post('welcome/login', 'WelcomeController@login')->name('welcome.login'); Step2: Go to the path file view
<form method="POST" action="{{ route('welcome.login') }}">
</form>
Result html
<form method="POST" action="http://localhost/api/welcome/login">
<form>
In Manifest theme sets with style name (AppTheme and myDialog)/ You can set new styles in styles.xml
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyActivity2"
android:label="@string/title_activity_my_activity2"
android:theme="@style/myDialog"
>
</activity>
</application>
styles.xml example
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Black">
<!-- Customize your theme here. -->
</style>
<style name="myDialog" parent="android:Theme.Dialog">
</style>
In parent you set actualy the theme
You can do this simply by using pandas drop duplicates function
df.drop_duplicates(['A','B'],keep= 'last')
In my opinion FirstOrDefault
is being overused a lot. In the majority of the cases when you’re filtering data you would either expect to get back a collection of elements matching the logical condition or a single unique element by its unique identifier – such as a user, book, post etc... That’s why we can even get as far as saying that FirstOrDefault()
is a code smell not because there is something wrong with it but because it’s being used way too often. This blog post explores the topic in details. IMO most of the times SingleOrDefault()
is a much better alternative so watch out for this mistake and make sure you use the most appropriate method that clearly represents your contract and expectations.
from the terminal type:-
aws configure
then fill in your keys and region.
after this do next step use any environment. You can have multiple keys depending your account. Can manage multiple enviroment or keys
import boto3
aws_session = boto3.Session(profile_name="prod")
# Create an S3 client
s3 = aws_session.client('s3')
Github is required if you want to collaborate across developers. If you are a single contributor git is enough, make sure you backup your code on regular basis
Consider Approach 1 with reshape method and Approach 2 with np.newaxis method that produce the same outcome:
#Lets suppose, we have:
x = [1,2,3,4,5,6,7,8,9]
print('I. x',x)
xNpArr = np.array(x)
print('II. xNpArr',xNpArr)
print('III. xNpArr', xNpArr.shape)
xNpArr_3x3 = xNpArr.reshape((3,3))
print('IV. xNpArr_3x3.shape', xNpArr_3x3.shape)
print('V. xNpArr_3x3', xNpArr_3x3)
#Approach 1 with reshape method
xNpArrRs_1x3x3x1 = xNpArr_3x3.reshape((1,3,3,1))
print('VI. xNpArrRs_1x3x3x1.shape', xNpArrRs_1x3x3x1.shape)
print('VII. xNpArrRs_1x3x3x1', xNpArrRs_1x3x3x1)
#Approach 2 with np.newaxis method
xNpArrNa_1x3x3x1 = xNpArr_3x3[np.newaxis, ..., np.newaxis]
print('VIII. xNpArrNa_1x3x3x1.shape', xNpArrNa_1x3x3x1.shape)
print('IX. xNpArrNa_1x3x3x1', xNpArrNa_1x3x3x1)
We have as outcome:
I. x [1, 2, 3, 4, 5, 6, 7, 8, 9]
II. xNpArr [1 2 3 4 5 6 7 8 9]
III. xNpArr (9,)
IV. xNpArr_3x3.shape (3, 3)
V. xNpArr_3x3 [[1 2 3]
[4 5 6]
[7 8 9]]
VI. xNpArrRs_1x3x3x1.shape (1, 3, 3, 1)
VII. xNpArrRs_1x3x3x1 [[[[1]
[2]
[3]]
[[4]
[5]
[6]]
[[7]
[8]
[9]]]]
VIII. xNpArrNa_1x3x3x1.shape (1, 3, 3, 1)
IX. xNpArrNa_1x3x3x1 [[[[1]
[2]
[3]]
[[4]
[5]
[6]]
[[7]
[8]
[9]]]]
Am I missing something? Somebody correct me if I'm wrong.
list.RemoveAll(s => s.Name == "Fred");
MultipleIE , IETester there are many similar to those.
Multiple IE supports IE3 IE4.01 IE5 IE5.5 and IE6 and "is no longer maintained and there are no plans to continue maintaining it! Thanks and good luck!".
IETester seems a better choice : IE10, IE9, IE8, IE7 IE 6 and IE5.5 on Windows 8 desktop, Windows 7, Vista and XP
You can use "translateX(-100%)" and "text-align: right" if your absolute element is "display: inline-block"
<div class="box">
<div class="absolute-right"></div>
</div>
<style type="text/css">
.box{
text-align: right;
}
.absolute-right{
display: inline-block;
position: absolute;
}
/*The magic:*/
.absolute-right{
-moz-transform: translateX(-100%);
-ms-transform: translateX(-100%);
-webkit-transform: translateX(-100%);
-o-transform: translateX(-100%);
transform: translateX(-100%);
}
</style>
You will get absolute-element aligned to the right relative its parent
As you set application/x-www-form-urlencoded
as content type so data sent must be like this format.
String urlParameters = "param1=data1¶m2=data2¶m3=data3";
Sending part now is quite straightforward.
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "<Url here>";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength ));
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write( postData );
}
Or you can create a generic method to build key value pattern which is required for application/x-www-form-urlencoded
.
private String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
EDIT: This answer was correct until mid-2013, but you may have a more recent version since the big msbuild change. See the answer from Jonny Leeds for more details.
The version under C:\Windows\Microsoft.NET\Framework\v4.0.30319
actually is .NET 4.5. It's a little odd, but certainly mscorlib
there contains AsyncTaskMethodBuilder
etc which are used for async.
.NET 4.5 effectively overwrites .NET 4.
To see your log in SQL Developer
then press:
CTRL+SHIFT + L (or CTRL + CMD + L on macOS)
or
View -> Log
or by using mysql query
show errors;
A broader answer to this question might consider the Lego brick approach often used in Occam, and offered to the Java community via JCSP. There is a very good presentation by Peter Welch on this idea.
This plug-and-play approach translates directly to Go, because Go uses the same Communicating Sequential Process fundamentals as does Occam.
So, when it comes to designing repetitive tasks, you can build your system as a dataflow network of simple components (as goroutines) that exchange events (i.e. messages or signals) via channels.
This approach is compositional: each group of small components can itself behave as a larger component, ad infinitum. This can be very powerful because complex concurrent systems are made from easy to understand bricks.
Footnote: in Welch's presentation, he uses the Occam syntax for channels, which is ! and ? and these directly correspond to ch<- and <-ch in Go.
RTM
From the docs for the Python random
module:
Functions for integers:
random.randrange(stop)
random.randrange(start, stop[, step])
Return a randomly selected element from range(start, stop, step).
This is equivalent to choice(range(start, stop, step)), but doesn’t
actually build a range object.
That explains why it only gives you 0, doesn't it. range(0,1)
is [0]
. It is choosing from a list consisting of only that value.
Also from those docs:
random.random()
Return the next random floating point number in the range [0.0, 1.0).
But if your inclusion of the numpy
tag is intentional, you can generate many random floats in that range with one call using a np.random
function.
That example is pretty vague, but maybe something like this?
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]
It basically does a splice (or assignment to a slice) operation. It removes items 3 to 6 and inserts a new list in their place (in this case a list with one item, which is the concatenation of the three items that were removed.)
For any type of list, you could do this (using the +
operator on all items no matter what their type is):
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [reduce(lambda x, y: x + y, items[3:6])]
This makes use of the reduce
function with a lambda
function that basically adds the items together using the +
operator.
I have a similar solution to @Satheesh using React hooks:
State initialization:
const [enteredText, setEnteredText] = useState('');
Input tag:
<input type="text" value={enteredText} (event handler, classNames, etc.) />
Inside the event handler function, after updating the object with data from input form, call:
setEnteredText('');
Note: This is described as 'two-way binding'
If you have GNU extensions, you can use sed's \L (lower entire match, or until \L [lower] or \E [end - toggle casing off] is reached), like so:
sed 's/.*/\L&/' <input >output
Note: '&' means the full match pattern.
As a side note, GNU extensions include \U (upper), \u (upper next character of match), \l (lower next character of match). For example, if you wanted to camelcase a sentence:
$ sed -r 's/\w+/\u&/g' <<< "Now is the time for all good men..." # Camel Case
Now Is The Time For All Good Men...
Note: Since the assumption is we have GNU extensions, we can also use the dash-r (extended regular expressions) option, which allows \w (word character) and relieves you of having to escape the capturing parenthesis and one-or-more quantifier (+). (Aside: \W [non-word], \s [whitespace], \S [non-whitespace]
are also supported with dash-r, but \d [digit]
and \D [non-digit]
are not.)
Ctrl+T in Visual Studio 2017.
Using recursion and walrus operator:
def prime_factors(n):
for i in range(2, int(n ** 0.5) + 1):
if (q_r := divmod(n, i))[1] == 0:
return [i] + factor_list(q_r[0])
return [n]
Without your actual data or source, it will be hard for us to diagnose what is going wrong. However, I can make a few suggestions:
Given what you wrote, I suspect whatever converts the database data to XML is broken; it's propagating non-XML characters.
Create some database entries with non-XML characters (NULs, DELs, control characters, et al.) and run your XML converter on it. Output the XML to a file and look at it in a hex editor. If this contains non-XML characters, your converter is broken. Fix it or, if you cannot, create a preprocessor that rejects output with such characters.
If the converter output looks good, the problem is in your XML consumer; it's inserting non-XML characters somewhere. You will have to break your consumption process into separate steps, examine the output at each step, and narrow down what is introducing the bad characters.
Update: I just ran into an example of this myself! What was happening is that the producer was encoding the XML as UTF16 and the consumer was expecting UTF8. Since UTF16 uses 0x00 as the high byte for all ASCII characters and UTF8 doesn't, the consumer was seeing every second byte as a NUL. In my case I could change encoding, but suggested all XML payloads start with a BOM.
I have a simple idea, something like this:
#!/bin/sh
echo `xrandr --current | grep current | awk '{print $8}'` >> RES1
echo `xrandr --current | grep current | awk '{print $10}'` >> RES2
cat RES2 | sed -i 's/,//g' RES2
P1RES=$(cat RES1)
P2RES=$(cat RES2)
rm RES1 RES2
echo "$P1RES"'x'"$P2RES" >> RES
RES=$(cat RES)
# Play The Game
# Finish The Game with Lower Resolution
xrandr -s $RES
Well, I need a better solution for all display devices under Linux and Similars S.O
That would violate object oriented principles. I'd say an elegant solution here and elsewhere in the project is using a object mapping framework like AutoMapper to configure a projection.
Here's a slighty more complex configuration than is neccessary but is flexible enough for most cases:
public class BaseToChildMappingProfile : Profile
{
public override string ProfileName
{
get { return "BaseToChildMappingProfile"; }
}
protected override void Configure()
{
Mapper.CreateMap<BaseClass, ChildClassOne>();
Mapper.CreateMap<BaseClass, ChildClassTwo>();
}
}
public class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(x =>
{
x.AddProfile<BaseToChildMappingProfile>();
});
}
}
When application starts call AutoMapperConfiguration.Configure()
and then you can project like this:
ChildClassOne child = Mapper.Map<BaseClass, ChildClassOne>(baseClass);
Properties are mapped by convention so if the class is inherited the property names are exactly the same and mapping is configured automatically. You can add additional properties by tweaking the configuration. See the documentation .
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
The file format would permit up to 255-character worksheet names, but if the Excel UI doesn't want you exceeding 31 characters, don't try to go beyond 31. App's full of weird undocumented limits and quirks, and feeding it files that are within spec but not within the range of things the testers would have tested usually causes REALLY strange behavior. (Personal favorite example: using the Excel 4.0 bytecode for an if() function, in a file with an Excel 97-style stringtable, disabled the toolbar button for bold in Excel 97.)
As I commented you need to use a StringIO object and decode i.e c=pd.read_csv(io.StringIO(s.decode("utf-8")))
if using requests, you need to decode as .content returns bytes if you used .text you would just need to pass s as is s = requests.get(url).text
c = pd.read_csv(StringIO(s))
.
A simpler approach is to pass the correct url of the raw data directly to read_csv
, you don't have to pass a file like object, you can pass a url so you don't need requests at all:
c = pd.read_csv("https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv")
print(c)
Output:
Country Region
0 Algeria AFRICA
1 Angola AFRICA
2 Benin AFRICA
3 Botswana AFRICA
4 Burkina AFRICA
5 Burundi AFRICA
6 Cameroon AFRICA
..................................
From the docs:
filepath_or_buffer :
string or file handle / StringIO The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be file ://localhost/path/to/table.csv
System: Ubuntu 16.04 LTS, yet you can try these steps in accordance to your respective systems.
If there is an SDK file present, it should be most likely found at /home/USERNAME/Android/sdk
USERNAME
is to be replaced by your username
If there is none, check the specified sdk path for the project in android studio.
File > Project Structure > sdk path
The sdk directory should be present in the specified path. In case, it is not there, open the file:
PROJECT_DIRECTORY/android/local.properties
PROJECT_DIRECTORY
needs to be replaced by your project name.
If the file is not there, create it. Then add the following line depending on where you find the sdk directory.
If sdk is there at /home/USERNAME/Android/
:
add the line: sdk.dir = /home/tanya/Android/sdk
If sdk is not there at /home/USERNAME/Android/
:
add the line: sdk.dir = /home/tanya/Android/
If the path specified for sdk directory in 'Project Structure' is entirely different and the sdk directory is present at the specified location,
add the line: sdk.dir = SPECIFIED_SDK_PATH
Add the specified sdk path in place of SPECIFIED_SDK_PATH
The correct solution to get the Prompt
value in a non-templated control context is:
@Html.TextBoxFor(model => model.Email,
new { placeholder = ModelMetadata.FromLambdaExpression(m => m.Email, ViewData).Watermark }
)
This will also not double-escape the watermark text.
Big O notation is a way of describing the upper bound of an algorithm in terms of space or running time. The n is the number of elements in the the problem (i.e size of an array, number of nodes in a tree, etc.) We are interested in describing the running time as n gets big.
When we say some algorithm is O(f(n)) we are saying that the running time (or space required) by that algorithm is always lower than some constant times f(n).
To say that binary search has a running time of O(logn) is to say that there exists some constant c which you can multiply log(n) by that will always be larger than the running time of binary search. In this case you will always have some constant factor of log(n) comparisons.
In other words where g(n) is the running time of your algorithm, we say that g(n) = O(f(n)) when g(n) <= c*f(n) when n > k, where c and k are some constants.
above solutions are very true...but the UI dialog does not retain the position after window is resized. below code does this
$(document).ready(function(){
$(".test").click(function(){
var posX = $(".test").offset().left - $(document).scrollLeft() + $(".test").outerWidth();
var posY = $(".test").offset().top - $(document).scrollTop() + $(".test").outerHeight();
console.log("in click function");
$(".abc").dialog({
position:[posX,posY]
});
})
})
$(window).resize(function(){
var posX=$(".test").offset().left - $(document).scrollLeft() + $(".test").outerWidth();
var posY = $(".test").offset().top - $(document).scrollTop() + $(".test").outerHeight();
$(".abc").dialog({
position:[posX,posY]
});
})
np.fromfile()
has a sep=
keyword argument:
Separator between items if file is a text file. Empty (“”) separator means the file should be treated as binary. Spaces (” ”) in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace.
The default value of sep=""
means that np.fromfile()
tries to read it as a binary file rather than a space-separated text file, so you get nonsense values back. If you use np.fromfile('markers.txt', sep=" ")
you will get the result you are looking for.
However, as others have pointed out, np.loadtxt()
is the preferred way to convert text files to numpy arrays, and unless the file needs to be human-readable it is usually better to use binary formats instead (e.g. np.load()
/np.save()
).
This code creates a nice vertical scrollbar for me in Firefox and Chrome:
#answerform {
position: absolute;
border: 5px solid gray;
padding: 5px;
background: white;
width: 300px;
height: 400px;
overflow-y: scroll;
}
_x000D_
<div id='answerform'>
badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br> mushroom
<br><br>mushroom<br><br> a badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br>
</div>
_x000D_
Here is a JS fiddle demo proving the above works.
Just do: document.getElementById('idselect').options.selectedIndex
Then you i'll get select index value, starting in 0.
I agree with Aamir that the submission arrow.m from Erik Johnson on the MathWorks File Exchange is a very nice option. You can use it to illustrate the different methods of vector addition like so:
Tip-to-tail method:
o = [0 0 0]; %# Origin
a = [2 3 5]; %# Vector 1
b = [1 1 0]; %# Vector 2
c = a+b; %# Resultant
arrowStarts = [o; a; o]; %# Starting points for arrows
arrowEnds = [a; c; c]; %# Ending points for arrows
arrow(arrowStarts,arrowEnds); %# Plot arrows
Parallelogram method:
o = [0 0 0]; %# Origin
a = [2 3 5]; %# Vector 1
b = [1 1 0]; %# Vector 2
c = a+b; %# Resultant
arrowStarts = [o; o; o]; %# Starting points for arrows
arrowEnds = [a; b; c]; %# Ending points for arrows
arrow(arrowStarts,arrowEnds); %# Plot arrows
hold on;
lineX = [a(1) b(1); c(1) c(1)]; %# X data for lines
lineY = [a(2) b(2); c(2) c(2)]; %# Y data for lines
lineZ = [a(3) b(3); c(3) c(3)]; %# Z data for lines
line(lineX,lineY,lineZ,'Color','k','LineStyle',':'); %# Plot lines
You can create spinner by these simple steps
first create spinner in xml
<Spinner
android:id="@+id/select"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#070707"></Spinner>
now create string arary in values
<string-array name="itemselect">
<item>Repurchase</item>
<item>Coupons</item>
</string-array>
now initialized in java file
public class MemberCart_Activity extends AppCompatActivity {
Spinner select;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member_cart);
select=findViewById(R.id.select);
ArrayAdapter<String> myadapter=new ArrayAdapter<String>(Main_Activity.this,android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.itemselect));
myadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
select.setAdapter(myadapter);
If you don't want or cannot use ArrayList, then there is a utility method:
Arrays.copyOf()
that will allow you to specify new size, while preserving the elements.
Try this.. credits to https://stackoverflow.com/users/1169519/teemu
for answering my question here: https://stackoverflow.com/questions/24651811/jquery-keyup-doesnt-work-with-keycode-filtering?noredirect=1#comment38213480_24651811
This solution helped me to progress on my project.
$("#your_textbox").on("input propertychange",function(){
// Do your thing here.
});
Note: propertychange for lower versions of IE.
I usually use the -p
flag with a git checkout from the other branch which I find easier and more granular than most other methods I have come across.
In principle:
git checkout <other_branch_name> <files/to/grab in/list/separated/by/spaces> -p
example:
git checkout mybranch config/important.yml app/models/important.rb -p
You then get a dialog asking you which changes you want in "blobs" this pretty much works out to every chunk of continuous code change which you can then signal y
(Yes) n
(No) etc for each chunk of code.
The -p
or patch
option works for a variety of commands in git including git stash save -p
which allows you to choose what you want to stash from your current work
I sometimes use this technique when I have done a lot of work and would like to separate it out and commit in more topic based commits using git add -p
and choosing what I want for each commit :)
This is something I wrote a few minutes ago just messing around. Hope it helps!
public class Main {
public static void main(String[] args) {
ArrayList<Integer> powers = new ArrayList<Integer>();
ArrayList<Integer> binaryStore = new ArrayList<Integer>();
powers.add(128);
powers.add(64);
powers.add(32);
powers.add(16);
powers.add(8);
powers.add(4);
powers.add(2);
powers.add(1);
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Paden9000 binary converter. Please enter an integer you wish to convert: ");
int input = sc.nextInt();
int printableInput = input;
for (int i : powers) {
if (input < i) {
binaryStore.add(0);
} else {
input = input - i;
binaryStore.add(1);
}
}
String newString= binaryStore.toString();
String finalOutput = newString.replace("[", "")
.replace(" ", "")
.replace("]", "")
.replace(",", "");
System.out.println("Integer value: " + printableInput + "\nBinary value: " + finalOutput);
sc.close();
}
}
So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.
The basic idea is to signal the reader to split on the carriage character "\n"
(or "\r\n"
for Windows). Python can do this with the file.readline()
function.
import json
def json_reader(filename):
with open(filename) as f:
for line in f:
yield json.loads(line)
However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.
def json_writer(file, json_objects):
with open(file, "w") as f:
for jsonobj in json_objects:
jsonstr = json.dumps(jsonobj)
f.write(jsonstr + "\n")
You could also do the same operation with file.writelines()
and a list comprehension:
...
json_strs = [json.dumps(j) + "\n" for j in json_objects]
f.writelines(json_strs)
...
And if you wanted to append the data instead of writing a new file just change open(file, "w")
to open(file, "a")
.
In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.
On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write
lst = list(json_reader(file))
I had a similar issue where I was getting an error for a member in the class that wasn't mapped to the db column, it was just a holder for a List of another entity. I changed List to ArrayList and the error went away. I know, I really shouldn't do that in a mapped entity, and that's what DTO's are for. Just wanted to share in case someone finds this thread and the answers above don't apply or help.
Here is what I did to solve just by 2 ways:
make ID column as int
type
if you are using autogenerate in ID dont assing value in the setter of ID. If your mapping the some then sometimes autogenetated ID is not concedered. (I dont know why)
try using @GeneratedValue(strategy=GenerationType.SEQUENCE)
if possible
(Windows) If you have already installed MySQL server
cd C:\Program Files\MySQL\MySQL Server X.X\bin
mysqld --install
and still cannot connect, then the service did not start automatically. Just try
Start > Search "services"
and scroll down until you see "MySQLXX", where the XX represents the MySQL Server version. If the Status isn't "Started", then
Right Click > Start
Set the horizontalPolicy & VerticalPolicy for the controls/widgets to "Preferred".
.h1 {
width: -moz-fit-content;
width: fit-content;
// workaround for IE11
display: table;
}
All modern browsers support width: fit-content
for that.
For IE11 we could emulate this behavior with display: table
which doesn't break margin collapse like display: inline-block
or float: left
.
I also faced the same issue with a self signed certificate . By referring to few of the above solutions , i tried regenerating the certificate with the correct CN i.e the IP Address of the server .But still it didn't work for me . Finally i tried regenerating the certificate by adding the SAN address to it via the below mentioned command
**keytool -genkey -keyalg RSA -keystore keystore.jks -keysize 2048 -alias <IP_ADDRESS> -ext san=ip:<IP_ADDRESS>**
After that i started my server and downloaded the client certificates via the below mentioned openssl command
**openssl s_client -showcerts -connect <IP_ADDRESS>:443 < /dev/null | openssl x509 -outform PEM > myCert.pem**
Then i imported this client certificate to the java default keystore file (cacerts) of my client machine by the below mentioned command
**keytool -import -trustcacerts -keystore /home/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.242.b08-1.el7.x86_64/jre/lib/security/cacerts -alias <IP_ADDRESS> -file ./mycert.pem**
If you deleted a branch via Source Tree
, you could easily find the SHA1 of the deleted branch by going to View -> Show Command History
.
It should have the next format:
Deleting branch ...
...
Deleted branch %NAME% (was %SHA1%)
...
Then just follow the original answer.
git branch branchName <sha1>
One of the way is Using below sql queries
--Size of All Table Space
--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME
--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)", FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);
This shows the number of connections per each DB:
SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName
FROM
sys.sysprocesses
WHERE
dbid > 0
GROUP BY
dbid, loginame
And this gives the total:
SELECT
COUNT(dbid) as TotalConnections
FROM
sys.sysprocesses
WHERE
dbid > 0
If you need more detail, run:
sp_who2 'Active'
Note: The SQL Server account used needs the 'sysadmin' role (otherwise it will just show a single row and a count of 1 as the result)
If you're willing to remove the brew
dependency, I would recommend nvm - I can't really recommend it over any other versioning solution because I haven't needed to try anything else. Having the ability to switch instantly between versions depending on which project you're working on is pretty valuable.
It would seem that is.nan
doesn't actually have a method for data frames, unlike is.na
. So, let's fix that!
is.nan.data.frame <- function(x)
do.call(cbind, lapply(x, is.nan))
data123[is.nan(data123)] <- 0
Select * from emp where joindate between date1 and date2;
But this query not show proper data.
Eg
1-jan-2013 to 12-jan-2013.
But it's show data
1-jan-2013 to 11-jan-2013.
new_list = [word_in_list + end_string for word_in_list in old_list]
Using names such as "list" for your variable names is bad since it will overwrite/override the builtins.
Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)
Once you've generated your JSON, you can use something like the code below to POST it
StringRequestEntity requestEntity = new StringRequestEntity(
JSON_STRING,
"application/json",
"UTF-8");
PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpClient.executeMethod(postMethod);
Edit
Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:
StringEntity requestEntity = new StringEntity(
JSON_STRING,
ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);
HttpResponse rawResponse = httpclient.execute(postMethod);
To avoid the array wrapper, remove it before you return the response:
import json
from django.core import serializers
def getObject(request, id):
obj = MyModel.objects.get(pk=id)
data = serializers.serialize('json', [obj,])
struct = json.loads(data)
data = json.dumps(struct[0])
return HttpResponse(data, mimetype='application/json')
I found this interesting post on the subject too:
http://timsaylor.com/convert-django-model-instances-to-dictionaries
It uses django.forms.models.model_to_dict, which looks like the perfect tool for the job.
function aecho {
set "$1[$2]"
echo "${!1}"
}
Example
$ foo=(dog cat bird)
$ aecho foo 1
cat
Just wanted to add to an old thread to hopefully aid other people. I needed programmatically add a cert to the firefox database using a GPO, this was how I did it for Windows
1, First download and unzip the precompiled firefox NSS nss-3.13.5-nspr-4.9.1-compiled-x86.zip
2, Add the cert manually to firefox Options-->Advanced--Certificates-->Authorities-->Import
3, from the downloaded NSS package, run
certutil -L -d c:\users\[username]\appdata\roaming\mozilla\firefox\[profile].default
4, The above query will show you the certificate name and Trust Attributes e.g.
my company Ltd CT,C,C
5, Delete the certificate in step 2. Options-->Advanced--Certificates-->Authorities-->Delete
6, Create a powershell script using the information from step 4 as follows. This script will get the users profile path and add the certificate. This only works if the user has one firefox profile (need somehow to retrieve the users firefox folder profile name)
#Script adds Radius Certificate to independent Firefox certificate store since the browser does not use the Windows built in certificate store
#Get Firefox profile cert8.db file from users windows profile path
$ProfilePath = "C:\Users\" + $env:username + "\AppData\Roaming\Mozilla\Firefox\Profiles\"
$ProfilePath = $ProfilePath + (Get-ChildItem $ProfilePath | ForEach-Object { $_.Name }).ToString()
#Update firefox cert8.db file with Radius Certificate
certutil -A -n "UK my company" -t "CT,C,C" -i CertNameToAdd.crt -d $ProfilePath
7, Create GPO as a User Configuration to run the PowerShell script
Hope that helps save someone time
I got this error while attempting to install composer using php cli on Windows. To solve it, I just needed to change the extension directory in php.ini
. I had to uncomment this line:
; On windows:
extension_dir = "ext"
Then this one and all things worked
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;
;...
extension=openssl
When you set keys (primary or foreign) you are setting constraints on how they can be used, which in turn limits what you can do with them. If you really want to alter the column, you could re-create the table without the constraints, although I'd recommend against it. Generally speaking, if you have a situation in which you want to do something, but it is blocked by a constraint, it's best resolved by changing what you want to do rather than the constraint.
read -p "Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
# do dangerous stuff
fi
I incorporated levislevis85's suggestion (thanks!) and added the -n
option to read
to accept one character without the need to press Enter. You can use one or both of these.
Also, the negated form might look like this:
read -p "Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 # handle exits from shell or function but don't exit interactive shell
fi
However, as pointed out by Erich, under some circumstances such as a syntax error caused by the script being run in the wrong shell, the negated form could allow the script to continue to the "dangerous stuff". The failure mode should favor the safest outcome so only the first, non-negated if
should be used.
The read
command outputs the prompt (-p "prompt"
) then accepts one character (-n 1
) and accepts backslashes literally (-r
) (otherwise read
would see the backslash as an escape and wait for a second character). The default variable for read
to store the result in is $REPLY
if you don't supply a name like this: read -p "my prompt" -n 1 -r my_var
The if
statement uses a regular expression to check if the character in $REPLY
matches (=~
) an upper or lower case "Y". The regular expression used here says "a string starting (^
) and consisting solely of one of a list of characters in a bracket expression ([Yy]
) and ending ($
)". The anchors (^
and $
) prevent matching longer strings. In this case they help reinforce the one-character limit set in the read
command.
The negated form uses the logical "not" operator (!
) to match (=~
) any character that is not "Y" or "y". An alternative way to express this is less readable and doesn't as clearly express the intent in my opinion in this instance. However, this is what it would look like: if [[ $REPLY =~ ^[^Yy]$ ]]
Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this
<category name="org.springframework.beans">
<priority value="debug" />
</category>
or
<category name="org.springframework">
<priority value="debug" />
</category>
I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest
{
@Autowired
private SpringDAO dao;
@Autowired
private ApplicationContext appContext;
@Test
public void checkConfig()
{
AnySpringBean bean = appContext.getBean(AnySpringBean.class);
Assert.assertNotNull(bean);
}
}
I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
UPDATE log4j config file
I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
</layout>
</appender>
<appender name="springAppender" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="C:/tomcatLogs/webApp/spring-details.log" />
<param name="append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{MM/dd/yyyy HH:mm:ss} [%t]:%c{5}.%M()%L %m%n" />
</layout>
</appender>
<category name="org.springframework">
<priority value="debug" />
</category>
<category name="org.springframework.beans">
<priority value="debug" />
</category>
<category name="org.springframework.security">
<priority value="debug" />
</category>
<category
name="org.springframework.beans.CachedIntrospectionResults">
<priority value="debug" />
</category>
<category name="org.springframework.jdbc.core">
<priority value="debug" />
</category>
<category name="org.springframework.transaction.support.TransactionSynchronizationManager">
<priority value="debug" />
</category>
<root>
<priority value="debug" />
<appender-ref ref="springAppender" />
<!-- <appender-ref ref="STDOUT"/> -->
</root>
</log4j:configuration>
I had a similar problem, I had created a DLL, i.e., A.dll, which referenced other DLL, i.e., B.dll.
I created an application C.exe and referenced DLLs A.dll and B.dll.
Solution - On removing the reference of B.dll from c.exe I was able to fix the issue.
Hope this helps.
You simply need to use semilogy instead of plot:
from pylab import *
import matplotlib.pyplot as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)
line, = ax.semilogy(a, color='blue', lw=2)
show()
This query works for me:
SELECT DISTINCT
local_tcp_port
FROM sys.dm_exec_connections
WHERE local_tcp_port IS NOT NULL
WARNING: Do not run this on a production machine.
On a Linux box:
redis-cli KEYS "*" | wc -l
Note: As mentioned in comments below, this is an O(N) operation, so on a large DB with many keys you should not use this. For smaller deployments, it should be fine.
No you can't set them as single one for example if you have div{ border-top: 2px solid red; border-right: 2px solid red; border-bottom: 2px solid red; border-left: 2px solid red; } same properties for all fours then you can set them in single line
div{border:2px solid red;}
You're almost there. Use the following regex (with multi-line option enabled)
\bObject Name:\s+(.*)$
The complete match would be
Object Name: D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log
while the captured group one would contain
D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log
If you want to capture the file path directly use
(?m)(?<=\bObject Name:).*$
in
operatorThis question age is about 10 years and it is surprising that nobody mention about this yet - however some people see the problem when we use delete
operator (e.g here). This is also a little bit counter intuitive solution but the in
operator which works in 'object world' can also work with arrays (because we can look on array indexes like on 'keys'...). In this way we can detect and distinct between undefined
array value and value (index) removed by delete
if(index in arrayName) {
// do stuff
}
let arr = [0, 1, 2, 3, null, undefined,6]
delete arr[2]; // we delete element at index=2
if(2 in arr) console.log('You will not see this because idx 2 was deleted');
if(5 in arr) console.log('This is element arr[5]:', arr[5]);
// Whole array and indexes bigger than arr.length:
for(let i=0; i<=9; i++) {
let val = (i in arr) ? arr[i] : 'empty'
let bound = i<arr.length ? '' : '(out of range)'
console.log(`${i} value: `, val, bound);
}
console.log('Look on below aray on chrome console (not in SO snippet console)');
console.log('typeof arr:', typeof arr);
console.log(arr);
_x000D_
Chrome console reveals some info about snippet array with deleted index 2 - this index actually not exists at all (!!!) (same way as key is removed from object). What is also interesting here array is viewd as key-value pairs (we even see 'length' key). It is also interesting that typeof arr
is Object (!!!), the delete
and in
operator works like for JS objects
(also square brackets notation arr[idx]
and obj[key]
is similar) - so it looks like array is some special JS object in the core.
To get similar effect without delete
define array as follows
[0, 1,, 3, null, undefined, 6] // pay attention to double comma: ",,"
No one has explicitly mentioned that weightSum
is a particular XML attribute for LinearLayout
.
I believe this would be helpful to anyone who was confused at first as I was, looking for weightSum
in the ConstraintLayout
documentation.
Ok for all of you out there that arrived here in desperation searching for the same problem. I hope you will find this quicker then I did ;O.
This is how it is solved. JoostK told me at github that "the first argument to join is the table (or data) you're joining.". And he was right.
Here is the code. Different table and names but you will get the idea right? It t
DB::table('users')
->select('first_name', 'TotalCatches.*')
->join(DB::raw('(SELECT user_id, COUNT(user_id) TotalCatch,
DATEDIFF(NOW(), MIN(created_at)) Days,
COUNT(user_id)/DATEDIFF(NOW(), MIN(created_at))
CatchesPerDay FROM `catch-text` GROUP BY user_id)
TotalCatches'),
function($join)
{
$join->on('users.id', '=', 'TotalCatches.user_id');
})
->orderBy('TotalCatches.CatchesPerDay', 'DESC')
->get();
Here's what I had to do to get this working. This means:
My site is managed through DotNetPanel. It has 3 security options for virtual directories:
Only "Allow Anonymous Access" is needed (although, that, by itself wasn't enough).
Setting
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
Didn't make a difference in my case.
However, using this binding worked:
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="Windows" />
<message clientCredentialType="UserName" />
</security>
I do some quick tests and have the following findings:
1) if using SynchronousQueue:
After the threads reach the maximum size, any new work will be rejected with the exception like below.
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@3fee733d rejected from java.util.concurrent.ThreadPoolExecutor@5acf9800[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
2) if using LinkedBlockingQueue:
The threads never increase from minimum size to maximum size, meaning the thread pool is fixed size as the minimum size.
I just wanted to share my experience with you if someone might has the same problem with MOODLE.
Our moodle platform was suddenly very slowly, the dashboard took about 2-3 times longer to load (up to 6 seconds) then usual and from time to time some pages didn't get loaded at all (not a 404 error but a blank page). In the Developer Tools Console the following error was visible: net::ERR_INCOMPLETE_CHUNKED_ENCODING.
Searching for this error, it looks like Chrome is the issue, but we had the problem with various browsers. After hours of research and comparing the databases from the days before I finally found the problem, someone turned the Event Monitoring on. However, in the "Config changes" log, this change wasn't visible! Turning Event Monitoring off, finally solved the problem - we had no rules defined for event monitoring.
We're running Moodle 3.1.2+ with MariaDB and PHP 5.4.
Use Arrays.copyOf my friend.
From $http.get
docs, the second parameter is a configuration object:
get(url, [config]);
Shortcut method to perform
GET
request.
You may change your code to:
$http.get('accept.php', {
params: {
source: link,
category_id: category
}
});
Or:
$http({
url: 'accept.php',
method: 'GET',
params: {
source: link,
category_id: category
}
});
As a side note, since Angular 1.6: .success
should not be used anymore, use .then
instead:
$http.get('/url', config).then(successCallback, errorCallback);
Like this:
Dim rng as Range
Set rng = ActiveCell.Resize(numRows, numCols)
then read the contents of that range to an array:
Dim arr As Variant
arr = rng.Value
'arr is now a two-dimensional array of size (numRows, numCols)
or, select the range (I don't think that's what you really want, but you ask for this in the question).
rng.Select
Thanks for the solution !
It works, but in a french Excel environment, you should apply something like
TEXTE(F2;"jj/mm/aaaa")
to get the date preserved as it is displayed in F2 cell, after concatenation. Best Regards
or you can simply use
def question_params
params.require(:question).permit(team_ids: [])
end
please refer http://complete-concrete-concise.com/web-tools/how-to-change-localhost-to-a-domain-name
this is best solution ever
Add an additional CSS class that blocks the transition, and then remove it to return to the previous state. This make both CSS and JQuery code short, simple and well understandable.
CSS:
.notransition {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
-ms-transition: none !important;
transition: none !important;
}
!important
was added to be sure that this rule will have more "weight", because ID is normally more specific than class.
JQuery:
$('#elem').addClass('notransition'); // to remove transition
$('#elem').removeClass('notransition'); // to return to previouse transition
Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.
Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.
The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error
Since jQuery 1.6, you can use .is
. Below is the answer from over a year ago...
var a = $('#foo');
var b = a;
if (a.is(b)) {
// the same object!
}
If you want to see if two variables are actually the same object, eg:
var a = $('#foo');
var b = a;
...then you can check their unique IDs. Every time you create a new jQuery object it gets an id.
if ($.data(a) == $.data(b)) {
// the same object!
}
Though, the same could be achieved with a simple a === b
, the above might at least show the next developer exactly what you're testing for.
In any case, that's probably not what you're after. If you wanted to check if two different jQuery objects contain the same set of elements, the you could use this:
$.fn.equals = function(compareTo) {
if (!compareTo || this.length != compareTo.length) {
return false;
}
for (var i = 0; i < this.length; ++i) {
if (this[i] !== compareTo[i]) {
return false;
}
}
return true;
};
var a = $('p');
var b = $('p');
if (a.equals(b)) {
// same set
}
I follow below guidelines to avoid null checks.
Avoid lazy initialization of member variables as much as possible. Initialize the variables in declaration itself. This will handle NullPointerExceptions.
Decide on mutability of member variables early in the cycle. Use language constructs like final
keyword effectively.
If you know that augments for method won't be changed, declare them as final
.
Limit the mutation of data as much as possible. Some variables can be created in a constructor and can never be changed. Remove public setter methods unless they are really required.
E.g. Assume that one class in your application (A.java
) is maintaining a collection like HashMap
. Don't provide public
getter method in A.java and allow B.java
to directly add an element in Map
. Instead provide an API in A.java
, which adds an element into collection.
// Avoid
a.getMap().put(key,value)
//recommended
public void addElement(Object key, Object value){
// Have null checks for both key and value here : single place
map.put(key,value);
}
And finally, use try{} catch{} finally{}
blocks at right places effectively.
You can have multiple identical hash keys; but only if you have a range key that varies. Think of it like file formats; you can have 2 files with the same name in the same folder as long as their format is different. If their format is the same, their name must be different. The same concept applies to DynamoDB's hash/range keys; just think of the hash as the name and the range as the format.
Also, I don't recall if they had these at the time of the OP (I don't believe they did), but they now offer Local Secondary Indexes.
My understanding of these is that it should now allow you to perform the desired queries without having to do a full scan. The downside is that these indexes have to be specified at table creation, and also (I believe) cannot be blank when creating an item. In addition, they require additional throughput (though typically not as much as a scan) and storage, so it's not a perfect solution, but a viable alternative, for some.
I do still recommend Mike Brant's answer as the preferred method of using DynamoDB, though; and use that method myself. In my case, I just have a central table with only a hash key as my ID, then secondary tables that have a hash and range that can be queried, then the item points the code to the central table's "item of interest", directly.
Additional data regarding the secondary indexes can be found in Amazon's DynamoDB documentation here for those interested.
Anyway, hopefully this will help anyone else that happens upon this thread.
<ImageBackground
source={require("../assests/background_image.jpg")}
style={styles.container}
>
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center"
}}
>
<Button
onPress={() => this.props.showImagePickerComponent(this.props.navigation)}
title="START"
color="#841584"
accessibilityLabel="Increase Count"
/>
</View>
</ImageBackground>
Please use this code for set background image in react native
ampersand (&) is escaped to &
double quotes (") are escaped to "
single quotes (') are escaped to '
less than (<) is escaped to <
greater than (>) is escaped to >
In C#, use System.Security.SecurityElement.Escape
or System.Net.WebUtility.HtmlEncode
to escape these illegal characters.
string xml = "<node>it's my \"node\" & i like it 0x12 x09 x0A 0x09 0x0A <node>";
string encodedXml1 = System.Security.SecurityElement.Escape(xml);
string encodedXml2= System.Net.WebUtility.HtmlEncode(xml);
encodedXml1
"<node>it's my "node" & i like it 0x12 x09 x0A 0x09 0x0A <node>"
encodedXml2
"<node>it's my "node" & i like it 0x12 x09 x0A 0x09 0x0A <node>"
New, improved answer to an old, frequently asked question...
How could I get its parent? Result should be the
store
node.
parent::
or ancestor::
axisMost answers here select the title
and then traverse up to the targeted parent or ancestor (store
) element. A simpler, direct approach is to select parent or ancestor element directly in the first place, obviating the need to traverse to a parent::
or ancestor::
axes:
//*[book/title = "50"]
Should the intervening elements vary in name:
//*[*/title = "50"]
Or, in name and depth:
//*[.//title = "50"]
If the verification logic is non-trivial, it will be messy to write a large lambda method (as your example shows). You could put all the test statements in a separate method, but I don't like to do this because it disrupts the flow of reading the test code.
Another option is to use a callback on the Setup call to store the value that was passed into the mocked method, and then write standard Assert
methods to validate it. For example:
// Arrange
MyObject saveObject;
mock.Setup(c => c.Method(It.IsAny<int>(), It.IsAny<MyObject>()))
.Callback<int, MyObject>((i, obj) => saveObject = obj)
.Returns("xyzzy");
// Act
// ...
// Assert
// Verify Method was called once only
mock.Verify(c => c.Method(It.IsAny<int>(), It.IsAny<MyObject>()), Times.Once());
// Assert about saveObject
Assert.That(saveObject.TheProperty, Is.EqualTo(2));
You might want to you use the @property
decorator,
>>> class Foo():
... @property
... def todo(self):
... raise NotImplementedError("To be implemented")
...
>>> f = Foo()
>>> f.todo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in todo
NotImplementedError: To be implemented
Pragma directives specify operating system or machine specific (x86 or x64 etc) compiler options. There are several options available. Details can be found in https://msdn.microsoft.com/en-us/library/d9x1s805.aspx
#pragma comment( comment-type [,"commentstring"] )
has this format.
Refer https://msdn.microsoft.com/en-us/library/7f0aews7.aspx for details about different comment-type.
#pragma comment(lib, "kernel32")
#pragma comment(lib, "user32")
The above lines of code includes the library names (or path) that need to be searched by the linker. These details are included as part of the library-search record in the object file.
So, in this case kernel.lib
and user32.lib
are searched by the linker and included in the final executable.
If your application is already using Apache Commons lib, you can slightly modify the accepted answer to not create a new empty array each time:
List<String> list = ..;
String[] array = list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
// or if using static import
String[] array = list.toArray(EMPTY_STRING_ARRAY);
There are a few more preallocated empty arrays of different types in ArrayUtils
.
Also we can trick JVM to create en empty array for us this way:
String[] array = list.toArray(ArrayUtils.toArray());
// or if using static import
String[] array = list.toArray(toArray());
But there's really no advantage this way, just a matter of taste, IMO.
if it crashes on the delete
line then you have almost certainly somehow corrupted the heap. We would need to see more code to diagnose the problem since the example you presented has no errors.
Perhaps you have a buffer overflow on the heap which corrupted the heap structures or even something as simple as a "double free" (or in the c++ case "double delete").
Also, as The Fuzz noted, you may have an error in your destructor as well.
And yes, it is completely normal and expected for delete
to invoke the destructor, that is in fact one of its two purposes (call destructor then free memory).
You can define and assign value as shown below in one line. I have given an example of two variables declared and assigned in single line. if the data type of multiple variables are same
Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946
sp_who2 will actually provide a list of connections for the database server, not a database. To view connections for a single database (YourDatabaseName in this example), you can use
DECLARE @AllConnections TABLE(
SPID INT,
Status VARCHAR(MAX),
LOGIN VARCHAR(MAX),
HostName VARCHAR(MAX),
BlkBy VARCHAR(MAX),
DBName VARCHAR(MAX),
Command VARCHAR(MAX),
CPUTime INT,
DiskIO INT,
LastBatch VARCHAR(MAX),
ProgramName VARCHAR(MAX),
SPID_1 INT,
REQUESTID INT
)
INSERT INTO @AllConnections EXEC sp_who2
SELECT * FROM @AllConnections WHERE DBName = 'YourDatabaseName'
(Adapted from SQL Server: Filter output of sp_who2.)
You can do like that In Kotlin If you need kotlin code in the future
val myUri = getImageUri(applicationContext, myBitmap!!)
val finalFile = File(getRealPathFromURI(myUri))
fun getImageUri(inContext: Context, inImage: Bitmap): Uri {
val bytes = ByteArrayOutputStream()
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path = MediaStore.Images.Media.insertImage(inContext.contentResolver, inImage, "Title", null)
return Uri.parse(path)
}
fun getRealPathFromURI(uri: Uri): String {
val cursor = contentResolver.query(uri, null, null, null, null)
cursor!!.moveToFirst()
val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
return cursor.getString(idx)
}
Do you mean this:
if (newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || ...)
Or you could use regular expression:
if (newStr4.matches("(Mon|Tues|Wed|Thurs|Fri).*"))
Two last variants are the same, int
is wrapped to Integer
automatically where you need an Object
. If you not write any class in <> it will be Object
by default. So there is no difference, but it will be better to understanding if you write Object
.
I just had to delete and reinstall my google-services.json
and then restart Android Studio.
Instead of making a bunch of const int declarations
You can group them all in 1 enum
So its all organized by the common group they belong to
I'm not quite sure what a "good way" of copying a file is, but assuming "good" means "fast", I could broaden the subject a little.
Current operating systems have long been optimized to deal with run of the mill file copy. No clever bit of code will beat that. It is possible that some variant of your copy techniques will prove faster in some test scenario, but they most likely would fare worse in other cases.
Typically, the sendfile
function probably returns before the write has been committed, thus giving the impression of being faster than the rest. I haven't read the code, but it is most certainly because it allocates its own dedicated buffer, trading memory for time. And the reason why it won't work for files bigger than 2Gb.
As long as you're dealing with a small number of files, everything occurs inside various buffers (the C++ runtime's first if you use iostream
, the OS internal ones, apparently a file-sized extra buffer in the case of sendfile
). Actual storage media is only accessed once enough data has been moved around to be worth the trouble of spinning a hard disk.
I suppose you could slightly improve performances in specific cases. Off the top of my head:
copy_file
sequentially (though you'll hardly notice the difference as long as the file fits in the OS cache)But all that is outside the scope of a general purpose file copy function.
So in my arguably seasoned programmer's opinion, a C++ file copy should just use the C++17 file_copy
dedicated function, unless more is known about the context where the file copy occurs and some clever strategies can be devised to outsmart the OS.
if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{ // Do stuff here
}
import boto3
client = boto3.client('s3')
s3_key = 'Your file without bucket name e.g. abc/bcd.txt'
bucket = 'your bucket name'
content = client.head_object(Bucket=bucket,Key=s3_key)
if content.get('ResponseMetadata',None) is not None:
print "File exists - s3://%s/%s " %(bucket,s3_key)
else:
print "File does not exist - s3://%s/%s " %(bucket,s3_key)
Finally found this method:
basename($_SERVER['REQUEST_URI']);
This will return all URLs with page name. (e.g.: index.php?id=1&name=rr&class=10
).
using System;
using System.Linq;
using MySql.Data.MySqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// add here your connection details
String connectionString = "Server=localhost;Database=database;Uid=username;Pwd=password;";
try
{
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
Console.WriteLine("MySQL version: " + connection.ServerVersion);
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadKey();
}
}
}
make sure your database server is running if its not running then its not able to make connection and bydefault mysql running on 3306 so don't need mention port if same in case of port number is different then we need to mention port
My solution is create a Pipe for return the values array or propierties object
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'valueArray',
})
export class ValueArrayPipe implements PipeTransform {
// El parametro object representa, los valores de las propiedades o indice
transform(objects : any = []) {
return Object.values(objects);
}
}
The template Implement
<button ion-item *ngFor="let element of element_list | valueArray" >
{{ element.any_property }}
</button>
<?php
$min=1;
$max=20;
echo rand($min,$max);
?>
For right menu you can do it:
public static Drawable setTintDrawable(Drawable drawable, @ColorInt int color) {
drawable.clearColorFilter();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
drawable.invalidateSelf();
Drawable wrapDrawable = DrawableCompat.wrap(drawable).mutate();
DrawableCompat.setTint(wrapDrawable, color);
return wrapDrawable;
}
And in your activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_profile, menu);
Drawable send = menu.findItem(R.id.send);
Drawable msg = menu.findItem(R.id.message);
DrawableUtils.setTintDrawable(send.getIcon(), Color.WHITE);
DrawableUtils.setTintDrawable(msg.getIcon(), Color.WHITE);
return true;
}
This is the result:
I don't know if this is good practice or not, but casting a Context object to an Activity object compiles fine.
Try this: ((Activity) mContext).startActivity(...)
Include an Setup Project (New Project > Other Project Types > Setup and Deployment > Visual Studio Installer
) in your solution. It has options to include the framework installer. Check out this Deployment Guide MSDN post.
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
You may want to take if from a diffrent side: It seems easier to have a TextView with a drawable on the background:
<TextView
android:id="@+id/text"
android:background="@drawable/rounded_rectangle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
</TextView>
The whole creating and dispatching events works, but since you are using the onchange
attribute, your life can be a little simpler:
http://jsfiddle.net/xwywvd1a/3/
var selEl = document.getElementById("sel");
selEl.options[1].selected = true;
selEl.onchange();
If you use the browser's event API (addEventListener, IE's AttachEvent, etc), then you will need to create and dispatch events as others have pointed out already.
#define MULTILINE(...) #__VA_ARGS__
Consumes everything between the parentheses.
Replaces any number of consecutive whitespace characters by a single space.
You could basically use html tags in your string resource like:
<resource>
<string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string>
</resources>
And use Html.fromHtml or use spannable, check the link I posted.
Old similar question: Is it possible to have multiple styles inside a TextView?
Thanks to everyone for their input. This problem got solved by choosing REPAIR in Control Panel. I guess this explicitly re-registers some of Office's native COM components and does stuff that REINSTALL doesn't. I expect the latter just goes through a checklist and sometimes accepts what's there if it's already installed, maybe. I then had a separate issue with registering my own .NET dll for COM interop on the user's machine (despite this also working on other machines) though I think this was my error rather than Microsoft. Thanks again, I really appreciate it.
Not 100% sure what you mean:
Trusted_Connection=True;
IS using Windows credentials and is 100% equivalent to:
Integrated Security=SSPI;
or
Integrated Security=true;
If you don't want to use integrated security / trusted connection, you need to specify user id and password explicitly in the connection string (and leave out any reference to Trusted_Connection
or Integrated Security
)
server=yourservername;database=yourdatabase;user id=YourUser;pwd=TopSecret
Only in this case, the SQL Server authentication mode is used.
If any of these two settings is present (Trusted_Connection=true
or Integrated Security=true/SSPI
), then the Windows credentials of the current user are used to authenticate against SQL Server and any user iD=
setting will be ignored and not used.
For reference, see the Connection Strings site for SQL Server 2005 with lots of samples and explanations.
Using Windows Authentication is the preferred and recommended way of doing things, but it might incur a slight delay since SQL Server would have to authenticate your credentials against Active Directory (typically). I have no idea how much that slight delay might be, and I haven't found any references for that.
Summing up:
If you specify either Trusted_Connection=True;
or Integrated Security=SSPI;
or Integrated Security=true;
in your connection string
==> THEN (and only then) you have Windows Authentication happening. Any user id=
setting in the connection string will be ignored.
If you DO NOT specify either of those settings,
==> then you DO NOT have Windows Authentication happening (SQL Authentication mode will be used)
With some version-control plug-ins, it means that the local file has not yet been shared with the version-control repository. (In my install, this includes plug-ins for CVS and git, but not Perforce.)
You can sometimes see a list of these decorations in the plug-in's preferences under Team/X/Label Decorations, where X describes the version-control system.
For example, for CVS, the list looks like this:
These adornments are added to the object icons provided by Eclipse. For example, here's a table of icons for the Java development environment.
I had a similar problem, but it occurred to me inside procedure, when my query param was set using variable e.g. SET @value='foo'
.
What was causing this was mismatched collation_connection
and Database collation. Changed collation_connection
to match collation_database
and problem went away. I think this is more elegant approach than adding COLLATE after param/value.
To sum up: all collations must match. Use SHOW VARIABLES
and make sure collation_connection
and collation_database
match (also check table collation using SHOW TABLE STATUS [table_name]
).
The LINQ solution:
Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).Select(ip => ip.ToString()).FirstOrDefault() ?? ""
check
System.getProperty("sun.jnu.encoding")
it seems to be the same encoding as the one used in your system's command line.
Because Xcode subsumes the CLI tools if installed first, I use the following hybrid which has been validated on 10.12 and 10.14. I expect it works on a lot of other versions:
installed=$(pkgutil --pkg-info=com.apple.pkg.CLTools_Executables 2>/dev/null || pkgutil --pkg-info=com.apple.pkg.Xcode)
Salt with awk
to taste for branching logic.
Of course xcode-select -p
handles the variations with a really short command but fails to give the detailed package, version, and installation date metadata.
This is not really an answer to the present question, however it might help others too.
At least I can tell there is a technical limit of 32767 values (=Short.MAX_VALUE) passable to the PostgreSQL backend, using Posgresql's JDBC driver 9.1.
This is a test of "delete from x where id in (... 100k values...)" with the postgresql jdbc driver:
Caused by: java.io.IOException: Tried to send an out-of-range integer as a 2-byte value: 100000
at org.postgresql.core.PGStream.SendInteger2(PGStream.java:201)
This is a known bug that appears to have been fixed internally at Microsoft.
System.Threading.Thread.Sleep(
(int)System.TimeSpan.FromSeconds(3).TotalMilliseconds);
Or with using
statements:
Thread.Sleep((int)TimeSpan.FromSeconds(2).TotalMilliseconds);
I prefer this to 1000 * numSeconds
(or simply 3000
) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep
before. It better documents your intent.
if you are using ASP.NET MVC
Open the layout file "_Layout.cshtml" or your custom one
At the part of the code you see, as below:
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
@Scripts.Render("~/bundles/jquery")
Remove the line "@Scripts.Render("~/bundles/jquery")"
(at the part of the code you see) past as the latest line, as below:
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
This help me and hope helps you as well.
Assuming you do not want to restrict the rows that are returned because you are aggregating other values as well, you can do it like this:
select count(case when Position = 'Manager' then 1 else null end) as ManagerCount
from ...
Let's say within the same column you had values of Manager, Supervisor, and Team Lead, you could get the counts of each like this:
select count(case when Position = 'Manager' then 1 else null end) as ManagerCount,
count(case when Position = 'Supervisor' then 1 else null end) as SupervisorCount,
count(case when Position = 'Team Lead' then 1 else null end) as TeamLeadCount,
from ...
You could try hbase api methods!
org.apache.hadoop.hbase.client.coprocessor.AggregationClient
Yes, -f
is the most suitable option for this.
This is my python code: it has a fast check for primes and checks from highest to lowest the prime factors. You have to stop if no new numbers came out. (Any ideas on this?)
import math
def is_prime_v3(n):
""" Return 'true' if n is a prime number, 'False' otherwise """
if n == 1:
return False
if n > 2 and n % 2 == 0:
return False
max_divisor = math.floor(math.sqrt(n))
for d in range(3, 1 + max_divisor, 2):
if n % d == 0:
return False
return True
number = <Number>
for i in range(1,math.floor(number/2)):
if is_prime_v3(i):
if number % i == 0:
print("Found: {} with factor {}".format(number / i, i))
The answer for the initial question arrives in a fraction of a second.
You can get network interfaces with NetworkInterface.getNetworkInterfaces()
, then the IP addresses off the NetworkInterface objects returned with .getInetAddresses()
, then the string representation of those addresses with .getHostAddress()
.
If you make a @Configuration
class which implements ApplicationListener<EmbeddedServletContainerInitializedEvent>
, you can override onApplicationEvent
to get the port number once it's set.
@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
int port = event.getEmbeddedServletContainer().getPort();
}
Accepted answer is correct but there's an important step missing here, in case this view - for which you want blurred background - is presented using
[self presentViewController:vc animated:YES completion:nil]
By default, this will negate the blur as UIKit removes the presenter's view, which you are actually blurring. To avoid that removal, add this line before the previous one
vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
Or use other Over
styles.
Try using the WebConfigurationManager class instead. For example:
string userName = WebConfigurationManager.AppSettings["PFUserName"]
Use the "rendered" attribute available on most if not all tags in the h-namespace.
<h:outputText value="Hi George" rendered="#{Person.name == 'George'}" />
It should be noted that not only will the caret (^) behave differently within the brackets, it will have the opposite result of placing it outside of the brackets. Placing the caret where you have it will search for all strings NOT beginning with the content you placed within the brackets. You also would want to place a period before the asterisk in between your brackets as with grep, it also acts as a "wildcard".
grep ^[.rwx].*[0-9]$
This should work for you, I noticed that some posters used a character class in their expressions which is an effective method as well, but you were not using any in your original expression so I am trying to get one as close to yours as possible explaining every minor change along the way so that it is better understood. How can we learn otherwise?
sys.argv
represents the command line options you execute a script with.
sys.argv[0]
is the name of the script you are running. All additional options are contained in sys.argv[1:]
.
You are attempting to open a file that uses sys.argv[1]
(the first argument) as what looks to be the directory.
Try running something like this:
python ConcatenateFiles.py /tmp
My answer is based on getting a 403 error although I had all of the Apache settings mentioned in the other answers correct.
It was a fresh Centos 7 server and it turned out that the issue was not the Apache settings but the fact that the PhpMyAdmin did not serve at all. The solution was to install php and add the php directive to apache.conf:
Don't forget to restart Apache server to take effect - systemctl restart httpd.service
I hope this helps. I first thought my issue was Apache directives, so I post my solution here.
Give a Format String value of C2 for the value's properties as shown in figure below.
I had the same problem even though I have 64-bit Windows 7 and i was loading a 64bit DLL b/c in Project properties | Build I had "Prefer 32-bit" checked. (Don't know why that's set by default). Once I unchecked that, everything ran fine
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
REST
RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.
SOAP
SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.
Reference: http://spf13.com/post/soap-vs-rest
And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/
Uhh, I don't know why everyone suggests serializing the array.
I say, the best way is to actually fit it into your database schema. I have no idea (and you gave no clues) about the actual semantic meaning of the data in your array, but there are generally two ways of storing sequences like that
create table mydata (
id int not null auto_increment primary key,
field1 int not null,
field2 int not null,
...
fieldN int not null
)
This way you are storing your array in a single row.
create table mydata (
id int not null auto_increment primary key,
...
)
create table myotherdata (
id int not null auto_increment primary key,
mydata_id int not null,
sequence int not null,
data int not null
)
The disadvantage of the first method is, obviously, that if you have many items in your array, working with that table will not be the most elegant thing. It is also impractical (possible, but quite inelegant as well - just make the columns nullable) to work with sequences of variable length.
For the second method, you can have sequences of any length, but of only one type. You can, of course, make that one type varchar or something and serialize the items of your array. Not the best thing to do, but certainly better, than serializing the whole array, right?
Either way, any of this methods gets a clear advantage of being able to access an arbitrary element of the sequence and you don't have to worry about serializing arrays and ugly things like that.
As for getting it back. Well, get the appropriate row/sequence of rows with a query and, well, use a loop.. right?
I think you are talking about ctrl + shift + F, by default it should be on "look in: entire solution" and there you go.
The simplest approach IMO is to use Guava and its ByteStreams
class:
byte[] bytes = ByteStreams.toByteArray(in);
Or for a file:
byte[] bytes = Files.toByteArray(file);
Alternatively (if you didn't want to use Guava), you could create a ByteArrayOutputStream
, and repeatedly read into a byte array and write into the ByteArrayOutputStream
(letting that handle resizing), then call ByteArrayOutputStream.toByteArray()
.
Note that this approach works whether you can tell the length of your input or not - assuming you have enough memory, of course.
if you have array that looks like this -
data = [["foo",1,2,3,4],["bar",1,2],["foobar",1,"*",3,5,:foo]]
and you want the first elements of each array to become the keys for the hash and the rest of the elements becoming value arrays, then you can do something like this -
data_hash = Hash[data.map { |key| [key.shift, key] }]
#=>{"foo"=>[1, 2, 3, 4], "bar"=>[1, 2], "foobar"=>[1, "*", 3, 5, :foo]}
dump this into a more specific collection of just the ids you don't want
var notTheseBarIds = filterBars.Select(fb => fb.BarId);
then try this:
fooSelect = (from f in fooBunch
where !notTheseBarIds.Contains(f.BarId)
select f).ToList();
or this:
fooSelect = fooBunch.Where(f => !notTheseBarIds.Contains(f.BarId)).ToList();
In the past, there was something like: https: //jstl.dev.java.net/download.html. But since a few days, there is something happening on dev.java.net.
Java.net will be modified, read this: http: //www.java.net/. So I think we have to wait. I also found: http: //java.net/projects/help/pages/RequestedProjects.
Maybe this is helpful.
Another option is to look into the maven repository: http://repo1.maven.org/maven2/javax/servlet/
This answer includes childViewControllers
and maintains a clean and readable implementation.
+ (UIViewController *)topViewController
{
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
return [rootViewController topVisibleViewController];
}
- (UIViewController *)topVisibleViewController
{
if ([self isKindOfClass:[UITabBarController class]])
{
UITabBarController *tabBarController = (UITabBarController *)self;
return [tabBarController.selectedViewController topVisibleViewController];
}
else if ([self isKindOfClass:[UINavigationController class]])
{
UINavigationController *navigationController = (UINavigationController *)self;
return [navigationController.visibleViewController topVisibleViewController];
}
else if (self.presentedViewController)
{
return [self.presentedViewController topVisibleViewController];
}
else if (self.childViewControllers.count > 0)
{
return [self.childViewControllers.lastObject topVisibleViewController];
}
return self;
}
on linux you can use du -h $FILE
, does that work on solaris too?
Another way: add windowNoTitle
and windowFullscreen
attributes directly to the theme (you can find styles.xml
file in res/values/
directory):
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
in the manifest file, in application
specify your theme
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
You must have an empty line in your file.
You may want to wrap your parseInt calls in a "try" block:
try {
tall[i++] = Integer.parseInt(s);
}
catch (NumberFormatException ex) {
continue;
}
Or simply check for empty strings before parsing:
if (s.length() == 0)
continue;
Note that by initializing your index variable i
inside the loop, it is always 0. You should move the declaration before the while
loop. (Or make it part of a for
loop.)
I have had the same problem, but none of the answers quite gave a step by step of what I needed to do. This error happens because your socket file has not been created yet. All you have to do is:
/tmp/mysql.sock
is created, to do that you run: mysql server start
config/database.yml
file and add/edit the socket: /tmp/mysql.sock
entryrake:dbmigrate
once again and everything should workout fineFor en-US ( American English ) strings this should suffice:
"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation".replace( /[^a-zA-Z ]/g, '').replace( /\s\s+/g, ' ' )
Be aware that if you support UTF-8 and characters like chinese/russian and all, this will replace them as well, so you really have to specify what you want.
Actually the @Ian Robinson answer works well but Chrome will continue complain with that message : "Resource interpreted as Font but transferred with MIME type application/x-woff"
If you get that, you can change from
application/x-woff
to
application/x-font-woff
and you will not have any Chrome console errors anymore !
(tested on Chrome 17)
Referring to Volomike's answer, I would suggest replacing the line
nViewH -= 250;
with
nViewH = nViewH / window.devicePixelRatio;
It works exactly as I check on a HTC Magic (PixelRatio = 1) and a Samsung Galaxy Tab 7" (PixelRatio = 1.5).
Probably a silly suggestion compared to others:
if(!preg_match("/^[a-zA-Z0-9]$/",$string)){
$sortedString=preg_replace("/^[a-zA-Z0-9]+$/","",$string);
}
In the second example you provide 3 arguments: filename, mode and a dictionary (kwargs
). But Python expects: 2 formal arguments plus keyword arguments.
By prefixing the dictionary by '**' you unpack the dictionary kwargs
to keywords arguments.
A dictionary (type dict
) is a single variable containing key-value pairs.
"Keyword arguments" are key-value method-parameters.
Any dictionary can by unpacked to keyword arguments by prefixing it with **
during function call.
They can be differentiated with where they are coming from or which developers they're targeting mainly.
Groovy is a bit like scripting version of Java. Long time Java programmers feel at home when building agile applications backed by big architectures. Groovy on Grails is, as the name suggests similar to the Rails framework. For people who don't want to bother with Java's verbosity all the time.
Scala is an object oriented and functional programming language and Ruby or Python programmers may feel more closer to this one. It employs quite a lot of common good ideas found in these programming languages.
Clojure is a dialect of the Lisp programming language so Lisp, Scheme or Haskell developers may feel at home while developing with this language.
Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp
Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:
I hope that helps
The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:
When the field holds an embedded document (i.e, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:
Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.
In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company
with the value 'ABC123'
and the field address
with the value '123 Street'
, in the exact order:
db.inventory.find( {
producer: {
company: 'ABC123',
address: '123 Street'
}
});
The simpler and current approach for adding header to a single request is:
// Step 1
const yourHeader: HttpHeaders = new HttpHeaders({
Authorization: 'Bearer JWT-token'
});
// POST request
this.http.post(url, body, { headers: yourHeader });
// GET request
this.http.get(url, { headers: yourHeader });
Use this..
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$res_arr_values[] = $row;
}
Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.
Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:
$ uname -a
armv7l
Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.
You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.
You can follow the GitHub issue for 64-bit support here, if you're interested.
float: right
to.. float the second column to the.. right.overflow: hidden
to clear the floats so that the background color I just put in will be visible.#wrapper{
background:#000;
overflow: hidden
}
#c1 {
float:left;
background:red;
}
#c2 {
background:green;
float: right
}
You can print the request type using:
request.getMethod();
You can print all the headers as mentioned here:
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println("Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
}
To print all the request params, use this:
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = params.nextElement();
System.out.println("Parameter Name - "+paramName+", Value - "+request.getParameter(paramName));
}
request
is the instance of HttpServletRequest
You can beautify the outputs as you desire.
It acts as curly bracket. We have to keep the number of white spaces consistent through out the program.
Example 1:
def main():
print "we are in main function"
print "print 2nd line"
main()
Result:
We are in main function
print 2nd line
Example 2:
def main():
print "we are in main function"
print "print 2nd line"
main()
Result:
print 2nd line
We are in main function
Here, in the 1st program, both the statement comes under the main function since both have equal number of white spaces while in the 2nd program, the 1st line is printed later because the main function is called after the 2nd line Note - The 2nd line has no white space, so it is independent of the main function.
I got a situation like the code below
for(id<-0 to 99) {
try {
var symbol = ctx.read("$.stocks[" + id + "].symbol").toString
var name = ctx.read("$.stocks[" + id + "].name").toString
stocklist(symbol) = name
}catch {
case ex: com.jayway.jsonpath.PathNotFoundException=>{break}
}
}
I am using a java lib and the mechanism is that ctx.read throw a Exception when it can find nothing. I was trapped in the situation that :I have to break the loop when a Exception was thrown, but scala.util.control.Breaks.break using Exception to break the loop ,and it was in the catch block thus it was caught.
I got ugly way to solve this: do the loop for the first time and get the count of the real length. and use it for the second loop.
take out break from Scala is not that good,when you are using some java libs.
This question is quite broad, so I'm going to give a couple of solutions.
Here's an example of using a Helper Method that you could change to fit your needs:
class SerializationHelper {
static toInstance<T>(obj: T, json: string) : T {
var jsonObj = JSON.parse(json);
if (typeof obj["fromJSON"] === "function") {
obj["fromJSON"](jsonObj);
}
else {
for (var propName in jsonObj) {
obj[propName] = jsonObj[propName]
}
}
return obj;
}
}
Then using it:
var json = '{"name": "John Doe"}',
foo = SerializationHelper.toInstance(new Foo(), json);
foo.GetName() === "John Doe";
Advanced Deserialization
This could also allow for some custom deserialization by adding your own fromJSON
method to the class (this works well with how JSON.stringify
already uses the toJSON
method, as will be shown):
interface IFooSerialized {
nameSomethingElse: string;
}
class Foo {
name: string;
GetName(): string { return this.name }
toJSON(): IFooSerialized {
return {
nameSomethingElse: this.name
};
}
fromJSON(obj: IFooSerialized) {
this.name = obj.nameSomethingElse;
}
}
Then using it:
var foo1 = new Foo();
foo1.name = "John Doe";
var json = JSON.stringify(foo1);
json === '{"nameSomethingElse":"John Doe"}';
var foo2 = SerializationHelper.toInstance(new Foo(), json);
foo2.GetName() === "John Doe";
Another way you could do this is by creating your own base class:
class Serializable {
fillFromJSON(json: string) {
var jsonObj = JSON.parse(json);
for (var propName in jsonObj) {
this[propName] = jsonObj[propName]
}
}
}
class Foo extends Serializable {
name: string;
GetName(): string { return this.name }
}
Then using it:
var foo = new Foo();
foo.fillFromJSON(json);
There's too many different ways to implement a custom deserialization using a base class so I'll leave that up to how you want it.
DOUBLE columns are not the same as DECIMAL columns, and you will get in trouble if you use DOUBLE columns for financial data.
DOUBLE is actually just a double precision (64 bit instead of 32 bit) version of FLOAT. Floating point numbers are approximate representations of real numbers and they are not exact. In fact, simple numbers like 0.01 do not have an exact representation in FLOAT or DOUBLE types.
DECIMAL columns are exact representations, but they take up a lot more space for a much smaller range of possible numbers. To create a column capable of holding values from 0.0001 to 99.9999 like you asked you would need the following statement
CREATE TABLE your_table
(
your_column DECIMAL(6,4) NOT NULL
);
The column definition follows the format DECIMAL(M, D) where M is the maximum number of digits (the precision) and D is the number of digits to the right of the decimal point (the scale).
This means that the previous command creates a column that accepts values from -99.9999 to 99.9999. You may also create an UNSIGNED DECIMAL column, ranging from 0.0000 to 99.9999.
For more information on MySQL DECIMAL the official docs are always a great resource.
Bear in mind that all of this information is true for versions of MySQL 5.0.3 and greater. If you are using previous versions, you really should upgrade.
ArrayList<String> keyList = new ArrayList<String>();
mKeyRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String temp = childDataSnapshot.getKey();
keyList.add(temp);
i = keyList.size();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
This code is working fine to add all firebase key into arraylist, you can do it with firebase values, of other static values.
I learned this from http://www.pcsalt.com/android/edittext-with-single-line-line-wrapping-and-done-action-in-android/, though I don't like the website myself. If you want multiline BUT want to retain the enter button as a post button, set the listview's "horizontally scrolling" to false.
android:scrollHorizontally="false"
If it doesn't work in xml, doing it programmatically weirdly works.
listView.setHorizontallyScrolling(false);
You're resetting the margin on all elements in the second css block. Default margin is 40px - this should solve the problem:
.my_container ul {list-style:disc outside none; margin-left:40px;}
In DBeaver you can use parameters in queries just like you can from code, so this will work:
SELECT *
FROM somewhere
WHERE something = :myvar
When you run the query DBeaver will ask you for the value for :myvar and run the query.
I believe the following code will help:
float f1 = 1.23f;
String f1Str = Float.toString(f1);
float f2 = Float.parseFloat(f1Str);
My issue was that viewWillAppear was not called when unwinding from a segue. The answer was to put a call to viewWillAppear(true) in the unwind segue in the View Controller that you segueing back to
@IBAction func unwind(for unwindSegue: UIStoryboardSegue, ViewController subsequentVC: Any) {
viewWillAppear(true)
}
In addition to previous answers there is one important for me note:
shelve
is JetBrains products feature (such as WebStorm
, PhpStorm
, PyCharm
, etc.). It puts shelved files into .idea/shelf
directory.
stash
is one of git
options. It puts stashed files under the .git
directory.
This is an easier way to do it. Hope this helps...
<script type="text/javascript">
$(document).ready(function () {
$("#preview").toggle(function() {
$("#div1").hide();
$("#div2").show();
}, function() {
$("#div1").show();
$("#div2").hide();
});
});
<div id="div1">
This is preview Div1. This is preview Div1.
</div>
<div id="div2" style="display:none;">
This is preview Div2 to show after div 1 hides.
</div>
<div id="preview" style="color:#999999; font-size:14px">
PREVIEW
</div>
Links:
http://www.w3schools.com/jquery/default.asp (W3Schools)
http://thenewboston.org/list.php?cat=32 (Video Tutorials)
http://andreehansson.se/the-basics-of-jquery/ (Basic Tutorial)
None of the previous answers completely solved my use case.
Needed to remove the directory that was being built. Clean. And then re-install. Looks like a silent permissions issue.
You have a concrete example of a Student and a MessageBoard. The Student registers by adding itself to the list of Observers that want to be notified when a new Message is posted to the MessageBoard. When a Message is added to the MessageBoard, it iterates over its list of Observers and notifies them that the event occurred.
Think Twitter. When you say you want to follow someone, Twitter adds you to their follower list. When they sent a new tweet in, you see it in your input. In that case, your Twitter account is the Observer and the person you're following is the Observable.
The analogy might not be perfect, because Twitter is more likely to be a Mediator. But it illustrates the point.
In the latest version of Twitter Bootstrap the layout is fluid by default, hence you don't need extra classes to declare your layout as fluid.
You can further refer to -
http://bassjobsen.weblogs.fm/migrate-your-templates-from-twitter-bootstrap-2-x-to-twitter-bootstrap-3/ http://blog.getbootstrap.com/
The simplest solution I found out is something like this:
<item name="colorAccent">@color/white_or_any_color</item>
Put the above in styles.xml
file under res > values
folder.
NOTE: If you use any other accent color, then the previous solutions should be good to go with.
API 21 or HIGHER
The one reason I have which made switching to MacVim worth it: Yank uses the system clipboard.
I can finally copy paste between MacVim on my terminal and the rest of my applications.
It is OK to throw from your constructor, but you should make sure that your object is constructed after main has started and before it finishes:
class A
{
public:
A () {
throw int ();
}
};
A a; // Implementation defined behaviour if exception is thrown (15.3/13)
int main ()
{
try
{
// Exception for 'a' not caught here.
}
catch (int)
{
}
}
For security & other reasons, ruby does not by default include the current directory in the load_path. You may want to check this for more details - Why does Ruby 1.9.2 remove "." from LOAD_PATH, and what's the alternative?
If you use jquery then you can also do like this,
$(document).on("keydown", '.class_name', function (event) {
if (event.keyCode == 37) {
console.log('left arrow pressed');
}
if (event.keyCode == 38) {
console.log('up arrow pressed');
}
if (event.keyCode == 39) {
console.log('right arrow pressed');
}
if (event.keyCode == 40) {
console.log('down arrow pressed');
}
});
I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.
I've written a stored procedure to show how to do this before. You basically have to process the string. I tried to post the code here but the formatting got all screwy.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[uspSplitTextList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[uspSplitTextList]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
-- uspSplitTextList
--
-- Description:
-- splits a separated list of text items and returns the text items
--
-- Arguments:
-- @list_text - list of text items
-- @Delimiter - delimiter
--
-- Notes:
-- 02/22/2006 - WSR : use DATALENGTH instead of LEN throughout because LEN doesn't count trailing blanks
--
-- History:
-- 02/22/2006 - WSR : revised algorithm to account for items crossing 8000 character boundary
-- 09/18/2006 - WSR : added to this project
--
CREATE PROCEDURE uspSplitTextList
@list_text text,
@Delimiter varchar(3)
AS
SET NOCOUNT ON
DECLARE @InputLen integer -- input text length
DECLARE @TextPos integer -- current position within input text
DECLARE @Chunk varchar(8000) -- chunk within input text
DECLARE @ChunkPos integer -- current position within chunk
DECLARE @DelimPos integer -- position of delimiter
DECLARE @ChunkLen integer -- chunk length
DECLARE @DelimLen integer -- delimiter length
DECLARE @ItemBegPos integer -- item starting position in text
DECLARE @ItemOrder integer -- item order in list
DECLARE @DelimChar varchar(1) -- first character of delimiter (simple delimiter)
-- create table to hold list items
-- actually their positions because we may want to scrub this list eliminating bad entries before substring is applied
CREATE TABLE #list_items ( item_order integer, item_begpos integer, item_endpos integer )
-- process list
IF @list_text IS NOT NULL
BEGIN
-- initialize
SET @InputLen = DATALENGTH(@list_text)
SET @TextPos = 1
SET @DelimChar = SUBSTRING(@Delimiter, 1, 1)
SET @DelimLen = DATALENGTH(@Delimiter)
SET @ItemBegPos = 1
SET @ItemOrder = 1
SET @ChunkLen = 1
-- cycle through input processing chunks
WHILE @TextPos <= @InputLen AND @ChunkLen <> 0
BEGIN
-- get current chunk
SET @Chunk = SUBSTRING(@list_text, @TextPos, 8000)
-- setup initial variable values
SET @ChunkPos = 1
SET @ChunkLen = DATALENGTH(@Chunk)
SET @DelimPos = CHARINDEX(@DelimChar, @Chunk, @ChunkPos)
-- loop over the chunk, until the last delimiter
WHILE @ChunkPos <= @ChunkLen AND @DelimPos <> 0
BEGIN
-- see if this is a full delimiter
IF SUBSTRING(@list_text, (@TextPos + @DelimPos - 1), @DelimLen) = @Delimiter
BEGIN
-- insert position
INSERT INTO #list_items (item_order, item_begpos, item_endpos)
VALUES (@ItemOrder, @ItemBegPos, (@TextPos + @DelimPos - 1) - 1)
-- adjust positions
SET @ItemOrder = @ItemOrder + 1
SET @ItemBegPos = (@TextPos + @DelimPos - 1) + @DelimLen
SET @ChunkPos = @DelimPos + @DelimLen
END
ELSE
BEGIN
-- adjust positions
SET @ChunkPos = @DelimPos + 1
END
-- find next delimiter
SET @DelimPos = CHARINDEX(@DelimChar, @Chunk, @ChunkPos)
END
-- adjust positions
SET @TextPos = @TextPos + @ChunkLen
END
-- handle last item
IF @ItemBegPos <= @InputLen
BEGIN
-- insert position
INSERT INTO #list_items (item_order, item_begpos, item_endpos)
VALUES (@ItemOrder, @ItemBegPos, @InputLen)
END
-- delete the bad items
DELETE FROM #list_items
WHERE item_endpos < item_begpos
-- return list items
SELECT SUBSTRING(@list_text, item_begpos, (item_endpos - item_begpos + 1)) AS item_text, item_order, item_begpos, item_endpos
FROM #list_items
ORDER BY item_order
END
DROP TABLE #list_items
RETURN
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
In addition to the 16/32/64 bit differences even odder things can occur.
There have been machines where sizeof(int *) will be one value, probably 4 but where sizeof(char *) is larger. Machines that naturally address words instead of bytes have to "augment" character pointers to specify what portion of the word you really want in order to properly implement the C/C++ standard.
This is now very unusual as hardware designers have learned the value of byte addressability.
in json everything is string between double quote ", so you need escape " if it happen in value (only in direct writing) use backslash \
and everything in json file wrapped in {} change your json to
{_x000D_
[_x000D_
{_x000D_
"id": "services.html",_x000D_
"img": "img/SolutionInnerbananer.jpg",_x000D_
"html": "<h2 class=\"fg-white\">AboutUs</h2><p class=\"fg-white\">developing and supporting complex IT solutions.Touching millions of lives world wide by bringing in innovative technology</p>"_x000D_
}_x000D_
]_x000D_
}
_x000D_
There is jq
for parsing json on the command line:
jq '.Body'
Visit this for jq: https://stedolan.github.io/jq/
Lots of hate for the Convert class here... Just to balance a little bit, there is one advantage for Convert - if you are handed an object,
Convert.ToDouble(o);
can just return the value easily if o is already a Double (or an int or anything readily castable).
Using Double.Parse or Double.TryParse is great if you already have it in a string, but
Double.Parse(o.ToString());
has to go make the string to be parsed first and depending on your input that could be more expensive.
Kyle's and Simon's answers are gross waste of CPU resources. CellFormatting
and CellPainting
events occur far too many times and should not be used for applying styles. Here are two better ways of doing it:
If your DataGridView or at least the columns that decide cell style are read-only, you should change DefaultCellStyle of rows in RowsAdded
event. This event occurs only once when a new row is added. The condition should be evaluated at that time and DefaultCellStyle
of the row should be set therein. Note that this event occurs for DataBound situations too.
If your DataGridView or those columns allow editing, you should use CellEndEdit
or CommitEdit
events to change DefaultCellStyle
.
In database design, a compound key is a set of superkeys that is not minimal.
A composite key is a set that contains a compound key and at least one attribute that is not a superkey
Given table: EMPLOYEES {employee_id, firstname, surname}
Possible superkeys are:
{employee_id}
{employee_id, firstname}
{employee_id, firstname, surname}
{employee_id} is the only minimal superkey, which also makes it the only candidate key--given that {firstname} and {surname} do not guarantee uniqueness. Since a primary key is defined as a chosen candidate key, and only one candidate key exists in this example, {employee_id} is the minimal superkey, the only candidate key, and the only possible primary key.
The exhaustive list of compound keys is:
{employee_id, firstname}
{employee_id, surname}
{employee_id, firstname, surname}
The only composite key is {employee_id, firstname, surname} since that key contains a compound key ({employee_id,firstname}) and an attribute that is not a superkey ({surname}).
Essentially, use an <a>
element with an href
attr pointing to the phone number prefixed by tel:
. Note that pluses can be used to specify country code, and hyphens can be included simply for human eyes.
MDN Web Docs
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Creating_a_phone_link
The HTML
<a>
element (or anchor element), along with its href attribute, creates a hyperlink to other web pages, files, locations within the same page, email addresses, or any other URL.[…]
Offering phone links is helpful for users viewing web documents and laptops connected to phones.
<a href="tel:+491570156">+49 157 0156</a>
IETF Documents
https://tools.ietf.org/html/rfc3966
The
tel
URI for Telephone NumbersThe "tel" URI has the following syntax:
telephone-uri
="tel:"
telephone-subscriber[…]
Examples
tel:+1-201-555-0123
: This URI points to a phone number in the United States. The hyphens are included to make the number more human readable; they separate country, area code and subscriber number.
tel:7042;phone-context=example.com
: The URI describes a local phone number valid within the context "example.com".
tel:863-1234;phone-context=+1-914-555
: The URI describes a local phone number that is valid within a particular phone prefix.
TLDR: Add this class to your utility methods and use it throughout your code, it mocks Enum behavior from traditional programming languages, and actually throws errors when you try to either access an enumerator that does not exist or add/update an enumerator. No need to rely on Object.freeze()
.
class Enum {
constructor(enumObj) {
const handler = {
get(target, name) {
if (typeof target[name] != 'undefined') {
return target[name];
}
throw new Error(`No such enumerator: ${name}`);
},
set() {
throw new Error('Cannot add/update properties on an Enum instance after it is defined')
}
};
return new Proxy(enumObj, handler);
}
}
Then create enums by instantiating the class:
const roles = new Enum({
ADMIN: 'Admin',
USER: 'User',
});
Full Explanation:
One very beneficial feature of Enums that you get from traditional languages is that they blow up (throw a compile-time error) if you try to access an enumerator which does not exist.
Besides freezing the mocked enum structure to prevent additional values from accidentally/maliciously being added, none of the other answers address that intrinsic feature of Enums.
As you are probably aware, accessing non-existing members in JavaScript simply returns undefined
and does not blow up your code. Since enumerators are predefined constants (i.e. days of the week), there should never be a case when an enumerator should be undefined.
Don't get me wrong, JavaScript's behavior of returning undefined
when accessing undefined properties is actually a very powerful feature of language, but it's not a feature you want when you are trying to mock traditional Enum structures.
This is where Proxy objects shine. Proxies were standardized in the language with the introduction of ES6 (ES2015). Here's the description from MDN:
The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
Similar to a web server proxy, JavaScript proxies are able to intercept operations on objects (with the use of "traps", call them hooks if you like) and allow you to perform various checks, actions and/or manipulations before they complete (or in some cases stopping the operations altogether which is exactly what we want to do if and when we try to reference an enumerator which does not exist).
Here's a contrived example that uses the Proxy object to mimic Enums. The enumerators in this example are standard HTTP Methods (i.e. "GET", "POST", etc.):
// Class for creating enums (13 lines)_x000D_
// Feel free to add this to your utility library in _x000D_
// your codebase and profit! Note: As Proxies are an ES6 _x000D_
// feature, some browsers/clients may not support it and _x000D_
// you may need to transpile using a service like babel_x000D_
_x000D_
class Enum {_x000D_
// The Enum class instantiates a JavaScript Proxy object._x000D_
// Instantiating a `Proxy` object requires two parameters, _x000D_
// a `target` object and a `handler`. We first define the handler,_x000D_
// then use the handler to instantiate a Proxy._x000D_
_x000D_
// A proxy handler is simply an object whose properties_x000D_
// are functions which define the behavior of the proxy _x000D_
// when an operation is performed on it. _x000D_
_x000D_
// For enums, we need to define behavior that lets us check what enumerator_x000D_
// is being accessed and what enumerator is being set. This can be done by _x000D_
// defining "get" and "set" traps._x000D_
constructor(enumObj) {_x000D_
const handler = {_x000D_
get(target, name) {_x000D_
if (typeof target[name] != 'undefined') {_x000D_
return target[name]_x000D_
}_x000D_
throw new Error(`No such enumerator: ${name}`)_x000D_
},_x000D_
set() {_x000D_
throw new Error('Cannot add/update properties on an Enum instance after it is defined')_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
// Freeze the target object to prevent modifications_x000D_
return new Proxy(enumObj, handler)_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
// Now that we have a generic way of creating Enums, lets create our first Enum!_x000D_
const httpMethods = new Enum({_x000D_
DELETE: "DELETE",_x000D_
GET: "GET",_x000D_
OPTIONS: "OPTIONS",_x000D_
PATCH: "PATCH",_x000D_
POST: "POST",_x000D_
PUT: "PUT"_x000D_
})_x000D_
_x000D_
// Sanity checks_x000D_
console.log(httpMethods.DELETE)_x000D_
// logs "DELETE"_x000D_
_x000D_
try {_x000D_
httpMethods.delete = "delete"_x000D_
} catch (e) {_x000D_
console.log("Error: ", e.message)_x000D_
}_x000D_
// throws "Cannot add/update properties on an Enum instance after it is defined"_x000D_
_x000D_
try {_x000D_
console.log(httpMethods.delete)_x000D_
} catch (e) {_x000D_
console.log("Error: ", e.message)_x000D_
}_x000D_
// throws "No such enumerator: delete"
_x000D_
ASIDE: What the heck is a proxy?
I remember when I first started seeing the word proxy everywhere, it definitely didn't make sense to me for a long time. If that's you right now, I think an easy way to generalize proxies is to think of them as software, institutions, or even people that act as intermediaries or middlemen between two servers, companies, or people.