VBA has the collection object:
Dim c As Collection
Set c = New Collection
c.Add "Data1", "Key1"
c.Add "Data2", "Key2"
c.Add "Data3", "Key3"
'Insert data via key into cell A1
Range("A1").Value = c.Item("Key2")
The Collection
object performs key-based lookups using a hash so it's quick.
You can use a Contains()
function to check whether a particular collection contains a key:
Public Function Contains(col As Collection, key As Variant) As Boolean
On Error Resume Next
col(key) ' Just try it. If it fails, Err.Number will be nonzero.
Contains = (Err.Number = 0)
Err.Clear
End Function
Edit 24 June 2015: Shorter Contains()
thanks to @TWiStErRob.
Edit 25 September 2015: Added Err.Clear()
thanks to @scipilot.
explain select * from test where id in (values (1), (2));
Seq Scan on test (cost=0.00..1.38 rows=2 width=208)
Filter: (id = ANY ('{1,2}'::bigint[]))
But if try 2nd query:
explain select * from test where id = any (values (1), (2));
Hash Semi Join (cost=0.05..1.45 rows=2 width=208)
Hash Cond: (test.id = "*VALUES*".column1)
-> Seq Scan on test (cost=0.00..1.30 rows=30 width=208)
-> Hash (cost=0.03..0.03 rows=2 width=4)
-> Values Scan on "*VALUES*" (cost=0.00..0.03 rows=2 width=4)
We can see that postgres build temp table and join with it
class
is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class
itself.
e.g.
class ANewType
{
// ... details
};
This defines a new type called ANewType
which is a class type.
You can then use this in function declarations:
void function(ANewType object);
You can then pass objects of type ANewType
into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.
If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.
void function(ANewType& object); // object passed by reference
This syntax means that any use of object
in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.
[* The class
keyword is also used in template definitions, but that's a different subject.]
As stated already, you can operate on Time
objects as if they were numeric (or floating point) values. These operations result in second resolution which can easily be converted.
For example:
def time_diff_milli(start, finish)
(finish - start) * 1000.0
end
t1 = Time.now
# arbitrary elapsed time
t2 = Time.now
msecs = time_diff_milli t1, t2
You will need to decide whether to truncate that or not.
this worked for me with minimal code
$(my_list).remove('li');
as date_format uses the same format as date ( http://www.php.net/manual/en/function.date.php ) the "Numeric representation of a month, without leading zeros" is a lowercase n .. so
echo date('n'); // "9"
How about User-Defined Type Guards? https://www.typescriptlang.org/docs/handbook/advanced-types.html
interface Bird {
fly();
layEggs();
}
interface Fish {
swim();
layEggs();
}
function isFish(pet: Fish | Bird): pet is Fish { //magic happens here
return (<Fish>pet).swim !== undefined;
}
// Both calls to 'swim' and 'fly' are now okay.
if (isFish(pet)) {
pet.swim();
}
else {
pet.fly();
}
If you are using webpack 4
, the following code is tree shakable.
import { has } from 'lodash-es';
The points to note;
CommonJS modules are not tree shakable so you should definitely use lodash-es
, which is the Lodash library exported as ES Modules, rather than lodash
(CommonJS).
lodash-es
's package.json contains "sideEffects": false
, which notifies webpack 4 that all the files inside the package are side effect free (see https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free).
This information is crucial for tree shaking since module bundlers do not tree shake files which possibly contain side effects even if their exported members are not used in anywhere.
Edit
As of version 1.9.0, Parcel also supports "sideEffects": false
, threrefore import { has } from 'lodash-es';
is also tree shakable with Parcel.
It also supports tree shaking CommonJS modules, though it is likely tree shaking of ES Modules is more efficient than CommonJS according to my experiment.
By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.
So just set it to:
<style name="AppTheme" parent="android:Theme.Holo" />
I figure it out with a timer, hope it helps. I have used a timer from java.util.Timer
and TimerTask
from the same package. See below:
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Hello World");
}
};
Timer timer = new Timer();
timer.schedule(task, new Date(), 3000);
Mistake in original post is acquire() call set inside the try loop. Here is a correct approach to use "binary" semaphore (Mutex):
semaphore.acquire();
try {
//do stuff
} catch (Exception e) {
//exception stuff
} finally {
semaphore.release();
}
char = split_string_to_char(text)(index)
------
Function split_string_to_char(text) As String()
Dim chars() As String
For char_count = 1 To Len(text)
ReDim Preserve chars(char_count - 1)
chars(char_count - 1) = Mid(text, char_count, 1)
Next
split_string_to_char = chars
End Function
You could also write your own Control for this, in case you want to use this more often. Assuming you have multiple TextBoxes in a Grid, it would look something like this:
public class AdvanceOnEnterTextBox : UserControl
{
TextBox _TextBox;
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(String), typeof(AdvanceOnEnterTextBox), null);
public static readonly DependencyProperty InputScopeProperty = DependencyProperty.Register("InputScope", typeof(InputScope), typeof(AdvanceOnEnterTextBox), null);
public AdvanceOnEnterTextBox()
{
_TextBox = new TextBox();
_TextBox.KeyDown += customKeyDown;
Content = _TextBox;
}
/// <summary>
/// Text for the TextBox
/// </summary>
public String Text
{
get { return _TextBox.Text; }
set { _TextBox.Text = value; }
}
/// <summary>
/// Inputscope for the Custom Textbox
/// </summary>
public InputScope InputScope
{
get { return _TextBox.InputScope; }
set { _TextBox.InputScope = value; }
}
void customKeyDown(object sender, KeyEventArgs e)
{
if (!e.Key.Equals(Key.Enter)) return;
var element = ((TextBox)sender).Parent as AdvanceOnEnterTextBox;
if (element != null)
{
int currentElementPosition = ((Grid)element.Parent).Children.IndexOf(element);
try
{
// Jump to the next AdvanceOnEnterTextBox (assuming, that Labels are inbetween).
((AdvanceOnEnterTextBox)((Grid)element.Parent).Children.ElementAt(currentElementPosition + 2)).Focus();
}
catch (Exception)
{
// Close Keypad if this was the last AdvanceOnEnterTextBox
((AdvanceOnEnterTextBox)((Grid)element.Parent).Children.ElementAt(currentElementPosition)).IsEnabled = false;
((AdvanceOnEnterTextBox)((Grid)element.Parent).Children.ElementAt(currentElementPosition)).IsEnabled = true;
}
}
}
}
why do these two different operators, [ ]
, and [[ ]]
, return the same result?
x = list(1, 2, 3, 4)
[ ]
provides sub setting operation. In general sub set of any object
will have the same type as the original object. Therefore, x[1]
provides a list. Similarly x[1:2]
is a subset of original list,
therefore it is a list. Ex.
x[1:2]
[[1]] [1] 1
[[2]] [1] 2
[[ ]]
is for extracting an element from the list. x[[1]]
is valid
and extract the first element from the list. x[[1:2]]
is not valid as [[ ]]
does not provide sub setting like [ ]
.
x[[2]] [1] 2
> x[[2:3]] Error in x[[2:3]] : subscript out of bounds
For Android 7, Galaxy S6 Edge:
If Developer Options is not available then
Now perform step 1. Now it should work, if its still not working then perform these steps. It worked for me.
Add these dependencies to your maven pom.xml . It will take care of all of the imports including OPCpackage
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)
If you want an unsigned difference, add an ABS()
around the expression.
Alternatively, you can use TIMEDIFF(ts1, ts2)
and then convert the time result to seconds with TIME_TO_SEC()
.
You're looking for the JavaScriptSerializer
class, which is used internally by JsonResult:
string json = new JavaScriptSerializer().Serialize(jsonResult.Data);
To return the whole table at once you could change the SELECT to:
SELECT ...
BULK COLLECT INTO T
FROM ...
This is only advisable for results that aren't excessively large, since they all have to be accumulated in memory before being returned; otherwise consider the pipelined function as suggested by Charles, or returning a REF CURSOR.
Given your representation, your function is as efficient as can be done. Of course, as noted by others (and as practiced in languages older than Lua), the solution to your real problem is to change representation. When you have tables and you want sets, you turn tables into sets by using the set element as the key and true
as the value. +1 to interjay.
You need to remove "in" from "collapse in"
you can also use the Readonly attribute: the input is not gonna be grayed but it won't be editable
<input type="text" name="lat" value="22.2222" readonly="readonly" />
Just add a new route to the WebApiConfig
entries.
For instance, to call:
public IEnumerable<SampleObject> Get(int pageNumber, int pageSize) { ..
add:
config.Routes.MapHttpRoute(
name: "GetPagedData",
routeTemplate: "api/{controller}/{pageNumber}/{pageSize}"
);
Then add the parameters to the HTTP call:
GET //<service address>/Api/Data/2/10
You're trying to assign the return value of clients.get(clients.size())
to the string hey
, but the object returned is a ClientThread
, not a string. As Andre mentioned, you need to use the proper index as well.
As far as your second error is concerned, there is no static method remove()
on the type ClientThread
. Really, you likely wanted the remove method of your List
instance, clients
.
You can remove the last item from the list, if there is one, as follows. Since remove also returns the object that was removed, you can capture the return and use it to print out the name:
int size = clients.size();
if (size > 0) {
ClientThread client = clients.remove(size - 1);
System.out.println(client + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());
}
I present a fully worked example on how building a shared library
and using it under Python
by means of ctypes
. I consider the Windows
case and deal with DLLs
. Two steps are needed:
The shared library
I consider is the following and is contained in the testDLL.cpp
file. The only function testDLL
just receives an int
and prints it.
#include <stdio.h>
?
extern "C" {
?
__declspec(dllexport)
?
void testDLL(const int i) {
printf("%d\n", i);
}
?
} // extern "C"
To build a DLL
with Visual Studio
from the command line run
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\vsdevcmd"
to set the include path and then run
cl.exe /D_USRDLL /D_WINDLL testDLL.cpp /MT /link /DLL /OUT:testDLL.dll
to build the DLL.
DLL
from the IDEAlternatively, the DLL
can be build using Visual Studio
as follows:
Under Python, do the following
import os
import sys
from ctypes import *
lib = cdll.LoadLibrary('testDLL.dll')
lib.testDLL(3)
That's because the color
input only accepts three attributes: "primary"
, "accent"
or "warn"
. Hence, you'll have to style the icons the CSS way:
Add a class to style your icon:
.white-icon {
color: white;
}
/* Note: If you're using an SVG icon, you should make the class target the `<svg>` element */
.white-icon svg {
fill: white;
}
Add the class to your icon:
<mat-icon class="white-icon">menu</mat-icon>
This one worked for me and it's also very easy
<?php
$position=14; // Define how many character you want to display.
$message="You are now joining over 2000 current";
$post = substr($message, 0, $position);
echo $post;
echo "...";
?>
Use is.na
DF <- data.frame(x = c(1, 2, 3), y = c(0, 10, NA), z=c(NA, 33, 22))
DF[!is.na(DF$y),]
try this. works for me
$options = array(
'cache_wsdl' => 0,
'trace' => 1,
'stream_context' => stream_context_create(array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
));
$client = new SoapClient(url, $options);
You can use the nice_hash gem: https://github.com/MarioRuiz/nice_hash
require 'nice_hash'
my_string = '{"val":"test","val1":"test1","val2":"test2"}'
# on my_hash will have the json as a hash, even when nested with arrays
my_hash = my_string.json
# you can filter and get what you want even when nested with arrays
vals = my_string.json(:val1, :val2)
# even you can access the keys like this:
puts my_hash._val1
puts my_hash.val1
puts my_hash[:val1]
Using the latest 7.x Tomcat (currently 7.0.69) solved the problem for me.
We did also try a workaround in a old eclipse bug, maybe that did it's part to solve the problem, too?
https://bugs.eclipse.org/bugs/show_bug.cgi?id=67414
Workaround:
Accessing package variables in a Script Component (of a Data Flow Task) is not the same as accessing package variables in a Script Task. For a Script Component, you first need to open the Script Transformation Editor (right-click on the component and select "Edit..."). In the Custom Properties section of the Script tab, you can enter (or select) the properties you want to make available to the script, either on a read-only or read-write basis: Then, within the script itself, the variables will be available as strongly-typed properties of the Variables object:
// Modify as necessary
public override void PreExecute()
{
base.PreExecute();
string thePath = Variables.FilePath;
// Do something ...
}
public override void PostExecute()
{
base.PostExecute();
string theNewValue = "";
// Do something to figure out the new value...
Variables.FilePath = theNewValue;
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string thePath = Variables.FilePath;
// Do whatever needs doing here ...
}
One important caveat: if you need to write to a package variable, you can only do so in the PostExecute() method.
Regarding the code snippet:
IDTSVariables100 varCollection = null;
this.VariableDispenser.LockForRead("User::FilePath");
string XlsFile;
XlsFile = varCollection["User::FilePath"].Value.ToString();
varCollection
is initialized to null and never set to a valid value. Thus, any attempt to dereference it will fail.
Following work for me:
Keep following setting blank if you have made in build.gradle.
signingConfigs {
release {
storePassword ""
keyAlias ""
keyPassword ""
}
}
and choose Gradle Task from your Editor window. It will show list of all flavor if you have created.
async
methods are different than normal methods. Whatever you return from async
methods are wrapped in a Task
.
If you return no value(void) it will be wrapped in Task
, If you return int
it will be wrapped in Task<int>
and so on.
If your async method needs to return int
you'd mark the return type of the method as Task<int>
and you'll return plain int
not the Task<int>
. Compiler will convert the int
to Task<int>
for you.
private async Task<int> MethodName()
{
await SomethingAsync();
return 42;//Note we return int not Task<int> and that compiles
}
Sameway, When you return Task<object>
your method's return type should be Task<Task<object>>
public async Task<Task<object>> MethodName()
{
return Task.FromResult<object>(null);//This will compile
}
Since your method is returning Task
, it shouldn't return any value. Otherwise it won't compile.
public async Task MethodName()
{
return;//This should work but return is redundant and also method is useless.
}
Keep in mind that async method without an await
statement is not async
.
suprised this doesn't have an answer using pathilib which was introduced in python 3.4
+
additionally, shutil updated in python 3.6
to accept a pathlib object more details in this PEP-0519
from pathlib import Path
src_path = '\tmp\files_to_move'
for each_file in Path(src_path).glob('*.*'): # grabs all files
trg_path = each_file.parent.parent # gets the parent of the folder
each_file.rename(trg_path.joinpath(each_file.name)) # moves to parent folder.
from pathlib import Path
import shutil
src_path = '\tmp\files_to_move'
trg_path = '\tmp'
for src_file in Path(src_path).glob('*.*'):
shutil.copy(src_file, trg_path)
Important: Please consider upgrading to MySQL 8+ and use the defined and documented ROW_NUMBER() function, and ditch old hacks tied to a feature limited ancient version of MySQL
Now here's one of those hacks:
The answers here that use in-query variables mostly/all seem to ignore the fact that the documentation says (paraphrase):
Don't rely on items in the SELECT list being evaluated in order from top to bottom. Don't assign variables in one SELECT item and use them in another one
As such, there's a risk they will churn out the wrong answer, because they typically do a
select
(row number variable that uses partition variable),
(assign partition variable)
If these are ever evaluated bottom up, the row number will stop working (no partitions)
So we need to use something with a guaranteed order of execution. Enter CASE WHEN:
SELECT
t.*,
@r := CASE
WHEN col = @prevcol THEN @r + 1
WHEN (@prevcol := col) = null THEN null
ELSE 1 END AS rn
FROM
t,
(SELECT @r := 0, @prevcol := null) x
ORDER BY col
As outline ld, order of assignment of prevcol is important - prevcol has to be compared to the current row's value before we assign it a value from the current row (otherwise it would be the current rows col value, not the previous row's col value).
Here's how this fits together:
The first WHEN is evaluated. If this row's col is the same as the previous row's col then @r is incremented and returned from the CASE. This return led values is stored in @r. It's a feature of MySQL that assignment returns the new value of what is assigned into @r into the result rows.
For the first row on the result set, @prevcol is null (it is initialised to null in the subquery) so this predicate is false. This first predicate also returns false every time col changes (current row is different to previous row). This causes the second WHEN to be evaluated.
The second WHEN predicate is always false, and it exists purely to assign a new value to @prevcol. Because this row's col is different to the previous row's col (we know this because if it were the same, the first WHEN would have been used), we have to assign the new value to keep it for testing next time. Because the assignment is made and then the result of the assignment is compared with null, and anything equated with null is false, this predicate is always false. But at least evaluating it did its job of keeping the value of col from this row, so it can be evaluated against the next row's col value
Because the second WHEN is false, it means in situations where the column we are partitioning by (col) has changed, it is the ELSE that gives a new value for @r, restarting the numbering from 1
We this get to a situation where this:
SELECT
t.*,
ROW_NUMBER() OVER(PARTITION BY pcol1, pcol2, ... pcolX ORDER BY ocol1, ocol2, ... ocolX) rn
FROM
t
Has the general form:
SELECT
t.*,
@r := CASE
WHEN col1 = @pcol1 AND col2 = @pcol2 AND ... AND colX = @pcolX THEN @r + 1
WHEN (@pcol1 := pcol1) = null OR (@pcol2 := col2) = null OR ... OR (@pcolX := colX) = null THEN null
ELSE 1
END AS rn
FROM
t,
(SELECT @r := 0, @pcol1 := null, @pcol2 := null, ..., @pcolX := null) x
ORDER BY pcol1, pcol2, ..., pcolX, ocol1, ocol2, ..., ocolX
Footnotes:
The p in pcol means "partition", the o in ocol means "order" - in the general form I dropped the "prev" from the variable name to reduce visual clutter
The brackets around (@pcolX := colX) = null
are important. Without them you'll assign null to @pcolX and things stop working
It's a compromise that the result set has to be ordered by the partition columns too, for the previous column compare to work out. You can't thus have your rownumber ordered according to one column but your result set ordered to another You might be able to resolve this with subqueries but I believe the docs also state that subquery ordering may be ignored unless LIMIT is used and this could impact performance
I haven't delved into it beyond testing that the method works, but if there is a risk that the predicates in the second WHEN will be optimised away (anything compared to null is null/false so why bother running the assignment) and not executed, it also stops. This doesn't seem to happen in my experience but I'll gladly accept comments and propose solution if it could reasonably occur
It may be wise to cast the nulls that create @pcolX to the actual types of your columns, in the subquery that creates the @pcolX variables, viz: select @pcol1 := CAST(null as INT), @pcol2 := CAST(null as DATE)
If you are using CMS like Drupal or Wordpress - just install jQuery Update module and error no longer persists.
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
I don't know if the question is just too old, but setting window.location to a download url will work, as long as the download mime type is correct (for example a zip archive).
var download = function(downloadURL) {
location = downloadURL;
});
download('http://example.com/archive.zip'); //correct usage
download('http://example.com/page.html'); //DON'T
git reset --hard
This is to revert all your local changes to the origin head
system ('/usr/bin/pdfcrop filename.pdf');
Here is an easy way to do so using HTMLBuilder
myTextView.setText(new HtmlBuilder().
open(HtmlBuilder.Type.BOLD).
append("Some bold text ").
close(HtmlBuilder.Type.BOLD).
open(HtmlBuilder.Type.ITALIC).
append("Some italic text").
close(HtmlBuilder.Type.ITALIC).
build()
);
Result:
Some bold text Some italic text
To summarize the above post by Cheers and hth. - Alf, Make sure you have main()
or WinMain()
defined and g++ should do the right thing.
My problem was that main()
was defined inside of a namespace by accident.
There is an option “unlimited scrollback buffer” which you can find under Preferences > Profiles > Terminal
or you can just pump up number of lines that you want to have in history in the same place.
Actually I used my script in html directly. But in javascript when you add oninput event listener for this event it gives the data automatically.You just need to assign the value as per your requirement.
[slider] {_x000D_
width: 300px;_x000D_
position: relative;_x000D_
height: 5px;_x000D_
margin: 45px 0 10px 0;_x000D_
}_x000D_
_x000D_
[slider] > div {_x000D_
position: absolute;_x000D_
left: 13px;_x000D_
right: 15px;_x000D_
height: 5px;_x000D_
}_x000D_
[slider] > div > [inverse-left] {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
height: 5px;_x000D_
border-radius: 10px;_x000D_
background-color: #CCC;_x000D_
margin: 0 7px;_x000D_
}_x000D_
_x000D_
[slider] > div > [inverse-right] {_x000D_
position: absolute;_x000D_
right: 0;_x000D_
height: 5px;_x000D_
border-radius: 10px;_x000D_
background-color: #CCC;_x000D_
margin: 0 7px;_x000D_
}_x000D_
_x000D_
_x000D_
[slider] > div > [range] {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
height: 5px;_x000D_
border-radius: 14px;_x000D_
background-color: #d02128;_x000D_
}_x000D_
_x000D_
[slider] > div > [thumb] {_x000D_
position: absolute;_x000D_
top: -7px;_x000D_
z-index: 2;_x000D_
height: 20px;_x000D_
width: 20px;_x000D_
text-align: left;_x000D_
margin-left: -11px;_x000D_
cursor: pointer;_x000D_
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.4);_x000D_
background-color: #FFF;_x000D_
border-radius: 50%;_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
[slider] > input[type=range] {_x000D_
position: absolute;_x000D_
pointer-events: none;_x000D_
-webkit-appearance: none;_x000D_
z-index: 3;_x000D_
height: 14px;_x000D_
top: -2px;_x000D_
width: 100%;_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]:focus::-webkit-slider-runnable-track {_x000D_
background: transparent;_x000D_
border: transparent;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]:focus {_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]::-webkit-slider-thumb {_x000D_
pointer-events: all;_x000D_
width: 28px;_x000D_
height: 28px;_x000D_
border-radius: 0px;_x000D_
border: 0 none;_x000D_
background: red;_x000D_
-webkit-appearance: none;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]::-ms-fill-lower {_x000D_
background: transparent;_x000D_
border: 0 none;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]::-ms-fill-upper {_x000D_
background: transparent;_x000D_
border: 0 none;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]::-ms-tooltip {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
[slider] > div > [sign] {_x000D_
opacity: 0;_x000D_
position: absolute;_x000D_
margin-left: -11px;_x000D_
top: -39px;_x000D_
z-index:3;_x000D_
background-color: #d02128;_x000D_
color: #fff;_x000D_
width: 28px;_x000D_
height: 28px;_x000D_
border-radius: 28px;_x000D_
-webkit-border-radius: 28px;_x000D_
align-items: center;_x000D_
-webkit-justify-content: center;_x000D_
justify-content: center;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
[slider] > div > [sign]:after {_x000D_
position: absolute;_x000D_
content: '';_x000D_
left: 0;_x000D_
border-radius: 16px;_x000D_
top: 19px;_x000D_
border-left: 14px solid transparent;_x000D_
border-right: 14px solid transparent;_x000D_
border-top-width: 16px;_x000D_
border-top-style: solid;_x000D_
border-top-color: #d02128;_x000D_
}_x000D_
_x000D_
[slider] > div > [sign] > span {_x000D_
font-size: 12px;_x000D_
font-weight: 700;_x000D_
line-height: 28px;_x000D_
}_x000D_
_x000D_
[slider]:hover > div > [sign] {_x000D_
opacity: 1;_x000D_
}
_x000D_
<div slider id="slider-distance">_x000D_
<div>_x000D_
<div inverse-left style="width:70%;"></div>_x000D_
<div inverse-right style="width:70%;"></div>_x000D_
<div range style="left:0%;right:0%;"></div>_x000D_
<span thumb style="left:0%;"></span>_x000D_
<span thumb style="left:100%;"></span>_x000D_
<div sign style="left:0%;">_x000D_
<span id="value">0</span>_x000D_
</div>_x000D_
<div sign style="left:100%;">_x000D_
<span id="value">100</span>_x000D_
</div>_x000D_
</div>_x000D_
<input type="range" value="0" max="100" min="0" step="1" oninput="_x000D_
this.value=Math.min(this.value,this.parentNode.childNodes[5].value-1);_x000D_
let value = (this.value/parseInt(this.max))*100_x000D_
var children = this.parentNode.childNodes[1].childNodes;_x000D_
children[1].style.width=value+'%';_x000D_
children[5].style.left=value+'%';_x000D_
children[7].style.left=value+'%';children[11].style.left=value+'%';_x000D_
children[11].childNodes[1].innerHTML=this.value;" />_x000D_
_x000D_
<input type="range" value="100" max="100" min="0" step="1" oninput="_x000D_
this.value=Math.max(this.value,this.parentNode.childNodes[3].value-(-1));_x000D_
let value = (this.value/parseInt(this.max))*100_x000D_
var children = this.parentNode.childNodes[1].childNodes;_x000D_
children[3].style.width=(100-value)+'%';_x000D_
children[5].style.right=(100-value)+'%';_x000D_
children[9].style.left=value+'%';children[13].style.left=value+'%';_x000D_
children[13].childNodes[1].innerHTML=this.value;" />_x000D_
</div>
_x000D_
My Team built a command line tool for uploading artifacts to nexus 3.x repository, Maybe it's will be helpful for you - Maven Artifacts Uploader
Modernizr doesn't actually change anything about how the new HTML5 input types are handled. It's a feature detector, not a shim (except for <header>
, <article>
, etc., which it shims to be handled as block elements similar to <div>
).
To use <input type='date'>
, you'd need to check Modernizr.inputtypes.date
in your own script, and if it's false, turn on another plugin that provides a date selector. You have thousands to choose from; Modernizr maintains a non-exhaustive list of polyfills that might give you somewhere to start. Alternatively, you could just let it go - all browsers fall back to text
when presented with an input type they don't recognize, so the worst that can happen is that your user has to type in the date. (You might want to give them a placeholder or use something like jQuery.maskedinput to keep them on track.)
Another option could be using automapper: You will be converting to any type from your anonymous returned object as long public properties matches. The key points are, returning object, use linq and autommaper. (or use similar idea returning serialized json, etc. or use reflection..)
using System.Linq;
using System.Reflection;
using AutoMapper;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var data = GetData();
var firts = data.First();
var info = firts.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).First(p => p.Name == "Name");
var value = info.GetValue(firts);
Assert.AreEqual(value, "One");
}
[TestMethod]
public void TestMethod2()
{
var data = GetData();
var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);
var mapper = config.CreateMapper();
var users = data.Select(mapper.Map<User>).ToArray();
var firts = users.First();
Assert.AreEqual(firts.Name, "One");
}
[TestMethod]
public void TestMethod3()
{
var data = GetJData();
var users = JsonConvert.DeserializeObject<User[]>(data);
var firts = users.First();
Assert.AreEqual(firts.Name, "One");
}
private object[] GetData()
{
return new[] { new { Id = 1, Name = "One" }, new { Id = 2, Name = "Two" } };
}
private string GetJData()
{
return JsonConvert.SerializeObject(new []{ new { Id = 1, Name = "One" }, new { Id = 2, Name = "Two" } }, Formatting.None);
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
}
}
The answer probably depends on what format your date is in, but here is an example using the Date
class:
dt <- as.Date("2010/02/10")
new.dt <- dt - as.difftime(2, unit="days")
You can even play with different units like weeks.
Have a look at the following
@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
your controller should have action method which would accept HttpPostedFileBase
;
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~/images/profile"), pic);
// file is uploaded
file.SaveAs(path);
// save the image path path to the database or you can send image
// directly to database
// in-case if you want to store byte[] ie. for DB
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
}
// after successfully uploading redirect the user
return RedirectToAction("actionname", "controller name");
}
Update 1
In case you want to upload files using jQuery with asynchornously, then try this article.
the code to handle the server side (for multiple upload) is;
try
{
HttpFileCollection hfc = HttpContext.Current.Request.Files;
string path = "/content/files/contact/";
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileName = "";
if (Request.Browser.Browser == "IE")
{
fileName = Path.GetFileName(hpf.FileName);
}
else
{
fileName = hpf.FileName;
}
string fullPathWithFileName = path + fileName;
hpf.SaveAs(Server.MapPath(fullPathWithFileName));
}
}
}
catch (Exception ex)
{
throw ex;
}
this control also return image name (in a javascript call back) which then you can use it to display image in the DOM.
Alternatively, you can try Async File Uploads in MVC 4.
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
If you prefer not to use JQuery:
function removeElementsByClass(className){
var elements = document.getElementsByClassName(className);
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
}
I didn't like how I had to explicitly specify all the other column in the other solutions so this worked best for me. Though it might be slow for large dataframes...?
df = df.set_index('Mid').reset_index()
I know that if you were to change that to an href you'd do:
$("a#link1").click(function(event) { event.preventDefault(); $('div.link1').show(); //whatever else you want to do });
so if you want to keep it with the div, I'd try
$("div.clickable").click(function(event) { event.preventDefault(); window.location = $(this).attr("url"); });
In newer versions of Eclipse that use the M2E plugin it is:
Right-click on your project(s) --> Maven --> Update Project...
In the following dialog is a checkbox for forcing the update ("Force Update of Snapshots/Releases")
I think the problem is in your JOIN
condition.
SELECT user.user_fname,
user.user_lname,
parent.user_fname,
parent.user_lname
FROM users AS user
JOIN users AS parent
ON parent.user_id = user.user_parent_id
WHERE user.user_id = $_GET[id]
Edit:
You should probably use LEFT JOIN
if there are users with no parents.
You need to use html helper, and you don't need to provide date format in model class. e.x :
@Html.TextBoxFor(m => m.ResgistrationhaseDate, "{0:dd/MM/yyyy}")
I've developed an almost flawless try & catch implementation in bash, that allows you to write code like:
try
echo 'Hello'
false
echo 'This will not be displayed'
catch
echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"
You can even nest the try-catch blocks inside themselves!
try {
echo 'Hello'
try {
echo 'Nested Hello'
false
echo 'This will not execute'
} catch {
echo "Nested Caught (@ $__EXCEPTION_LINE__)"
}
false
echo 'This will not execute too'
} catch {
echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"
}
The code is a part of my bash boilerplate/framework. It further extends the idea of try & catch with things like error handling with backtrace and exceptions (plus some other nice features).
Here's the code that's responsible just for try & catch:
set -o pipefail
shopt -s expand_aliases
declare -ig __oo__insideTryCatch=0
# if try-catch is nested, then set +e before so the parent handler doesn't catch us
alias try="[[ \$__oo__insideTryCatch -gt 0 ]] && set +e;
__oo__insideTryCatch+=1; ( set -e;
trap \"Exception.Capture \${LINENO}; \" ERR;"
alias catch=" ); Exception.Extract \$? || "
Exception.Capture() {
local script="${BASH_SOURCE[1]#./}"
if [[ ! -f /tmp/stored_exception_source ]]; then
echo "$script" > /tmp/stored_exception_source
fi
if [[ ! -f /tmp/stored_exception_line ]]; then
echo "$1" > /tmp/stored_exception_line
fi
return 0
}
Exception.Extract() {
if [[ $__oo__insideTryCatch -gt 1 ]]
then
set -e
fi
__oo__insideTryCatch+=-1
__EXCEPTION_CATCH__=( $(Exception.GetLastException) )
local retVal=$1
if [[ $retVal -gt 0 ]]
then
# BACKWARDS COMPATIBILE WAY:
# export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-1)]}"
# export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-2)]}"
export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[-1]}"
export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[-2]}"
export __EXCEPTION__="${__EXCEPTION_CATCH__[@]:0:(${#__EXCEPTION_CATCH__[@]} - 2)}"
return 1 # so that we may continue with a "catch"
fi
}
Exception.GetLastException() {
if [[ -f /tmp/stored_exception ]] && [[ -f /tmp/stored_exception_line ]] && [[ -f /tmp/stored_exception_source ]]
then
cat /tmp/stored_exception
cat /tmp/stored_exception_line
cat /tmp/stored_exception_source
else
echo -e " \n${BASH_LINENO[1]}\n${BASH_SOURCE[2]#./}"
fi
rm -f /tmp/stored_exception /tmp/stored_exception_line /tmp/stored_exception_source
return 0
}
Feel free to use, fork and contribute - it's on GitHub.
Do ctrl+F5 to compile and run your project without debugging. Look at the output pane (defaults to "Show output from Build"). If it compiled successfully, the path to the .exe file should be there after {projectname}.vcxproj ->
Update in 2019:
This is now officially supported in Visual Studio 2019 Preview 2 for .Net Core 3.0 or higher. Of course, you may have to put some thoughts in potential risks of using a Preview version of IDE. I imagine in the near future this will be included in the official Visual Studio.
Fortunately, data breakpoints are no longer a C++ exclusive because they are now available for .NET Core (3.0 or higher) in Visual Studio 2019 Preview 2!
You can't verify (with enough accuracy to rely on) if an email actually exists using just a single PHP method. You can send an email to that account, but even that alone won't verify the account exists (see below). You can, at least, verify it's at least formatted like one
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//Email is valid
}
You can add another check if you want. Parse the domain out and then run checkdnsrr
if(checkdnsrr($domain)) {
// Domain at least has an MX record, necessary to receive email
}
Many people get to this point and are still unconvinced there's not some hidden method out there. Here are some notes for you to consider if you're bound and determined to validate email:
Spammers also know the "connection trick" (where you start to send an email and rely on the server to bounce back at that point). One of the other answers links to this library which has this caveat
Some mail servers will silently reject the test message, to prevent spammers from checking against their users' emails and filter the valid emails, so this function might not work properly with all mail servers.
In other words, if there's an invalid address you might not get an invalid address response. In fact, virtually all mail servers come with an option to accept all incoming mail (here's how to do it with Postfix). The answer linking to the validation library neglects to mention that caveat.
Spam blacklists. They blacklist by IP address and if your server is constantly doing verification connections you run the risk of winding up on Spamhaus or another block list. If you get blacklisted, what good does it do you to validate the email address?
If it's really that important to verify an email address, the accepted way is to force the user to respond to an email. Send them a full email with a link they have to click to be verified. It's not spammy, and you're guaranteed that any responses have a valid address.
You can't follow the cursor with a DIV
, but you can draw a DIV
when moving the cursor!
$(document).on('mousemove', function(e){
$('#your_div_id').css({
left: e.pageX,
top: e.pageY
});
});
That div must be off the float, so position: absolute
should be set.
This work for me!
public void showLoader(){
URL url = this.getClass().getResource("images/ajax-loader.gif");
Icon icon = new ImageIcon(url);
JLabel label = new JLabel(icon);
frameLoader.setUndecorated(true);
frameLoader.getContentPane().add(label);
frameLoader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameLoader.pack();
frameLoader.setLocationRelativeTo(null);
frameLoader.setVisible(true);
}
Yes, many changes at Heroku. If you're using a Heroku dyno for your webserver, you have to find way to alias from one DNS
name to another DNS
name (since each Heroku DNS endpoint may resolve to many IP addrs to dynamically adjust to request loads).
A CNAME
record is for aliasing www.example.com
-> www.example.com.herokudns.com.
You can't use CNAME
for a naked domain (@
), i.e. example.com
(unless you find a name server that can do CNAME Flattening
- which is what I did).
But really the easiest solution, that can pretty much be taken care of all in your GoDaddy account, is to create a CNAME record
that does this: www.example.com -> www.example.com.herokudns.com
.
And then create a permanent 301 redirect from example.com
to www.example.com
.
This requires only one heroku custom domain name configured in your heroku app settings: www.example.com.herokudns.com
. @Jonathan Roy talks about this (above) but provides a bad link.
The key information is written in @Sam's answer but not really salient, so let's make it clear.
The line which appears even without -v
switch:
ssh: connect to host (some host or IP address) port 22: Bad file number
is actually irrelevant.
If you focus on it you'll waste your time as it is not a hint about what the actual problem is, just an effect of running git's ssh on Windows. It's not even a sign that the git or ssh install or configuration is wrong. Really, ignore it.
The very same command on Linux produced instead this message for me, which gave an actual hint about the problem:
ssh: connect to host (some host or IP address) port 22: Connection timed out
Focus on lines being added with -v
on command line. In my case it was:
debug1: connect to address (some host or IP address) port 22: Attempt to connect timed out without establishing a connection
My problem was a typo in the IP address, but yours may be different.
If someone can prove that "bad file number" only appears when the actual reason is "connection time out" then it makes some sense to address why connection could time out.
Until that, "bad file number" is only a generic error message and this question is fully answered by saying "ignore it and look for other error messages".
EDIT: Qwertie mentioned that the error message is indeed generic, as it can happen on "Connection refused" also. This confirms the analysis.
Please don't clutter this question with general hints and answer, they have nothing to do with the actual topic (and title) of this question which is "Git SSH error: “Connect to host: Bad file number”". If using -v
you have more informative message that deserve their own question, then open another question, then you can make a link to it.
Since the previous instructions for installing with yum are broken here are the updated instructions for installing on something like fedora. I've tested this on "Amazon Linux AMI 2016.03"
sudo yum install atlas-devel lapack-devel blas-devel libgfortran
pip install scipy
move
in windows is equivalent of mv
command in Linux
del
in windows is equivalent of rm
command in Linux
I think this is the most reliable way to get the desktop path which isn't always the same as the username.
MsgBox CreateObject("WScript.Shell").specialfolders("Desktop")
<a href="#" onclick="window.open('MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>
The above link will open the PDF in full screen mode, that's the best you can achieve.
Its possible using pseudo element (after).
I have added to the original code a
position:relativeand some margin.
#content{
width: 100px;
min-height: 100px;
margin: 20px auto;
border-style: ridge;
border-color: #567498;
border-spacing:10px;
position:relative;
background:#000;
}
#content:after {
content: '';
position: absolute;
top: -15px;
left: -15px;
right: -15px;
bottom: -15px;
border: red 2px solid;
}
All of the above solutions recognize a string like "http://www.google.com/path,www.yahoo.com/path" as valid. This solution always works as it should
import re
# URL-link validation
ip_middle_octet = u"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5]))"
ip_last_octet = u"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))"
URL_PATTERN = re.compile(
u"^"
# protocol identifier
u"(?:(?:https?|ftp|rtsp|rtp|mmp)://)"
# user:pass authentication
u"(?:\S+(?::\S*)?@)?"
u"(?:"
u"(?P<private_ip>"
# IP address exclusion
# private & local networks
u"(?:localhost)|"
u"(?:(?:10|127)" + ip_middle_octet + u"{2}" + ip_last_octet + u")|"
u"(?:(?:169\.254|192\.168)" + ip_middle_octet + ip_last_octet + u")|"
u"(?:172\.(?:1[6-9]|2\d|3[0-1])" + ip_middle_octet + ip_last_octet + u"))"
u"|"
# IP address dotted notation octets
# excludes loopback network 0.0.0.0
# excludes reserved space >= 224.0.0.0
# excludes network & broadcast addresses
# (first & last IP address of each class)
u"(?P<public_ip>"
u"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])"
u"" + ip_middle_octet + u"{2}"
u"" + ip_last_octet + u")"
u"|"
# host name
u"(?:(?:[a-z\u00a1-\uffff0-9_-]-?)*[a-z\u00a1-\uffff0-9_-]+)"
# domain name
u"(?:\.(?:[a-z\u00a1-\uffff0-9_-]-?)*[a-z\u00a1-\uffff0-9_-]+)*"
# TLD identifier
u"(?:\.(?:[a-z\u00a1-\uffff]{2,}))"
u")"
# port number
u"(?::\d{2,5})?"
# resource path
u"(?:/\S*)?"
# query string
u"(?:\?\S*)?"
u"$",
re.UNICODE | re.IGNORECASE
)
def url_validate(url):
""" URL string validation
"""
return re.compile(URL_PATTERN).match(url)
In Python inside there is a good use of container called a named tuple, it can be used to create a definition of class and has all the features of the original tuple.
Using named tuple will be directly applied to the default class template to generate a simple class, this method allows a lot of code to improve readability and it is also very convenient when defining a class.
Don't use localhost in the url!
Use like this:
Here is a version that will log to the console when the developer tools are open and not when they are closed.
(function(window) {
var console = {};
console.log = function() {
if (window.console && (typeof window.console.log === 'function' || typeof window.console.log === 'object')) {
window.console.log.apply(window, arguments);
}
}
// Rest of your application here
})(window)
I know this is an old thread, but I just spent 3 hours trying to figure out what my issue was. I ordinarily know what this error means, but you can run into this in a more subtle way as well. My issue was my client class (the one calling a static method from an instance class) had a property of a different type but named the same as the static method. The error reported by the compiler was the same as reported here, but the issue was basically name collision.
For anyone else getting this error and none of the above helps, try fully qualifying your instance class with the namespace name. ..() so the compiler can see the exact name you mean.
I believe this will solve the issue
var z = '[{"name":"1","age":"2"},{"name":"1","age":"3"}]';
z = JSON.stringify(JSON.parse(z));
$.ajax({
url: "/setTest",
data: z,
type: "POST",
dataType:"json",
contentType:'application/json'
});
You need to add your tiles into your resource bundle. I mean add all those files to your project make sure to copy all files to project directory option checked.
I observed that only one word distinguishes Safari - "Version". So this regex will work perfect:
/.*Version.*Safari.*/.test(navigator.userAgent)
When you select a radio button and click on a submit button, you need to handle the submission of any selected values in your php code using $_POST[]
For example:
if your radio button is:
<input type="radio" name="rdb" value="male"/>
then in your php code you need to use:
$rdb_value = $_POST['rdb'];
string Camnr , Klantnr , Ordernr , Bonnr , Volgnr , Omschrijving , Startdatum , Bonprioriteit , Matsoort , Dikte , Draaibaarheid , Draaiomschrijving , Orderleverdatum , Regeltaakkode , Gebruiksvoorkeur , Regelcamprog , Regeltijd , Orderrelease;
Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = Startdatum = Bonprioriteit = Matsoort = Dikte = Draaibaarheid = Draaiomschrijving = Orderleverdatum = Regeltaakkode = Gebruiksvoorkeur = Regelcamprog = Regeltijd = Orderrelease = string.Empty;
The best bet is to start off with tel: which works on all mobiles
Then put in this code, which will only run when on a desktop, and only when a link is clicked.
I'm using http://detectmobilebrowsers.com/ to detect mobile browsers, you can use whatever method you prefer
if (!jQuery.browser.mobile) {
jQuery('body').on('click', 'a[href^="tel:"]', function() {
jQuery(this).attr('href',
jQuery(this).attr('href').replace(/^tel:/, 'callto:'));
});
}
So basically you cover all your bases.
tel: works on all phones to open the dialer with the number
callto: works on your computer to connect to skype from firefox, chrome
This error happens when you are also missing cmd.CommandType = System.Data.CommandType.StoredProcedure;
In Javascript :
document.getElementById('searchField').value = '';
In jQuery :
$('#searchField').val('');
That should do it
The parent div (I assume the outermost div) is display: block
and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block
is probably what you are going for:
First, You will need to import sys
sys - System-specific parameters and functions
This module provides access to certain variables used and maintained by the interpreter, and to functions that interact strongly with the interpreter. This module is still available. I will edit this post in case this module is not working anymore.
And then, you can print the numbers of arguments or what you want here, the list of arguments.
Follow the script below :
#!/usr/bin/python
import sys
print 'Number of arguments entered :' len(sys.argv)
print 'Your argument list :' str(sys.argv)
Then, run your python script :
$ python arguments_List.py chocolate milk hot_Chocolate
And you will have the result that you were asking :
Number of arguments entered : 4
Your argument list : ['arguments_List.py', 'chocolate', 'milk', 'hot_Chocolate']
Hope that helped someone.
For CodeIgniter 3
<form action="<?php echo base_url('index.php/TestingController/insertdata') ?>" method="POST"
enctype="multipart/form-data">
<div class="form-group">
<label for="">title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="">File</label>
<input type="file" name="files" id="files" class="form-control">
</div>
<input type="submit" value="Submit" class="btn btn-primary">
</form>
public function insertdatanew()
{
$this->load->library('upload');
$files = $_FILES;
$cpt = count($_FILES['filesdua']['name']);
for ($i = 0; $i < $cpt; $i++) {
$_FILES['filesdua']['name'] = $files['filesdua']['name'][$i];
$_FILES['filesdua']['type'] = $files['filesdua']['type'][$i];
$_FILES['filesdua']['tmp_name'] = $files['filesdua']['tmp_name'][$i];
$_FILES['filesdua']['error'] = $files['filesdua']['error'][$i];
$_FILES['filesdua']['size'] = $files['filesdua']['size'][$i];
// fungsi uploud
$config['upload_path'] = './uploads/testing/';
$config['allowed_types'] = '*';
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('filesdua')) {
$error = array('error' => $this->upload->display_errors());
var_dump($error);
// $this->load->view('welcome_message', $error);
} else {
// menambil nilai value yang di upload
$data = array('upload_data' => $this->upload->data());
$nilai = $data['upload_data'];
$filename = $nilai['file_name'];
var_dump($filename);
// $this->load->view('upload_success', $data);
}
}
// var_dump($cpt);
}
Try this
1) Window > Preferences > General > Content Types
, set UTF-8 as the
default encoding for all content types.
2) Window > Preferences > General > Workspace
, set Text file encoding
to Other : UTF-8
Update to angular 4.X.X, there is a new way to mark an option selected:
<select [compareWith]="byId" [(ngModel)]="selectedItem">
<option *ngFor="let item of items" [ngValue]="item">{{item.name}}
</option>
</select>
byId(item1: ItemModel, item2: ItemModel) {
return item1.id === item2.id;
}
Some tutorial here
My original question for this was how to both have an element of a fixed aspect, but to fit that within a specified container exactly, which makes it a little fiddly. If you simply want an individual element to maintain its aspect ratio it is a lot easier.
The best method I've come across is by giving an element zero height and then using percentage padding-bottom to give it height. Percentage padding is always proportional to the width of an element, and not its height, even if its top or bottom padding.
So utilising that you can give an element a percentage width to sit within a container, and then padding to specify the aspect ratio, or in other terms, the relationship between its width and height.
.object {
width: 80%; /* whatever width here, can be fixed no of pixels etc. */
height: 0px;
padding-bottom: 56.25%;
}
.object .content {
position: absolute;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
box-sizing: border-box;
-moz-box-sizing: border-box;
padding: 40px;
}
So in the above example the object takes 80% of the container width, and then its height is 56.25% of that value. If it's width was 160px then the bottom padding, and thus the height would be 90px - a 16:9 aspect.
The slight problem here, which may not be an issue for you, is that there is no natural space inside your new object. If you need to put some text in for example and that text needs to take it's own padding values you need to add a container inside and specify the properties in there.
Also vw and vh units aren't supported on some older browsers, so the accepted answer to my question might not be possible for you and you might have to use something more lo-fi.
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
setTimeout(callback,t)
is used to run callback after at least t millisecond. The actual delay depends on many external factors like OS timer granularity and system load.
So, there is a possibility that it will be called slightly after the set time, but will never be called before.
A timer can't span more than 24.8 days.
The scanner can also use delimiters other than whitespace.
Easy example from Scanner API:
String input = "1 fish 2 fish red fish blue fish";
// \\s* means 0 or more repetitions of any whitespace character
// fish is the pattern to find
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // prints: 1
System.out.println(s.nextInt()); // prints: 2
System.out.println(s.next()); // prints: red
System.out.println(s.next()); // prints: blue
// don't forget to close the scanner!!
s.close();
The point is to understand the regular expressions (regex
) inside the Scanner::useDelimiter
. Find an useDelimiter
tutorial here.
To start with regular expressions here you can find a nice tutorial.
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(ab|cd) Matches ab or cd
Following
$(document).ready(function() {
});
can be replaced
$(window).bind("load", function() {
// insert your code here
});
There is once more way which i'm using to increase the page load time.
$(document).ready(function() {
$(window).load(function() {
//insert all your ajax callback code here.
//Which will run only after page is fully loaded in background.
});
});
I have extended the mixin of @livskiy as follows:
class ModelDiffMixin(models.Model):
"""
A model mixin that tracks model fields' values and provide some useful api
to know what fields have been changed.
"""
_dict = DictField(editable=False)
def __init__(self, *args, **kwargs):
super(ModelDiffMixin, self).__init__(*args, **kwargs)
self._initial = self._dict
@property
def diff(self):
d1 = self._initial
d2 = self._dict
diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
return dict(diffs)
@property
def has_changed(self):
return bool(self.diff)
@property
def changed_fields(self):
return self.diff.keys()
def get_field_diff(self, field_name):
"""
Returns a diff for field if it's changed and None otherwise.
"""
return self.diff.get(field_name, None)
def save(self, *args, **kwargs):
"""
Saves model and set initial state.
"""
object_dict = model_to_dict(self,
fields=[field.name for field in self._meta.fields])
for field in object_dict:
# for FileFields
if issubclass(object_dict[field].__class__, FieldFile):
try:
object_dict[field] = object_dict[field].path
except :
object_dict[field] = object_dict[field].name
# TODO: add other non-serializable field types
self._dict = object_dict
super(ModelDiffMixin, self).save(*args, **kwargs)
class Meta:
abstract = True
and the DictField is:
class DictField(models.TextField):
__metaclass__ = models.SubfieldBase
description = "Stores a python dict"
def __init__(self, *args, **kwargs):
super(DictField, self).__init__(*args, **kwargs)
def to_python(self, value):
if not value:
value = {}
if isinstance(value, dict):
return value
return json.loads(value)
def get_prep_value(self, value):
if value is None:
return value
return json.dumps(value)
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
it can be used by extending it in your models a _dict field will be added when you sync/migrate and that field will store the state of your objects
You want rows where that condition is true so you need a comma:
data[data$Ozone > 14, ]
If you are looking for only attributes, then you can get them by:
@post.attributes
Note that this calls ActiveModel::AttributeSet.to_hash
every time you invoke it, so if you need to access the hash multiple times you should cache it in a local variable:
attribs = @post.attributes
Swift 4
let combination = NSMutableAttributedString()
var part1 = NSMutableAttributedString()
var part2 = NSMutableAttributedString()
var part3 = NSMutableAttributedString()
let attrRegular = [NSAttributedStringKey.font : UIFont(name: "Palatino-Roman", size: 15)]
let attrBold:Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15)]
let attrBoldWithColor: Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15),
NSAttributedStringKey.foregroundColor: UIColor.red]
if let regular = attrRegular as? [NSAttributedStringKey : NSObject]{
part1 = NSMutableAttributedString(string: "first", attributes: regular)
}
if let bold = attrRegular as? [NSAttributedStringKey : NSObject]{
part2 = NSMutableAttributedString(string: "second", attributes: bold)
}
if let boldWithColor = attrBoldWithColor as? [NSAttributedStringKey : NSObject]{
part3 = NSMutableAttributedString(string: "third", attributes: boldWithColor)
}
combination.append(part1)
combination.append(part2)
combination.append(part3)
Attributes list please see here NSAttributedStringKey on Apple Docs
Some minor additional content for setting programmatically:
Label textLabel = new Label() {
AutoSize = false,
TextAlign = ContentAlignment.MiddleCenter,
Dock = DockStyle.None,
Left = 10,
Width = myDialog.Width - 10
};
Dockstyle and Content alignment may differ from your needs. For example, for a simple label on a wpf form I use DockStyle.None.
I know this thread is a year old, but the real problem is in your working directory.
I believe that the working directory is C:\Users\Administrator\Documents\Mibot\oops\
. Please check for the file named socket.py
in this directory. Once you find it, rename or move it. When you import socket, socket.py
from the current directory is used instead of the socket.py
from Python's directory. Hope this helped. :)
Note: Never use the file names from Python's directory to save your program's file name; it will conflict with your program(s).
Try using this: On the command line, in your home directory, create a directory for global installations:
mkdir ~/.npm-global
Configure npm to use the new directory path:
npm config set prefix '~/.npm-global'
In your preferred text editor, open or create a ~/.profile file and add this line:
export PATH=~/.npm-global/bin:$PATH
On the command line, update your system variables:
source ~/.profile
Now use npm install it should work.
I agree with Chris-Jr. If you are using Firebase to embed your AdMob ads (or even if you are not) the play-services-analytics includes the play-services-ads even though you don't add that as a dependency. Google have obviously made a mistake in their 11.4.0 roll-out as the analytics is including version 10.0.1 of ads, not 11.4.0 (the mouse over hint in the gradle shows this).
I manually added compile 'com.google.android.gms:play-services-ads:11.4.0' at the top which worked, but only after I disabled Instant Run: http://stackoverflow.com/a/35169716/530047
So its either regress to 10.0.1 or add the ads and disable Instant Run. That's what I found if it helps any.
Get Schema Name and Table Name from a database.
public IList<Tuple<string, string>> ListTables()
{
DataTable dt = con.GetSchema("Tables");
var tables = new List<Tuple<string, string>>();
foreach (DataRow row in dt.Rows)
{
string schemaName = (string)row[1];
string tableName = (string)row[2];
//AddToList();
tables.Add(Tuple.Create(schemaName, tableName));
Console.WriteLine(schemaName +" " + tableName) ;
}
return tables;
}
I've used this code which works quite well just do appendData and either pass a single byte with an array, or two arrays to combine them :
protected byte[] appendData(byte firstObject,byte[] secondObject){
byte[] byteArray= {firstObject};
return appendData(byteArray,secondObject);
}
protected byte[] appendData(byte[] firstObject,byte secondByte){
byte[] byteArray= {secondByte};
return appendData(firstObject,byteArray);
}
protected byte[] appendData(byte[] firstObject,byte[] secondObject){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
try {
if (firstObject!=null && firstObject.length!=0)
outputStream.write(firstObject);
if (secondObject!=null && secondObject.length!=0)
outputStream.write(secondObject);
} catch (IOException e) {
e.printStackTrace();
}
return outputStream.toByteArray();
}
input[type="checkbox"] {
/* your style */
}
But this will only work for browsers except IE7 and below, for those you will have to use a class.
Then just modify the previous answers to:
Console.Write(strToProcess.Replace("@", "@" + Environment.NewLine));
If you don't want the newlines in the text file, then don't preserve it.
UIPanGestureRecognizer * pan1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(moveObject:)];
pan1.minimumNumberOfTouches = 1;
[image1 addGestureRecognizer:pan1];
-(void)moveObject:(UIPanGestureRecognizer *)pan;
{
image1.center = [pan locationInView:image1.superview];
}
Here is a manual way to do git remote set-url origin [new repo URL]
:
git clone <old remote>
Open <repository>/.git/config
$ git config -e
[core]
repositoryformatversion = 0
filemode = false
bare = false
logallrefupdates = true
symlinks = false
ignorecase = true
[remote "origin"]
url = <old remote>
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
and change the remote (the url option)
[remote "origin"]
url = <new remote>
fetch = +refs/heads/*:refs/remotes/origin/*
Push the repository to GitHub: git push
You can also use both/multiple remotes.
Another trick not yet mentioned is to have the class which implements a property (e.g. Foo
of type Bar
) also define a delegate delegate void ActByRef<T1,T2>(ref T1 p1, ref T2 p2);
and implement a method ActOnFoo<TX1>(ref Bar it, ActByRef<Bar,TX1> proc, ref TX1 extraParam1)
(and possibly versions for two and three "extra parameters" as well) which will pass its internal representation of Foo
to the supplied procedure as a ref
parameter. This has a couple of big advantages over other methods of working with the property:
Passing things be ref
is an excellent pattern; too bad it's not used more.
I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
Left and top options will define the amount of padding from left and top. Hope this will help.
The jquery.selectboxes.js plugin has a sort method. You can implement the plugin, or dive into the code to see a way to sort the options.
To actually explain what happens:
The ADB executable has two components
When you start ADB for the first time you may notice a message like "starting ADB server". If you updated ADB after that, the newer executable needs to kill the obsolete server and start a new one with matching version.
This can also happen when you have multiple versions of ADB present on your development machine (Genymotion, Android SDK, phone OEM companion apps, various standalone scripts).
This does not concern the ADB installed on your phone/emulator.
The obvious (not necessarily easy) solution is to make sure you use the same version of ADB everywhere.
Here is solution for legacy datatable 1.9.4
var myData = [
{
"id": 1,
"first_name": "Andy",
"last_name": "Anderson"
}
];
var myData2 = [
{
"id": 2,
"first_name": "Bob",
"last_name": "Benson"
}
];
$('#table').dataTable({
// data: myData,
aoColumns: [
{ mData: 'id' },
{ mData: 'first_name' },
{ mData: 'last_name' }
]
});
$('#table').dataTable().fnClearTable();
$('#table').dataTable().fnAddData(myData2);
If you need to join xpath-selected text nodes but can not use string-join
(when you are stuck with XSL 1.0) this might help:
<xsl:variable name="x">
<xsl:apply-templates select="..." mode="string-join-mode"/>
</xsl:variable>
joined and normalized: <xsl:value-of select="normalize-space($x)"/>
<xsl:template match="*" mode="string-join-mode">
<xsl:apply-templates mode="string-join-mode"/>
</xsl:template>
<xsl:template match="text()" mode="string-join-mode">
<xsl:value-of select="."/>
</xsl:template>
Its workaround.
If you not push to server, you will clone into new folder else washout(delete all files) from your repository folder and clone new.
Collections.addAll provides the shortest (one-line) receipt
Having
String[] array = {"foo", "bar", "baz"};
Set<String> set = new HashSet<>();
You can do as below
Collections.addAll(set, array);
Try using window.location.href
for the url to match the window's origin.
(Update) V5.1 & Hooks (Requires React >= 16.8)
You can use useHistory
, useLocation
and useRouteMatch
in your component to get match
, history
and location
.
const Child = () => {
const location = useLocation();
const history = useHistory();
const match = useRouteMatch("write-the-url-you-want-to-match-here");
return (
<div>{location.pathname}</div>
)
}
export default Child
(Update) V4 & V5
You can use withRouter
HOC in order to inject match
, history
and location
in your component props.
class Child extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
(Update) V3
You can use withRouter
HOC in order to inject router
, params
, location
, routes
in your component props.
class Child extends React.Component {
render() {
const { router, params, location, routes } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
Original answer
If you don't want to use the props, you can use the context as described in React Router documentation
First, you have to set up your childContextTypes
and getChildContext
class App extends React.Component{
getChildContext() {
return {
location: this.props.location
}
}
render() {
return <Child/>;
}
}
App.childContextTypes = {
location: React.PropTypes.object
}
Then, you will be able to access to the location object in your child components using the context like this
class Child extends React.Component{
render() {
return (
<div>{this.context.location.pathname}</div>
)
}
}
Child.contextTypes = {
location: React.PropTypes.object
}
Had the same bug. Actually worked in case the traffic was sent using some proxy (fiddler in my case). Updated .NET framework from 4.5.2 to >=4.6 and now everything works fine. The actual request was:
new WebClient().DownloadData("URL");
The exception was:
SocketException: An existing connection was forcibly closed by the remote host
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
hi,that maybe the project's problem,
chose the project and setting you eclipse:
project -> clean...
The Jquery .on
works ok but I had some problems with the rendering implementing some of the solutions above. My problem using the .on
is that somehow it was rendering the events differently than the .hover
method.
Just fyi for anyone else that may also have the problem. I solved my problem by re-registering the hover event for the dynamically added item:
re-register the hover event because hover doesn't work for dynamically created items. so every time i create the new/dynamic item i add the hover code again. works perfectly
$('#someID div:last').hover(
function() {
//...
},
function() {
//...
}
);
this short code worked for me:
Configuration wConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ServiceModelSectionGroup wServiceSection = ServiceModelSectionGroup.GetSectionGroup(wConfig);
ClientSection wClientSection = wServiceSection.Client;
wClientSection.Endpoints[0].Address = <your address>;
wConfig.Save();
Of course you have to create the ServiceClient proxy AFTER the config has changed. You also need to reference the System.Configuration and System.ServiceModel assemblies to make this work.
Cheers
You need to add two new file one is index.html, copy and paste the below code and other is imageup.php which will upload your image
<form action="imageup.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner" >
<input type="submit" value="submit">
</form>
imageup.php
<?php
$banner=$_FILES['banner']['name'];
$expbanner=explode('.',$banner);
$bannerexptype=$expbanner[1];
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Yh:i:sa', time());
$rand=rand(10000,99999);
$encname=$date.$rand;
$bannername=md5($encname).'.'.$bannerexptype;
$bannerpath="uploads/banners/".$bannername;
move_uploaded_file($_FILES["banner"]["tmp_name"],$bannerpath);
?>
The above code will upload your image with encrypted name
Intent eventIntentMessage =getPackageManager()
.getLaunchIntentForPackage(Telephony.Sms.getDefaultSmsPackage(getApplicationContext));
startActivity(eventIntentMessage);
For all people who speak C, take a look at these two macros:
// calculate the size of 'output' buffer required for a 'input' buffer of length x during Base64 encoding operation
#define B64ENCODE_OUT_SAFESIZE(x) ((((x) + 3 - 1)/3) * 4 + 1)
// calculate the size of 'output' buffer required for a 'input' buffer of length x during Base64 decoding operation
#define B64DECODE_OUT_SAFESIZE(x) (((x)*3)/4)
Taken from here.
It's treating the string application
as your URL.
This means your shell isn't parsing the command correctly.
My guess is that you copied the string from somewhere, and that when you pasted it, you got some characters that looked like regular quotes, but weren't.
Try retyping the command; you'll only get valid characters from your keyboard. I bet you'll get a much different result from what looks like the same query.
As this is probably a shell problem and not a 'curl' problem (you didn't build cURL yourself from source, did you?), it might be good to mention whether you're on Linux/Windows/etc.
Integer.valueOf(s)
is similar to
new Integer(Integer.parseInt(s))
The difference is valueOf()
returns an Integer
, and parseInt()
returns an int
(a primitive type). Also note that valueOf()
can return a cached Integer
instance, which can cause confusing results where the result of ==
tests seem intermittently correct. Before autoboxing there could be a difference in convenience, after java 1.5 it doesn't really matter.
Moreover, Integer.parseInt(s)
can take primitive datatype as well.
I had moved my log4j.properties into the resources folder and it worked fine for me !
The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.
The easiest solution would be to close the file after you've read it in, then reopen it for writing.
with open("replayScript.json", "r") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
with open("replayScript.json", "w") as jsonFile:
json.dump(data, jsonFile)
Alternatively, you can use seek()
to move the cursor back to the beginning of the file then start writing, followed by a truncate()
to deal with the case where the new data is smaller than the previous.
with open("replayScript.json", "r+") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
jsonFile.seek(0) # rewind
json.dump(data, jsonFile)
jsonFile.truncate()
One of the possible solution you might be interested in. Traversing an array of chars from right to left and vise versa in one loop.
public static string WordsToCapitalLetter(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("value");
}
int inputValueCharLength = value.Length;
var valueAsCharArray = value.ToCharArray();
int min = 0;
int max = inputValueCharLength - 1;
while (max > min)
{
char left = value[min];
char previousLeft = (min == 0) ? left : value[min - 1];
char right = value[max];
char nextRight = (max == inputValueCharLength - 1) ? right : value[max - 1];
if (char.IsLetter(left) && !char.IsUpper(left) && char.IsWhiteSpace(previousLeft))
{
valueAsCharArray[min] = char.ToUpper(left);
}
if (char.IsLetter(right) && !char.IsUpper(right) && char.IsWhiteSpace(nextRight))
{
valueAsCharArray[max] = char.ToUpper(right);
}
min++;
max--;
}
return new string(valueAsCharArray);
}
In the absence of the ability to do zone transfers, I wrote this small bash script, dg
:
#!/bin/bash
COMMON_SUBDOMAINS=(www mail smtp pop imap blog en ftp ssh login)
if [[ "$2" == "x" ]]; then
dig +nocmd "$1" +noall +answer "${3:-any}"
wild_ips="$(dig +short "*.$1" "${3:-any}" | tr '\n' '|')"
wild_ips="${wild_ips%|}"
for sub in "${COMMON_SUBDOMAINS[@]}"; do
dig +nocmd "$sub.$1" +noall +answer "${3:-any}"
done | grep -vE "${wild_ips}"
dig +nocmd "*.$1" +noall +answer "${3:-any}"
else
dig +nocmd "$1" +noall +answer "${2:-any}"
fi
Now I use dg example.com
to get a nice, clean list of DNS records, or dg example.com x
to include a bunch of other popular subdomains.
grep -vE "${wild_ips}"
filters out records that could be the result of a wildcard DNS entry such as * 10800 IN A 1.38.216.82
. Otherwise, a wildcard entry would make it appear as if there were records for each $COMMON_SUBDOMAN
.
Note: This relies on ANY
queries, which are blocked by some DNS providers such as CloudFlare.
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
This is how to make an activity start running after android device reboot:
Insert this code in your AndroidManifest.xml
file, within the <application>
element (not within the <activity>
element):
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:enabled="true"
android:exported="true"
android:name="yourpackage.yourActivityRunOnStartup"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Then create a new class yourActivityRunOnStartup
(matching the android:name
specified for the <receiver>
element in the manifest):
package yourpackage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class yourActivityRunOnStartup extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
Note:
The call i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
is important because the activity is launched from a context outside the activity. Without this, the activity will not start.
Also, the values android:enabled
, android:exported
and android:permission
in the <receiver>
tag do not seem mandatory. The app receives the event without these values. See the example here.
I assume the C string is in a fixed memory, so if you replace spaces you have to shift all characters.
The easiest seems to be to create new string and iterate over the original one and copy only non space characters.
I believe you are having the same problem here.
The sheet must be active before you can select a range on it.
Also, don't omit the sheet name qualifier:
Sheets("BxWsn Simulation").Select
Sheets("BxWsn Simulation").Range("Result").Select
Or,
With Sheets("BxWsn Simulation")
.Select
.Range("Result").Select
End WIth
which is the same.
I had to do the same for one of my projects and I ended up writing my own as well. I called it HorzListView is now part of my open source Aniqroid library.
http://aniqroid.sileria.com/doc/api/ (Look for downloads at the bottom or use google code project to see more download options: http://code.google.com/p/aniqroid/downloads/list)
The class documentation is here: http://aniqroid.sileria.com/doc/api/com/sileria/android/view/HorzListView.html
I think you should use reflection. Something like this:
private T ConvertDictionaryTo<T>(IDictionary<string, object> dictionary) where T : new()
{
Type type = typeof (T);
T ret = new T();
foreach (var keyValue in dictionary)
{
type.GetProperty(keyValue.Key).SetValue(ret, keyValue.Value, null);
}
return ret;
}
It takes your dictionary and loops through it and sets the values. You should make it better but it's a start. You should call it like this:
SomeClass someClass = ConvertDictionaryTo<SomeClass>(a);
For some unexplained reason this solution doesn't work for me (maybe some incompatibility of types), so I came up with a solution for myself:
HttpResponseMessage response = await client.GetAsync("api/yourcustomobjects");
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
var product = JsonConvert.DeserializeObject<Product>(data);
}
This way my content is parsed into a JSON string and then I convert it to my object.
This worked for me, but I used it as start. powershell outputs, waiting for service to finshing starting a few times then finishes and then a get-service on the remote server shows the service started.
**start**-service -inputobject $(get-service -ComputerName remotePC -Name Spooler)
Update 2016: with git 2.8 (March 2016), you can simply use:
git config --list --show-origin
And with Git 2.26 (Q1 2020), you can add a --show-scope
option
git config --list --show-origin --show-scope
You will see which config is set where.
See "Where do the settings in my Git configuration come from?"
As Stevoisiak points out in the comments,
it will work with non-standard install locations. (i.e. Git Portable)
(like the latest PortableGit-2.14.2-64-bit.7z.exe
, which can be uncompressed anywhere you want)
Original answer (2010)
From the docs:
--global
For writing options: write to global
~/.gitconfig
file rather than the repository.git/config
.
Since you're using Git for Windows, it may not be clear what location this corresponds to. But if you look at etc/profile (in C:\Program Files\Git
), you'll see:
HOME="$HOMEDRIVE$HOMEPATH"
Meaning:
C:\Users\MyLogin
(on Windows 7)
That means the file is in C:\Users\MyLogin\.gitconfig
for Git in Windows 7.
...
WHERE table1.x LIKE table2.y + '%'
Using dataType: 'jsonp'
worked for me.
async function get_ajax_data(){
var _reprojected_lat_lng = await $.ajax({
type: 'GET',
dataType: 'jsonp',
data: {},
url: _reprojection_url,
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR)
},
success: function (data) {
console.log(data);
// note: data is already json type, you
// just specify dataType: jsonp
return data;
}
});
} // function
$str = preg_replace('/\?\//', '?', $str);
Edit: See CMS' answer. It's late, I should know better.
Here's a simplified version with extended explanation for beginners like me who are trying to learn how to put more than one command in one line.
If you were to write out the problem in steps, it would look like this:
// For every file in this directory
// Check the filetype
// If it's an ASCII file, then print out the filename
To achieve this, we can use three UNIX commands: find
, file
, and grep
.
find
will check every file in the directory.
file
will give us the filetype. In our case, we're looking for a return of 'ASCII text'
grep
will look for the keyword 'ASCII' in the output from file
So how can we string these together in a single line? There are multiple ways to do it, but I find that doing it in order of our pseudo-code makes the most sense (especially to a beginner like me).
find ./ -exec file {} ";" | grep 'ASCII'
Looks complicated, but not bad when we break it down:
find ./
= look through every file in this directory. The find
command prints out the filename of any file that matches the 'expression', or whatever comes after the path, which in our case is the current directory or ./
The most important thing to understand is that everything after that first bit is going to be evaluated as either True or False. If True, the file name will get printed out. If not, then the command moves on.
-exec
= this flag is an option within the find command that allows us to use the result of some other command as the search expression. It's like calling a function within a function.
file {}
= the command being called inside of find
. The file
command returns a string that tells you the filetype of a file. Regularly, it would look like this: file mytextfile.txt
. In our case, we want it to use whatever file is being looked at by the find
command, so we put in the curly braces {}
to act as an empty variable, or parameter. In other words, we're just asking for the system to output a string for every file in the directory.
";"
= this is required by find
and is the punctuation mark at the end of our -exec
command. See the manual for 'find' for more explanation if you need it by running man find
.
| grep 'ASCII'
= |
is a pipe. Pipe take the output of whatever is on the left and uses it as input to whatever is on the right. It takes the output of the find
command (a string that is the filetype of a single file) and tests it to see if it contains the string 'ASCII'
. If it does, it returns true.
NOW, the expression to the right of find ./
will return true when the grep
command returns true. Voila.
I found very good explanation about .la files here http://openbooks.sourceforge.net/books/wga/dealing-with-libraries.html
Summary (The way I understood): Because libtool deals with static and dynamic libraries internally (through --diable-shared or --disable-static) it creates a wrapper on the library files it builds. They are treated as binary library files with in libtool supported environment.
This
Example:
objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";
Put them into a list
and use merge
with Reduce
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# id v1 v2 v3
# 1 1 1 NA NA
# 2 10 4 NA NA
# 3 2 3 4 NA
# 4 43 5 NA NA
# 5 73 2 NA NA
# 6 23 NA 2 1
# 7 57 NA 3 NA
# 8 62 NA 5 2
# 9 7 NA 1 NA
# 10 96 NA 6 NA
You can also use this more concise version:
Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
This is a great article for syntax needed to create new objects from a LINQ query.
But, if the assignments to fill in the fields of the object are anything more than simple assignments, for example, parsing strings to integers, and one of them fails, it is not possible to debug this. You can not create a breakpoint on any of the individual assignments.
And if you move all the assignments to a subroutine, and return a new object from there, and attempt to set a breakpoint in that routine, you can set a breakpoint in that routine, but the breakpoint will never be triggered.
So instead of:
var query2 = from c in doc.Descendants("SuggestionItem")
select new SuggestionItem
{ Phrase = c.Element("Phrase").Value
Blocked = bool.Parse(c.Element("Blocked").Value),
SeenCount = int.Parse(c.Element("SeenCount").Value)
};
Or
var query2 = from c in doc.Descendants("SuggestionItem")
select new SuggestionItem(c);
I instead did this:
List<SuggestionItem> retList = new List<SuggestionItem>();
var query = from c in doc.Descendants("SuggestionItem") select c;
foreach (XElement item in query)
{
SuggestionItem anItem = new SuggestionItem(item);
retList.Add(anItem);
}
This allowed me to easily debug and figure out which assignment was failing. In this case, the XElement was missing a field I was parsing for to set in the SuggestionItem.
I ran into these gotchas with Visual Studio 2017 while writing unit tests for a new library routine.
I would use this in HTML 5... Just sayin
#footer {
position: absolute;
bottom: 0;
width: 100%;
height: 60px;
background-color: #f5f5f5;
}
Tried all the answers but none worked. Maybe it's because I'm appending and removing childs before saving the XML. After a lot of googling found this comment in the php documentation. I only had to reload the resulting XML to make it work.
$outXML = $xml->saveXML();
$xml = new DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$xml->loadXML($outXML);
$outXML = $xml->saveXML();
Another possibility is to use regular expressions which is what Perl is famous for:
if ($mystring =~ /s1\.domain\.com/) {
print qq("$mystring" contains "s1.domain.com"\n);
}
The backslashes are needed because a .
can match any character. You can get around this by using the \Q
and \E
operators.
my $substring = "s1.domain.com";
if ($mystring =~ /\Q$substring\E/) {
print qq("$mystring" contains "$substring"\n);
}
Or, you can do as eugene y stated and use the index function.
Just a word of warning: Index returns a -1
when it can't find a match instead of an undef
or 0
.
Thus, this is an error:
my $substring = "s1.domain.com";
if (not index($mystring, $substr)) {
print qq("$mystring" doesn't contains "$substring"\n";
}
This will be wrong if s1.domain.com
is at the beginning of your string. I've personally been burned on this more than once.
Well this might appear weird but after installing pycrypto
or pycryptodome
, we need to update the directory name crypto
to Crypto
in lib/site-packages
You get the integer limits in <limits.h>
or <climits>
. Floating point characteristics are defined in <float.h>
for C. In C++, the preferred version is usually std::numeric_limits<double>::max()
(for which you #include <limits>
).
As to your original question, if you want a larger integer type than long
, you should probably consider long long
. This isn't officially included in C++98 or C++03, but is part of C99 and C++11, so all reasonably current compilers support it.
you can use the example from Microsoft - for you without namespace:
using System.Xml.Linq;
using System.Xml.XPath;
var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");
should do it
All you have to do is add:
#include <string>
using namespace std;
at the top. (BTW I know this was posted in 2013 but I just wanted to answer)
Json.Net prefers to use the default (parameterless) constructor on an object if there is one. If there are multiple constructors and you want Json.Net to use a non-default one, then you can add the [JsonConstructor]
attribute to the constructor that you want Json.Net to call.
[JsonConstructor]
public Result(int? code, string format, Dictionary<string, string> details = null)
{
...
}
It is important that the constructor parameter names match the corresponding property names of the JSON object (ignoring case) for this to work correctly. You do not necessarily have to have a constructor parameter for every property of the object, however. For those JSON object properties that are not covered by the constructor parameters, Json.Net will try to use the public property accessors (or properties/fields marked with [JsonProperty]
) to populate the object after constructing it.
If you do not want to add attributes to your class or don't otherwise control the source code for the class you are trying to deserialize, then another alternative is to create a custom JsonConverter to instantiate and populate your object. For example:
class ResultConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Result));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Load the JSON for the Result into a JObject
JObject jo = JObject.Load(reader);
// Read the properties which will be used as constructor parameters
int? code = (int?)jo["Code"];
string format = (string)jo["Format"];
// Construct the Result object using the non-default constructor
Result result = new Result(code, format);
// (If anything else needs to be populated on the result object, do that here)
// Return the result
return result;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Then, add the converter to your serializer settings, and use the settings when you deserialize:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new ResultConverter());
Result result = JsonConvert.DeserializeObject<Result>(jsontext, settings);
Can try this too, almost similar previous answers.
d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
df = pd.DataFrame(d).set_index('filename')
Count of null values in each column.
df.isnull().sum()
df.isnull().any(axis=1)
One small addition to the answer by vasekt:
The provided solution with the SocketFactoryRegistry works when using PoolingHttpClientConnectionManager.
However, connections via plain http don't work any longer then. You have to add a PlainConnectionSocketFactory for the http protocol additionally to make them work again:
Registry<ConnectionSocketFactory> socketFactoryRegistry =
RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslsf)
.register("http", new PlainConnectionSocketFactory()).build();
Use the body of this loop to do whatever you want to with the digits
for digit in map(int, str(my_number)):
I compared each of method that each answer mentioned. At this moment I use python 3.6.3 for this implementation. This is the code that I have used:
import time
import random
from decimal import Decimal
def method1():
common_elements = [x for x in li1_temp if x in li2_temp]
print(len(common_elements))
def method2():
common_elements = (x for x in li1_temp if x in li2_temp)
print(len(list(common_elements)))
def method3():
common_elements = set(li1_temp) & set(li2_temp)
print(len(common_elements))
def method4():
common_elements = set(li1_temp).intersection(li2_temp)
print(len(common_elements))
if __name__ == "__main__":
li1 = []
li2 = []
for i in range(100000):
li1.append(random.randint(0, 10000))
li2.append(random.randint(0, 10000))
li1_temp = list(set(li1))
li2_temp = list(set(li2))
methods = [method1, method2, method3, method4]
for m in methods:
start = time.perf_counter()
m()
end = time.perf_counter()
print(Decimal((end - start)))
If you run this code you can see that if you use list or generator(if you iterate over generator, not just use it. I did this when I forced generator to print length of it), you get nearly same performance. But if you use set you get much better performance. Also if you use intersection method you will get a little bit better performance. the result of each method in my computer is listed bellow:
You can simply do the following inside your TR loop:
$(this).find('td').each (function() {
// do your cool stuff
});
The second method is preferred because of the encapsulation. You can certainly have the readonly field be public, but that goes against C# idioms in which you have data access occur through properties and not fields.
The reasoning behind this is that the property defines a public interface and if the backing implementation to that property changes, you don't end up breaking the rest of the code because the implementation is hidden behind an interface.
I tried all suggestions with reset and reflog without any success. Restoring local history of IntelliJ resolved the problem of lost files
I fixed this issue by changing the web app to use a different "Application Pool".
I can recommend interesting solution for Linux fans. After I explored this solution, I've switched from DependencyWalker to this.
You can use your favorite ldd
over Windows-related exe
, dll
.
To do this you need to install Cygwin (basic installation, without additional packages required) on your Windows and then just start Cygwin Terminal
. Now you can run your favorite Linux commands, including:
$ ldd your_dll_file.dll
UPD: You can use ldd
also through git bash terminal on Windows. No need to install cygwin in case if you have git already installed.
random.uniform(a, b)
appears to be what your looking for. From the docs:
Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.
See here.
You could change the encoding of your entire operating system. On Ubuntu you can do this with
sudo apt install locales
sudo locale-gen en_US en_US.UTF-8
sudo dpkg-reconfigure locales
You cannot load images directly with @2x
or @3x
, system selects appropriate image automatically, just specify the name using UIImage
:
UIImage(named: "green-square-Retina")
may be you can specify where the buildfile is located and then invoke desired action.
Eg: ant -file {BuildfileLocation/build.xml} -v
Below is a simpler solution how to get the last digit from an int
:
public int lastDigit(int number) { return Math.abs(number) % 10; }
Let arrList
be the ArrayList
and newValue
the new String
, then just do:
arrList.set(5, newValue);
This can be found in the java api reference here.
In Flask shell, all I needed to do was a session.rollback()
to get past this.
Looks like the script executes before the DOM loads. Try loading the script asynchronously.
<script src="yourcode.js" async></script>
Alternative method: In Eclipse 3.6, under "Line Wrapping" then "General Settings" there is an option to "Never join already wrapped lines." This means the formatter will wrap long lines but not undo any wrapping you already have.
Write and run the following code in the Immediate Window
?cells(,"type the column name here").column
For example ?cells(,"BYL").column
will return 2014. The code is case-insensitive, hence you may write ?cells(,"byl").column
and the output will still be the same.
Suppose you have this script
<div>
<p id="response"><p>
<script>
var query = document.location.href.substring(document.location.href.indexOf("?") + 1);
var text_input = query.split("&")[0].split("=")[1];
document.getElementById('response').innerHTML=text_input;
</script> </div>
And the url form is www.localhost.com/web_form_response.html?text_input=stack&over=flow
The text written to <p id="response">
will be stack
With Bootstrap 3.2 you can wrap each iframe in the responsive-embed wrapper of your choice:
http://getbootstrap.com/components/#responsive-embed
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="…"></iframe>
</div>
<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
<iframe class="embed-responsive-item" src="…"></iframe>
</div>
If you don't want to wrap your iframes, you can use FluidVids https://github.com/toddmotto/fluidvids. See demo here: http://toddmotto.com/labs/fluidvids/
<!-- fluidvids.js -->
<script src="js/fluidvids.js"></script>
<script>
fluidvids.init({
selector: ['iframe'],
players: ['www.youtube.com', 'player.vimeo.com']
});
</script>
At least in 10.11 (El Capitan), the man page for umount indicates:
Due to the complex and interwoven nature of Mac OS X, umount may fail often. It is recommended that diskutil(1) (as in, "diskutil unmount /mnt") be used instead.
This approach (e.g., "diskutil umount path/to/mount/point") allows me to unmount sshfs-mounted content, and does not require sudo. (And I believe that it should work back through at least 10.8.)
DROP that table and again run Spring Project. That might help. Sometime you are overriding foreignKey.
jQuery dialog has an isOpen
property that can be used to check if a jQuery dialog is open or not.
You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html
Just use GETDATE()
or GETUTCDATE()
(if you want to get the "universal" UTC time, instead of your local server's time-zone related time).
INSERT INTO [Business]
([IsDeleted]
,[FirstName]
,[LastName]
,[LastUpdated]
,[LastUpdatedBy])
VALUES
(0, 'Joe', 'Thomas',
GETDATE(), <LastUpdatedBy, nvarchar(50),>)
Rclone is what you are looking for. Rclone ("rsync for cloud storage") is a command line program to sync files and directories to and from different cloud storage providers including local filesystems. Rclone was previously known as Swiftsync and has been available since 2013.
There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).
So use just font-family: Calibri
or, better, font-family: Calibri, sans-serif
. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)
Create an empty list of Character and then make a loop to get every character from the array and put them in the list one by one.
List<Character> characterList = new ArrayList<Character>();
char arrayChar[] = abc.toCharArray();
for (char aChar : arrayChar)
{
characterList.add(aChar); // autoboxing
}
I don't understand the first two answers. I think they must be version-dependent. I cannot reproduce them on MySQLdb 1.2.3, which comes with Ubuntu 14.04LTS. Let's try them. First, we verify that MySQL doesn't accept double-apostrophes:
mysql> select * from methods limit 1;
+----------+--------------------+------------+
| MethodID | MethodDescription | MethodLink |
+----------+--------------------+------------+
| 32 | Autonomous Sensing | NULL |
+----------+--------------------+------------+
1 row in set (0.01 sec)
mysql> select * from methods where MethodID = ''32'';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '9999'' ' at line 1
Nope. Let's try the example that Mandatory posted using the query constructor inside /usr/lib/python2.7/dist-packages/MySQLdb/cursors.py
where I opened "con" as a connection to my database.
>>> search = "test"
>>> "SELECT * FROM records WHERE email LIKE '%s'" % con.literal(search)
"SELECT * FROM records WHERE email LIKE ''test''"
>>>
Nope, the double apostrophes cause it to fail. Let's try Mike Graham's first comment, where he suggests leaving off the apostrophes quoting the %s:
>>> "SELECT * FROM records WHERE email LIKE %s" % con.literal(search)
"SELECT * FROM records WHERE email LIKE 'test'"
>>>
Yep, that will work, but Mike's second comment and the documentation says that the argument to execute (processed by con.literal) must be a tuple (search,)
or a list [search]
. You can try them, but you'll find no difference from the output above.
The best answer is ksg97031's.
I have an example of doing both by classpath or from external config with log4j2.properties
package org.mmartin.app1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.LogManager;
public class App1 {
private static Logger logger=null;
private static final String LOG_PROPERTIES_FILE = "config/log4j2.properties";
private static final String CONFIG_PROPERTIES_FILE = "config/config.properties";
private Properties properties= new Properties();
public App1() {
System.out.println("--Logger intialized with classpath properties file--");
intializeLogger1();
testLogging();
System.out.println("--Logger intialized with external file--");
intializeLogger2();
testLogging();
}
public void readProperties() {
InputStream input = null;
try {
input = new FileInputStream(CONFIG_PROPERTIES_FILE);
this.properties.load(input);
} catch (IOException e) {
logger.error("Unable to read the config.properties file.",e);
System.exit(1);
}
}
public void printProperties() {
this.properties.list(System.out);
}
public void testLogging() {
logger.debug("This is a debug message");
logger.info("This is an info message");
logger.warn("This is a warn message");
logger.error("This is an error message");
logger.fatal("This is a fatal message");
logger.info("Logger's name: "+logger.getName());
}
private void intializeLogger1() {
logger = LogManager.getLogger(App1.class);
}
private void intializeLogger2() {
LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
File file = new File(LOG_PROPERTIES_FILE);
// this will force a reconfiguration
context.setConfigLocation(file.toURI());
logger = context.getLogger(App1.class.getName());
}
public static void main(String[] args) {
App1 app1 = new App1();
app1.readProperties();
app1.printProperties();
}
}
--Logger intialized with classpath properties file--
[DEBUG] 2018-08-27 10:35:14.510 [main] App1 - This is a debug message
[INFO ] 2018-08-27 10:35:14.513 [main] App1 - This is an info message
[WARN ] 2018-08-27 10:35:14.513 [main] App1 - This is a warn message
[ERROR] 2018-08-27 10:35:14.513 [main] App1 - This is an error message
[FATAL] 2018-08-27 10:35:14.513 [main] App1 - This is a fatal message
[INFO ] 2018-08-27 10:35:14.514 [main] App1 - Logger's name: org.mmartin.app1.App1
--Logger intialized with external file--
[DEBUG] 2018-08-27 10:35:14.524 [main] App1 - This is a debug message
[INFO ] 2018-08-27 10:35:14.525 [main] App1 - This is an info message
[WARN ] 2018-08-27 10:35:14.525 [main] App1 - This is a warn message
[ERROR] 2018-08-27 10:35:14.525 [main] App1 - This is an error message
[FATAL] 2018-08-27 10:35:14.525 [main] App1 - This is a fatal message
[INFO ] 2018-08-27 10:35:14.525 [main] App1 - Logger's name: org.mmartin.app1.App1
-- listing properties --
dbpassword=password
database=localhost
dbuser=user
Here is the version that I used:
typedef enum { false = 0, true = !false } bool;
Because false only has one value, but a logical true could have many values, but technique sets true to be what the compiler will use for the opposite of false.
This takes care of the problem of someone coding something that would come down to this:
if (true == !false)
I think we would all agree that that is not a good practice, but for the one time cost of doing "true = !false" we eliminate that problem.
[EDIT] In the end I used:
typedef enum { myfalse = 0, mytrue = !myfalse } mybool;
to avoid name collision with other schemes that were defining true
and false
. But the concept remains the same.
[EDIT] To show conversion of integer to boolean:
mybool somebool;
int someint = 5;
somebool = !!someint;
The first (right most) ! converts the non-zero integer to a 0, then the second (left most) ! converts the 0 to a myfalse
value. I will leave it as an exercise for the reader to convert a zero integer.
[EDIT]
It is my style to use the explicit setting of a value in an enum when the specific value is required even if the default value would be the same. Example: Because false needs to be zero I use false = 0,
rather than false,
try this
SELECT
Orders.OrderNumber,
LineItems.Quantity,
LineItems.Description
FROM Orders
INNER JOIN (
SELECT
Orders.OrderNumber,
Max(LineItem.LineItemID) AS LineItemID
FROM Orders
INNER JOIN LineItems
ON Orders.OrderNumber = LineItems.OrderNumber
GROUP BY Orders.OrderNumber
) AS Items ON Orders.OrderNumber = Items.OrderNumber
INNER JOIN LineItems
ON Items.LineItemID = LineItems.LineItemID
Add this dependecy in pom.xml file. Hope this help.
In <systemPath>
property you have to write your jdk lib path..
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.4.2</version>
<scope>system</scope>
<systemPath>C:/Program Files/Java/jdk1.6.0_30/lib/tools.jar</systemPath>
</dependency>
An easy and straightforward solution using the CASE function:
SELECT CASE WHEN ( a > 0 ) THEN (a*-1) ELSE (a*-1) END AS NegativeA,
CASE WHEN ( b > 0 ) THEN (b*-1) ELSE (b*-1) END AS PositiveB
FROM YourTableName
You can try using AppDomain.UnhandledException and see if that lets you catch it.
**EDIT*
Here is some more information that might be useful (it's a long read).
If you really want to prune your history of .gitignore
d files, first save .gitignore
outside the repo, e.g. as /tmp/.gitignore
, then run
git filter-branch --force --index-filter \
"git ls-files -i -X /tmp/.gitignore | xargs -r git rm --cached --ignore-unmatch -rf" \
--prune-empty --tag-name-filter cat -- --all
Notes:
git filter-branch --index-filter
runs in the .git
directory I think, i.e. if you want to use a relative path you have to prepend one more ../
first. And apparently you cannot use ../.gitignore
, the actual .gitignore
file, that yields a "fatal: cannot use ../.gitignore as an exclude file" for some reason (maybe during a git filter-branch --index-filter
the working directory is (considered) empty?)git ls-files -iX <(git show $(git hash-object -w .gitignore))
instead to avoid copying .gitignore
somewhere else, but that alone already returns an empty string (whereas cat <(git show $(git hash-object -w .gitignore))
indeed prints .gitignore
's contents as expected), so I cannot use <(git show $GITIGNORE_HASH)
in git filter-branch
....gitignore
-clean a specific branch, replace --all
in the last line with its name. The --tag-name-filter cat
might not work properly then, i.e. you'll probably not be able to directly transfer a single branch's tags properlyWith the Entity Framework most of the time SaveChanges()
is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.
Sometimes though the SaveChanges(false) + AcceptAllChanges()
pairing is useful.
The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.
I.e. something like this (bad):
using (TransactionScope scope = new TransactionScope())
{
//Do something with context1
//Do something with context2
//Save and discard changes
context1.SaveChanges();
//Save and discard changes
context2.SaveChanges();
//if we get here things are looking good.
scope.Complete();
}
If context1.SaveChanges()
succeeds but context2.SaveChanges()
fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes on context1
, so you can't replay or effectively log the failure.
But if you change your code to look like this:
using (TransactionScope scope = new TransactionScope())
{
//Do something with context1
//Do something with context2
//Save Changes but don't discard yet
context1.SaveChanges(false);
//Save Changes but don't discard yet
context2.SaveChanges(false);
//if we get here things are looking good.
scope.Complete();
context1.AcceptAllChanges();
context2.AcceptAllChanges();
}
While the call to SaveChanges(false)
sends the necessary commands to the database, the context itself is not changed, so you can do it again if necessary, or you can interrogate the ObjectStateManager
if you want.
This means if the transaction actually throws an exception you can compensate, by either re-trying or logging state of each contexts ObjectStateManager
somewhere.
Use a selector that will select all the rows and take the length.
var rowCount = $('#myTable tr').length;
Note: this approach also counts all trs of every nested table!
First of all, have only one id="test"
Secondly, try this:
if ($('[name="test"]').is(':checked'))
Check out the addressable gem - a popular replacement for Ruby's URI module that makes query parsing easy:
require "addressable/uri"
uri = Addressable::URI.parse("http://www.example.com/something?param1=value1¶m2=value2¶m3=value3")
uri.query_values['param1']
=> 'value1'
(It also apparently handles param encoding/decoding, unlike URI)
I have been using this for years and it works well. Could probably be made more efficient, but
grabstring("Test string","","",0) returns Test string
grabstring("Test string","Test ","",0) returns string
grabstring("Test string","s","",5) returns string
function grabstring($strSource,$strPre,$strPost,$StartAt) {
if(@strpos($strSource,$strPre)===FALSE && $strPre!=""){
return("");
}
@$Startpoint=strpos($strSource,$strPre,$StartAt)+strlen($strPre);
if($strPost == "") {
$EndPoint = strlen($strSource);
} else {
if(strpos($strSource,$strPost,$Startpoint)===FALSE){
$EndPoint= strlen($strSource);
} else {
$EndPoint = strpos($strSource,$strPost,$Startpoint);
}
}
if($strPre == "") {
$Startpoint = 0;
}
if($EndPoint - $Startpoint < 1) {
return "";
} else {
return substr($strSource, $Startpoint, $EndPoint - $Startpoint);
}
}