Might it be possible that you're using a WCF-based web service reference? By default, the ServiceThrottlingBehavior.MaxConcurrentCalls is 16.
You could try updating your service reference behavior's <serviceThrottling>
element
<serviceThrottling
maxConcurrentCalls="999"
maxConcurrentSessions="999"
maxConcurrentInstances="999" />
(Note that I'd recommend the settings above.) See MSDN for more information how to configure an appropriate <behavior>
element.
Taken from this answer.
packages.config
file. This is the first time I see ignoring a problem actually makes it go away...
Edit in 2020: if you are viewing this warning, consider upgrading to PackageReference if you can
If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings xdt:Transform="Replace">
<!-- production environment config --->
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
Information for this answer are brought from this answer and this blog post.
notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).
Well, you can stick one or more "soft hyphens" (­
) in your long unbroken strings. I doubt that old IE versions deal with that correctly, but what it's supposed to do is tell the browser about allowable word breaks that it can use if it has to.
Now, how exactly would you pick where to stuff those characters? That depends on the actual string and what it means, I guess.
Along with the embed, I also had to install the Google Cast extension in my browser.
<iframe width="1280" height="720" src="https://www.youtube.com/embed/4u856utdR94" frameborder="0" allowfullscreen></iframe>
If you already have a table pre_loaded_tbl with some data. You can use a trick to load the data into your table with following query
INSERT INTO TABLE tweet_table
SELECT "my_data" AS my_column
FROM pre_loaded_tbl
LIMIT 5;
Also please note that "my_data" is independent of any data in the pre_loaded_tbl. You can select any data and write any column name (here my_data and my_column). Hive does not require it to have same column name. However structure of select statement should be same as that of your tweet_table. You can use limit to determine how many times you can insert into the tweet_table.
However if you haven't' created any table, you will have to load the data using file copy or load data commands in above answers.
If git fetch -p origin
does not work for some reason (like because the origin repo no longer exists or you are unable to reach it), another solution is to remove the information which is stored locally on that branch by doing from the root of the repo:
rm .git/refs/remotes/origin/DELETED_BRANCH
or if it is stored in the file .git/packed-refs
by deleting the corresponding line which is like
7a9930974b02a3b31cb2ebd17df6667514962685 refs/remotes/origin/DELETED_BRANCH
SELECT field1,
field2,
'example' AS newfield
FROM TABLE1
This will add a column called "newfield" to the output, and its value will always be "example".
The main
function must be declared as a non-member function in the global namespace. This means that it cannot be a static or non-static member function of a class, nor can it be placed in a namespace (even the unnamed namespace).
The name main
is not reserved in C++ except as a function in the global namespace. You are free to declare other entities named main
, including among other things, classes, variables, enumerations, member functions, and non-member functions not in the global namespace.
You can declare a function named main
as a member function or in a namespace, but such a function would not be the main
function that designates where the program starts.
The main
function cannot be declared as static
or inline
. It also cannot be overloaded; there can be only one function named main
in the global namespace.
The main
function cannot be used in your program: you are not allowed to call the main
function from anywhere in your code, nor are you allowed to take its address.
The return type of main
must be int
. No other return type is allowed (this rule is in bold because it is very common to see incorrect programs that declare main
with a return type of void
; this is probably the most frequently violated rule concerning the main
function).
There are two declarations of main
that must be allowed:
int main() // (1)
int main(int, char*[]) // (2)
In (1), there are no parameters.
In (2), there are two parameters and they are conventionally named argc
and argv
, respectively. argv
is a pointer to an array of C strings representing the arguments to the program. argc
is the number of arguments in the argv
array.
Usually, argv[0]
contains the name of the program, but this is not always the case. argv[argc]
is guaranteed to be a null pointer.
Note that since an array type argument (like char*[]
) is really just a pointer type argument in disguise, the following two are both valid ways to write (2) and they both mean exactly the same thing:
int main(int argc, char* argv[])
int main(int argc, char** argv)
Some implementations may allow other types and numbers of parameters; you'd have to check the documentation of your implementation to see what it supports.
main()
is expected to return zero to indicate success and non-zero to indicate failure. You are not required to explicitly write a return
statement in main()
: if you let main()
return without an explicit return
statement, it's the same as if you had written return 0;
. The following two main()
functions have the same behavior:
int main() { }
int main() { return 0; }
There are two macros, EXIT_SUCCESS
and EXIT_FAILURE
, defined in <cstdlib>
that can also be returned from main()
to indicate success and failure, respectively.
The value returned by main()
is passed to the exit()
function, which terminates the program.
Note that all of this applies only when compiling for a hosted environment (informally, an environment where you have a full standard library and there's an OS running your program). It is also possible to compile a C++ program for a freestanding environment (for example, some types of embedded systems), in which case startup and termination are wholly implementation-defined and a main()
function may not even be required. If you're writing C++ for a modern desktop OS, though, you're compiling for a hosted environment.
Creating a sum method would work nicely, e.g. you could add the sum function to Array
Array.prototype.sum = function(selector) {
if (typeof selector !== 'function') {
selector = function(item) {
return item;
}
}
var sum = 0;
for (var i = 0; i < this.length; i++) {
sum += parseFloat(selector(this[i]));
}
return sum;
};
then you could do
> [1,2,3].sum()
6
and in your case
> myData.sum(function(item) { return item[1]; });
23
Edit: Extending the builtins can be frowned upon because if everyone did it we would get things unexpectedly overriding each other (namespace collisions). you could add the sum function to some module and accept an array as an argument if you like.
that could mean changing the signature to myModule.sum = function(arr, selector) {
then this
would become arr
String data = "This world is mine";
System.out.print(data.split("\\s+").length);
Like Andrew said /exclude
parameter of xcopy should be existing file that has list of excludes.
Documentation of xcopy says:
Using /exclude
List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.
Example:
xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
and list-of-excluded-files.txt
should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:
exclusion.txt
% Modulo operator can be also used for printing strings (Just like in C) as defined on Google https://developers.google.com/edu/python/strings.
# % operator
text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')
This seems to bit off topic but It will certainly help someone.
It all depends what you mean by change the font size. This EmacsWiki section provides the best and most complete information. It distinguishes the various cases (text scaling, frame font, buffer/frame, etc.): Changing Font Size.
For me the problem was an error that didn't come up in the build output, namely I had two utility classes that were in different namespaces initially. I changed the namespace of the second one to match the first one's (without knowing there was another one utility class in the first one), and that's when this error started to come up.
I imagine the build output error surfaced, because the Logic Layer library DLL file could not be built, and the main application couldn't find it.
The solution was to change back the second utility class to a different namespace and that's when the real build errors started to pour in. After sorting them out the build went through just fine.
As an overview, if any of the previous solutions doesn't work for you, you might have suppressed errors in the code that Visual Studio is not showing, so try to retrack your coding steps and check for any irregularities.
PS: This was in Visual Studio 2015 Community Edition
I have just encountered a similar need. In my case, slf4j is configured with the java logging adapter (the jdk14 one). Using the following code snippet I have managed to change the debug level at runtime:
Logger logger = LoggerFactory.getLogger("testing");
java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger("testing");
julLogger.setLevel(java.util.logging.Level.FINE);
logger.debug("hello world");
In Mysql 5.7+ you can execute
select current_timestamp(6)
for more details
https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html
From Working with CSS preprocessors in Chrome DevTools:
Many developers generate CSS style sheets using a CSS preprocessor, such as Sass, Less, or Stylus. Because the CSS files are generated, editing the CSS files directly is not as helpful.
For preprocessors that support CSS source maps, DevTools lets you live-edit your preprocessor source files in the Sources panel, and view the results without having to leave DevTools or refresh the page. When you inspect an element whose styles are provided by a generated CSS file, the Elements panel displays a link to the original source file, not the generated .css file.
Following is how I draw a checkbox in a table!
| Checkbox Experiments | [ ] unchecked header | [x] checked header |
| ---------------------|:---------------------:|:-------------------:|
| checkbox | [ ] row | [x] row |
I just thought that I'd add that there is a notion of Z-order in Swing, see [java.awt.Component#setComponentZOrder][1]
which affects the positions of a component in its parents component array, which determines the painting order.
Note that you should override javax.swing.JComponent#isOptimizedDrawingEnabled to return false in the parent container to get your overlapping components to repaint correctly, otherwise their repaints will clobber each other. (JComponents assume no overlapping children unless isOptimizedDrawingEnabled returns false)
I've created an open source (BSD) C header that deals with this problem. It currently supports POSIX and Windows. Please check it out:
https://github.com/cxong/tinydir
tinydir_dir dir;
tinydir_open(&dir, "/path/to/dir");
while (dir.has_next)
{
tinydir_file file;
tinydir_readfile(&dir, &file);
printf("%s", file.name);
if (file.is_dir)
{
printf("/");
}
printf("\n");
tinydir_next(&dir);
}
tinydir_close(&dir);
Never mind, I found it in the docs:
-g/--globoff
This option switches off the "URL globbing parser". When you set this option, you can
specify URLs that contain the letters {}[] without having them being interpreted by curl
itself. Note that these letters are not normal legal URL contents but they should be
encoded according to the URI standard.
I had this problem even after setting the config properly. git config
My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).
Instead of saving it to a file, save it to php://output
Docs:
$objWriter->save('php://output');
This will send it AS-IS to the browser.
You want to add some headersDocs first, like it's common with file downloads, so the browser knows which type that file is and how it should be named (the filename):
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
// It will be called file.xls
header('Content-Disposition: attachment; filename="file.xls"');
// Write file to the browser
$objWriter->save('php://output');
First do the headers, then the save. For the excel headers see as well the following question: Setting mime type for excel document.
Here is the code that will return all video ids under your channel
<?php
$baseUrl = 'https://www.googleapis.com/youtube/v3/';
// https://developers.google.com/youtube/v3/getting-started
$apiKey = 'API_KEY';
// If you don't know the channel ID see below
$channelId = 'CHANNEL_ID';
$params = [
'id'=> $channelId,
'part'=> 'contentDetails',
'key'=> $apiKey
];
$url = $baseUrl . 'channels?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads'];
$params = [
'part'=> 'snippet',
'playlistId' => $playlist,
'maxResults'=> '50',
'key'=> $apiKey
];
$url = $baseUrl . 'playlistItems?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$videos = [];
foreach($json['items'] as $video)
$videos[] = $video['snippet']['resourceId']['videoId'];
while(isset($json['nextPageToken'])){
$nextUrl = $url . '&pageToken=' . $json['nextPageToken'];
$json = json_decode(file_get_contents($nextUrl), true);
foreach($json['items'] as $video)
$videos[] = $video['snippet']['resourceId']['videoId'];
}
print_r($videos);
Note: You can get channel id at https://www.youtube.com/account_advanced after logged in.
Have you tried this: create a Computed column, called 'Expiry', with a formula that amounts to '[Created] + 7 days'. Then use the computed column in your View's filter. Let us know whether this worked or what problems this poses!
Hex Color code
#007AFF
and you need this libary https://github.com/thii/SwiftHEXColors
ps. iOS, Swift
With Python 3, the following code will format an Exception
object exactly as would be obtained using traceback.format_exc()
:
import traceback
try:
method_that_can_raise_an_exception(params)
except Exception as ex:
print(''.join(traceback.format_exception(etype=type(ex), value=ex, tb=ex.__traceback__)))
The advantage being that only the Exception
object is needed (thanks to the recorded __traceback__
attribute), and can therefore be more easily passed as an argument to another function for further processing.
I wrote a simpler loop that works too (note that all my values are unique):
HashMap<Character, String> myHashMap = new HashMap<Character, String>();
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
for (char i : myHashMap.keySet()) {
reversedHashMap.put(myHashMap.get(i), i);
}
I'm surprised no one has mentioned the fact that you can mix positional and keyword arguments to do sneaky things like this using *args
and **kwargs
(from this site):
def test_var_kwargs(farg, **kwargs):
print "formal arg:", farg
for key in kwargs:
print "another keyword arg: %s: %s" % (key, kwargs[key])
This allows you to use arbitrary keyword arguments that may have keys you don't want to define upfront.
Go to the GitHub page where they are maintain the official repository: https://github.com/spring-projects/eclipse-integration-gradle/blob/master/README.md
Copy the latest release link: http://dist.springsource.com/release/TOOLS/gradle (latest release)
Use this in Eclipse->Help->Install New Software..->Paste the link in "Work With"->press enter->select the names of the extension->click next and agree the license and follow the prompts.
After you have installed just import the project as a grade project and eclipse will take of the rest.
Though there are already quite a few answers, I thought my answer might help some who have exactly the same problem as mine. In my case, the problem is caused by the following permissions added per the suggestion of an ad network:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
The consequence of the above permissions is that the following features are added automatically:
android.hardware.LOCATION
android.hardware.location.GPS
android.hardware.location.NETWORK
The reason is that "Google Play attempts to discover an application's implied feature requirements by examining other elements declared in the manifest file, specifically, elements." Two of my testing devices do not have the above features, so the app became incompatible with them. Removing those permissions solved the problem immediately.
You can also initialize data members at the point you declare them:
class another_example{
public:
another_example();
~another_example();
private:
int m_iInteger=10;
double m_dDouble=10.765;
};
I use this form pretty much exclusively, although I have read some people consider it 'bad form', perhaps because it was only recently introduced - I think in C++11. To me it is more logical.
Another useful facet to the new rules is how to initialize data-members that are themselves classes. For instance suppose that CDynamicString
is a class that encapsulates string handling. It has a constructor that allows you specify its initial value CDynamicString(wchat_t* pstrInitialString)
. You might very well use this class as a data member inside another class - say a class that encapsulates a windows registry value which in this case stores a postal address. To 'hard code' the registry key name to which this writes you use braces:
class Registry_Entry{
public:
Registry_Entry();
~Registry_Entry();
Commit();//Writes data to registry.
Retrieve();//Reads data from registry;
private:
CDynamicString m_cKeyName{L"Postal Address"};
CDynamicString m_cAddress;
};
Note the second string class which holds the actual postal address does not have an initializer so its default constructor will be called on creation - perhaps automatically setting it to a blank string.
git reset
is all about moving HEAD
, and generally the branch ref.
Question: what about the working tree and index?
When employed with --soft
, moves HEAD
, most often updating the branch ref, and only the HEAD
.
This differ from commit --amend
as:
commit --amend
is only about not moving HEAD, while allowing to redo the current commit)Just found this example of combining:
all into one (octopus, since there is more than two branches merged) commit merge.
Tomas "wereHamster" Carnecky explains in his "Subtree Octopus merge" article:
- The subtree merge strategy can be used if you want to merge one project into a subdirectory of another project, and the subsequently keep the subproject up to date. It is an alternative to git submodules.
- The octopus merge strategy can be used to merge three or more branches. The normal strategy can merge only two branches and if you try to merge more than that, git automatically falls back to the octopus strategy.
The problem is that you can choose only one strategy. But I wanted to combine the two in order to get a clean history in which the whole repository is atomically updated to a new version.
I have a superproject, let's call it
projectA
, and a subproject,projectB
, that I merged into a subdirectory ofprojectA
.
(that's the subtree merge part)
I'm also maintaining a few local commits.
ProjectA
is regularly updated,projectB
has a new version every couple days or weeks and usually depends on a particular version ofprojectA
.When I decide to update both projects, I don't simply pull from
projectA
andprojectB
as that would create two commits for what should be an atomic update of the whole project.
Instead, I create a single merge commit which combinesprojectA
,projectB
and my local commits.
The tricky part here is that this is an octopus merge (three heads), butprojectB
needs to be merged with the subtree strategy. So this is what I do:
# Merge projectA with the default strategy:
git merge projectA/master
# Merge projectB with the subtree strategy:
git merge -s subtree projectB/master
Here the author used a reset --hard
, and then read-tree
to restore what the first two merges had done to the working tree and index, but that is where reset --soft
can help:
How to I redo those two merges, which have worked, i.e. my working tree and index are fine, but without having to record those two commits?
# Move the HEAD, and just the HEAD, two commits back!
git reset --soft HEAD@{2}
Now, we can resume Tomas's solution:
# Pretend that we just did an octopus merge with three heads:
echo $(git rev-parse projectA/master) > .git/MERGE_HEAD
echo $(git rev-parse projectB/master) >> .git/MERGE_HEAD
# And finally do the commit:
git commit
So, each time:
git reset --soft
is the answer.
Avoid if, else and elseifs!
$loadMethod = "";
if(isset($_GET['s'])){
switch($_GET['s']){
case 'jwshxnsyllabus':
$loadMethod = "loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')";
break;
case 'aquinas':
$loadMethod = "loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')";
break;
case 'POP2':
$loadMethod = "loadSyllabi('POP2')";
}
}
echo '<body onload="'.$loadMethod.'">';
clean, readable code is maintainable code
Use a font-awesome icon as the default icon of your navbar.
<span class="navbar-toggler-icon">
<i class="fas fa-bars" style="color:#fff; font-size:28px;"></i>
</span>
Or try this on old font-awesome versions:
<span class="navbar-toggler-icon">
<i class="fa fa-navicon" style="color:#fff; font-size:28px;"></i>
</span>
const ValidateImg = (file) =>{_x000D_
let img = new Image()_x000D_
img.src = window.URL.createObjectURL(file)_x000D_
img.onload = () => {_x000D_
if(img.width === 100 && img.height ===100){_x000D_
alert("Correct size");_x000D_
return true;_x000D_
}_x000D_
alert("Incorrect size");_x000D_
return true;_x000D_
}_x000D_
}
_x000D_
For those who want the same but are using React
openFileInput = () => {
this.fileInput.click()
}
<a href="#" onClick={this.openFileInput}>
<p>Carregue sua foto de perfil</p>
<img src={img} />
</a>
<input style={{display:'none'}} ref={(input) => { this.fileInput = input; }} type="file"/>
In datatable options put this:
$(document).ready( function() {
$('#example').dataTable({
"aaSorting": [[ 2, 'asc' ]],
//More options ...
});
})
Here is the solution: "aaSorting": [[ 2, 'asc' ]],
2
means table will be sorted by third column,
asc
in ascending order.
What about using extension method?
public static class StringExtensions
{
public static string Repeat(this char chatToRepeat, int repeat) {
return new string(chatToRepeat,repeat);
}
public static string Repeat(this string stringToRepeat,int repeat)
{
var builder = new StringBuilder(repeat*stringToRepeat.Length);
for (int i = 0; i < repeat; i++) {
builder.Append(stringToRepeat);
}
return builder.ToString();
}
}
You could then write :
Debug.WriteLine('-'.Repeat(100)); // For Chars
Debug.WriteLine("Hello".Repeat(100)); // For Strings
Note that a performance test of using the stringbuilder version for simple characters instead of strings gives you a major preformance penality :
on my computer the difference in mesured performance is 1:20 between:
Debug.WriteLine('-'.Repeat(1000000)) //char version and
Debug.WriteLine("-".Repeat(1000000)) //string version
They don't do the same thing. The first one works if obj is of type ClassA or of some subclass of ClassA. The second one will only match objects of type ClassA. The second one will be faster since it doesn't have to check the class hierarchy.
For those who want to know the reason, but don't want to read the article referenced in is vs typeof.
Below works fine.
//a[@id='oldcontent']
If you've tried certain ones and they haven't worked, then let us know, otherwise something simple like this should work.
This answer is a bit of expansion for @rastating's great answer. You can use the following code for all versions of .NET without any worries:
public static void SetDefaultCulture(CultureInfo culture)
{
Type type = typeof (CultureInfo);
try
{
// Class "ReflectionContext" exists from .NET 4.5 onwards.
if (Type.GetType("System.Reflection.ReflectionContext", false) != null)
{
type.GetProperty("DefaultThreadCurrentCulture")
.SetValue(System.Threading.Thread.CurrentThread.CurrentCulture,
culture, null);
type.GetProperty("DefaultThreadCurrentUICulture")
.SetValue(System.Threading.Thread.CurrentThread.CurrentCulture,
culture, null);
}
else //.NET 4 and lower
{
type.InvokeMember("s_userDefaultCulture",
BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static,
null,
culture,
new object[] {culture});
type.InvokeMember("s_userDefaultUICulture",
BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static,
null,
culture,
new object[] {culture});
type.InvokeMember("m_userDefaultCulture",
BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static,
null,
culture,
new object[] {culture});
type.InvokeMember("m_userDefaultUICulture",
BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static,
null,
culture,
new object[] {culture});
}
}
catch
{
// ignored
}
}
}
I faced a similar issue where XML was containing control characters. After looking into the code, I found that a deprecated class,StringBufferInputStream, was used for reading string content.
http://docs.oracle.com/javase/7/docs/api/java/io/StringBufferInputStream.html
This class does not properly convert characters into bytes. As of JDK 1.1, the preferred way to create a stream from a string is via the StringReader class.
I changed it to ByteArrayInputStream and it worked fine.
if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond()
method.
Edit
for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED
action
This would do
string x = TextBoxD1.Text;
int xi = Convert.ToInt32(x);
Or you can use
int xi = Int32.Parse(x);
d = {"name":"interpolator",
"children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)
Of course, it's unlikely that the order will be exactly preserved ... But that's just the nature of dictionaries ...
I had the same problem and Andrew is correct. Check your classpath variable "M2_REPO". It probably points to an invalid location of your local maven repo.
In my case I was using mvn eclipse:eclipse
on the command line and this plugin was setting the M2_REPO classpath variable. Eclipse couldn't find my maven settings.xml in my home directory and as a result was incorrectly the M2_REPO classpath variable. My solution was to restart eclipse and it picked up my settings.xml and removed the red exclamation on my projects.
I got some more information from this guy: http://www.mkyong.com/maven/how-to-configure-m2_repo-variable-in-eclipse-ide/
I tend to use Homebrew on Mac. It will install and configure all the stuff for you.
http://mxcl.github.com/homebrew/
Then you should be able to install it with brew install mcrypt php53-mcrypt
and it'll Just Work (tm).
You can replace the 53
with whatever version of PHP you're using, such as php56-mcrypt
or php70-mcrypt
. If you're not sure, use brew search php
.
Do also remember that if you are using the built in Mac PHP it's installed into /usr/bin
you can see which php you are using with which php
at the terminal and it'll return the path.
Given sheet 2:
ColumnA
-------
apple
orange
You can flag the rows in sheet 1 where a value exists in sheet 2:
ColumnA ColumnB
------- --------------
pear =IF(ISERROR(VLOOKUP(A1,Sheet2!A:A,1,FALSE)),"Keep","Delete")
apple =IF(ISERROR(VLOOKUP(A2,Sheet2!A:A,1,FALSE)),"Keep","Delete")
cherry =IF(ISERROR(VLOOKUP(A3,Sheet2!A:A,1,FALSE)),"Keep","Delete")
orange =IF(ISERROR(VLOOKUP(A4,Sheet2!A:A,1,FALSE)),"Keep","Delete")
plum =IF(ISERROR(VLOOKUP(A5,Sheet2!A:A,1,FALSE)),"Keep","Delete")
The resulting data looks like this:
ColumnA ColumnB
------- --------------
pear Keep
apple Delete
cherry Keep
orange Delete
plum Keep
You can then easily filter or sort sheet 1 and delete the rows flagged with 'Delete'.
add an ALIAS
on the subquery,
SELECT COUNT(made_only_recharge) AS made_only_recharge
FROM
(
SELECT DISTINCT (identifiant) AS made_only_recharge
FROM cdr_data
WHERE CALLEDNUMBER = '0130'
EXCEPT
SELECT DISTINCT (identifiant) AS made_only_recharge
FROM cdr_data
WHERE CALLEDNUMBER != '0130'
) AS derivedTable -- <<== HERE
We managed installation of netbeans 6.8 under windows 8 successfully the following way:
-> installation executes without any errors
AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.
As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.
So AArch64 and ARM64 refer to the same thing.
Historically a \n
was used to move the carriage down, while the \r
was used to move the carriage back to the left side of the page.
Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
objBL.date = Convert.ToDateTime(txtDate.Value).ToString(timeFormat)
I found using okHttp a lot easier as I could not get any of these solutions to work: https://stackoverflow.com/a/37942387/447549
You can use: if(-e $base_path)
I've got this working in a similar situation for moving to next page like this:
$("#page_next").click(function () {
$("#pageNumber").val(parseInt($("#pageNumber").val()) + 1);
submitForm(this);
return false;
});
You should be able to add brackets to achieve what you want something like this:
var newcurrentpageTemp = (parseInt($(this).attr("id"))) + 1;//Get the id from the hyperlink
->where()
support passing any string to it and it will use it in the query.
You can try using this:
$this->db->select('*')->from('certs');
$this->db->where('`id` NOT IN (SELECT `id_cer` FROM `revokace`)', NULL, FALSE);
The ,NULL,FALSE
in the where()
tells CodeIgniter not to escape the query, which may mess it up.
UPDATE: You can also check out the subquery library I wrote.
$this->db->select('*')->from('certs');
$sub = $this->subquery->start_subquery('where_in');
$sub->select('id_cer')->from('revokace');
$this->subquery->end_subquery('id', FALSE);
If any of other solution doesn't fix it, try to override the styles to hide the sort togglers:
.sorting_asc:after, .sorting_desc:after {
content: "";
}
$(this).parents(".ui-dialog-content").dialog('close')
Simple, I like to make sure I don't:
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
The only way I found which works for me is adding an entry into the "Web Deployment Assembly"
Project webapp > Properties > Deployment Assembly
Add ...
Source : "/target/classes"
Deploy Path : "WEB-INF/classes"
Judging by the declaration and description of the startsWith
Java function, the "most straight forward way" to implement it in VBA would either be with Left
:
Public Function startsWith(str As String, prefix As String) As Boolean
startsWith = Left(str, Len(prefix)) = prefix
End Function
Or, if you want to have the offset parameter available, with Mid
:
Public Function startsWith(str As String, prefix As String, Optional toffset As Integer = 0) As Boolean
startsWith = Mid(str, toffset + 1, Len(prefix)) = prefix
End Function
You have to understand how Unix interprets your input.
The standard Unix shell interpolates environment variables, and what are called globs before it passes the parameters to your program. This is a bit different from Windows which makes the program interpret the expansion.
Try this:
$ echo *
This will echo all the files and directories in your current directory. Before the echo
command acts, the shell interpolates the *
and expands it, then passes that expanded parameter back to your command. You can see it in action by doing this:
$ set -xv
$ echo *
$ set +xv
The set -xv
turns on xtrace and verbose. Verbose echoes the command as entered, and xtrace echos the command that will be executed (that is, after the shell expansion).
Now try this:
$ echo "*"
Note that putting something inside quotes hides the glob expression from the shell, and the shell cannot expand it. Try this:
$ foo="this is the value of foo"
$ echo $foo
$ echo "$foo"
$ echo '$foo'
Note that the shell can still expand environment variables inside double quotes, but not in single quotes.
Now let's look at your statement:
file="home/edward/bank1/fiche/Test*"
The double quotes prevent the shell from expanding the glob expression, so file
is equal to the literal home/edward/bank1/finche/Test*
. Therefore, you need to do this:
file=/home/edward/bank1/fiche/Test*
The lack of quotes (and the introductory slash which is important!) will now make file equal to all files that match that expression. (There might be more than one!). If there are no files, depending upon the shell, and its settings, the shell may simply set file to that literal string anyway.
You certainly have the right idea:
file=/home/edward/bank1/fiche/Test*
if test -s $file
then
echo "found one"
else
echo "found none"
fi
However, you still might get found none returned if there is more than one file. Instead, you might get an error in your test
command because there are too many parameters.
One way to get around this might be:
if ls /home/edward/bank1/finche/Test* > /dev/null 2>&1
then
echo "There is at least one match (maybe more)!"
else
echo "No files found"
fi
In this case, I'm taking advantage of the exit code of the ls
command. If ls
finds one file it can access, it returns a zero exit code. If it can't find one matching file, it returns a non-zero exit code. The if
command merely executes a command, and then if the command returns a zero, it assumes the if
statement as true and executes the if
clause. If the command returns a non-zero value, the if
statement is assumed to be false, and the else
clause (if one is available) is executed.
The test
command works in a similar fashion. If the test
is true, the test
command returns a zero. Otherwise, the test
command returns a non-zero value. This works great with the if
command. In fact, there's an alias to the test
command. Try this:
$ ls -li /bin/test /bin/[
The i
prints out the inode. The inode is the real ID of the file. Files with the same ID are the same file. You can see that /bin/test
and /bin/[
are the same command. This makes the following two commands the same:
if test -s $file
then
echo "The file exists"
fi
if [ -s $file ]
then
echo "The file exists"
fi
Another option is GhostDriver which is now officially supported by WebDriver: Ghostdriver actual performance gain
Assuming you are talking about the current URL, you can parse out part of the URL using window.location
.
See: http://java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript
See the Create a video slideshow from images – FFmpeg
If your video does not show the frames correctly If you encounter problems, such as the first image is skipped or only shows for one frame, then use the fps video filter instead of -r for the output framerate
ffmpeg -r 1/5 -i img%03d.png -c:v libx264 -vf fps=25 -pix_fmt yuv420p out.mp4
Alternatively the format video filter can be added to the filter chain to replace -pix_fmt yuv420p like "fps=25,format=yuv420p". The advantage of this method is that you can control which filter goes first
ffmpeg -r 1/5 -i img%03d.png -c:v libx264 -vf "fps=25,format=yuv420p" out.mp4
I tested below parameters, it worked for me
"e:\ffmpeg\ffmpeg.exe" -r 1/5 -start_number 0 -i "E:\images\01\padlock%3d.png" -c:v libx264 -vf "fps=25,format=yuv420p" e:\out.mp4
below parameters also worked but it always skips the first image
"e:\ffmpeg\ffmpeg.exe" -r 1/5 -start_number 0 -i "E:\images\01\padlock%3d.png" -c:v libx264 -r 30 -pix_fmt yuv420p e:\out.mp4
making a video from images placed in different folders
First, add image paths to imagepaths.txt like below.
# this is a comment details https://trac.ffmpeg.org/wiki/Concatenate
file 'E:\images\png\images__%3d.jpg'
file 'E:\images\jpg\images__%3d.jpg'
Sample usage as follows;
"h:\ffmpeg\ffmpeg.exe" -y -r 1/5 -f concat -safe 0 -i "E:\images\imagepaths.txt" -c:v libx264 -vf "fps=25,format=yuv420p" "e:\out.mp4"
-safe 0 parameter prevents Unsafe file name error
Related links
FFmpeg making a video from images placed in different folders
Assuming SQL Server:
e.g. if you class special characters as anything NOT alphanumeric:
DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'
IF (@MyString LIKE '%[^a-zA-Z0-9]%')
PRINT 'Contains "special" characters'
ELSE
PRINT 'Does not contain "special" characters'
Just add to other characters you don't class as special, inside the square brackets
andig is correct that a common reason for LayoutInflater ignoring your layout_params would be because a root was not specified. Many people think you can pass in null for root. This is acceptable for a few scenarios such as a dialog, where you don't have access to root at the time of creation. A good rule to follow, however, is that if you have root, give it to LayoutInflater.
I wrote an in-depth blog post about this that you can check out here:
https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/
Try with your IP Address , I think you can access it by internet.
It's all about the linkage.
The previous answers provided good explainations about extern
.
But I want to add an important point.
You ask about extern
in C++ not in C and I don't know why there is no answer mentioning about the case when extern
comes with const
in C++.
In C++, a const
variable has internal linkage by default (not like C).
So this scenario will lead to linking error:
Source 1 :
const int global = 255; //wrong way to make a definition of global const variable in C++
Source 2 :
extern const int global; //declaration
It need to be like this:
Source 1 :
extern const int global = 255; //a definition of global const variable in C++
Source 2 :
extern const int global; //declaration
- hosts: lnx
tasks:
- find: paths="/appl/scripts/inq" recurse=yes patterns="inq.Linux*"
register: file_to_copy
- copy: src={{ item.path }} dest=/usr/local/sbin/
owner: root
mode: 0775
with_items: "{{ files_to_copy.files }}"
flush the response to the client before response.end()
More about Response.Flush Method
So use the below-mentioned code before response.End();
response.Flush();
Its may be due to the default storage space set to 40GB ( default path , /var/lib/docker)
you can change the storage volume to point to different path
DOCKER_STORAGE_OPTIONS='--storage-driver=overlay --graph=CUSTOM_PATH'
if you run command docker info ( it should show storage driver as overlay)
using System.IO;
using System.Text;
using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{
sw.WriteLine("my text...");
}
An alternate way of getting your encoding:
using System.IO;
using System.Text;
using (var sw = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
sw.WriteLine("my text...");
}
Check out the docs for the StreamWriter constructor.
you want to use include_once() or require_once(). The other option would be to create an additional file with all your class includes in the correct order so they don't need to call includes themselves:
"classes.php"
include 'database.php';
include 'parent.php';
include 'child1.php';
include 'child2.php';
Then you just need:
require_once('classes.php');
You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.
You can use google map Obtaining User Location here!
After obtaining your location(longitude and latitude), you can use google place api
This code can help you get your location easily but not the best way.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
This should work:
/^((?!PART).)*$/
If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:
/^(?!PART)/
The (?!...)
syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/
." The site I've linked explains this far better than I can, but I'll try to break this down:
^ #Start matching from the beginning of the string.
(?!PART) #This position must not be followed by the string "PART".
. #Matches any character except line breaks (it will include those in single-line mode).
$ #Match all the way until the end of the string.
The ((?!xxx).)*
idiom is probably hardest to understand. As we saw, (?!PART)
looks at the string ahead and says that whatever comes next can't match the subpattern /PART/
. So what we're doing with ((?!xxx).)*
is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.
The ^
and $
anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.
Since we do have ^
and $
, if PART were anywhere in the string, one of the characters would match (?=PART).
and the overall match would fail. Hope that's clear enough to be helpful.
I have had excellent success with a technique which resembles the X macros pointed to by @RolandXu. We made heavy use of the stringize operator, too. The technique mitigates the maintenance nightmare when you have an application domain where items appear both as strings and as numerical tokens.
It comes in particularily handy when machine readable documentation is available so that the macro X(...) lines can be auto-generated. A new documentation would immediately result in a consistent program update covering the strings, enums and the dictionaries translating between them in both directions. (We were dealing with PCL6 tokens).
And while the preprocessor code looks pretty ugly, all those technicalities can be hidden in the header files which never have to be touched again, and neither do the source files. Everything is type safe. The only thing that changes is a text file containing all the X(...) lines, and that is possibly auto generated.
For more generic advice on debugging this kind of problem MDN have a good article TypeError: "x" is not a function:
It was attempted to call a value like a function, but the value is not actually a function. Some code expects you to provide a function, but that didn't happen.
Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript objects have no map function, but JavaScript Array object do.
Basically the object (all functions in js are also objects) does not exist where you think it does. This could be for numerous reasons including(not an extensive list):
var x = function(){_x000D_
var y = function() {_x000D_
alert('fired y');_x000D_
}_x000D_
};_x000D_
_x000D_
//the global scope can't access y because it is closed over in x and not exposed_x000D_
//y is not a function err triggered_x000D_
x.y();
_x000D_
var x = function(){_x000D_
var y = function() {_x000D_
alert('fired y');_x000D_
}_x000D_
};_x000D_
_x000D_
//z is not a function error (as above) triggered_x000D_
x.z();
_x000D_
I think stash -p
is probably the choice you want, but just in case you run into other even more tricky things in the future, remember that:
Stash
is really just a very simple alternative to the only slightly more complex branch
sets. Stash is very useful for moving things around quickly, but you can accomplish more complex things with branches without that much more headache and work.
# git checkout -b tmpbranch
# git add the_file
# git commit -m "stashing the_file"
# git checkout master
go about and do what you want, and then later simply rebase
and/or merge
the tmpbranch. It really isn't that much extra work when you need to do more careful tracking than stash will allow.
select field1, field2, 'example' as TempField
from table1
This should work across different SQL implementations.
What you could do is create a new class, similar to @Gregoire's example, however, you would want to override the ToString()
method so it appears correctly in the combo box e.g.
public class Language
{
private string _name;
private string _code;
public Language(string name, string code)
{
_name = name;
_code = code;
}
public string Name { get { return _name; } }
public string Code { get { return _code; } }
public override void ToString()
{
return _name;
}
}
Try this:
import requests
import json
# Goole Maps API.
link = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'
# Request data from link as 'str'
data = requests.get(link).text
# convert 'str' to Json
data = json.loads(data)
# Now you can access Json
for i in data['routes'][0]['legs'][0]['steps']:
lattitude = i['start_location']['lat']
longitude = i['start_location']['lng']
print('{}, {}'.format(lattitude, longitude))
That didn't really work in my case - i.e. in order to overwrite hosts file you have to follow it's directions, ie:
./emulator -avd myEmulatorName -partition-size 280
and then in other term window (pushing new hosts file /tmp/hosts):
./adb remount
./adb push /tmp/hosts /system/etc
I had the same problem and found a very elegant solution for a Pager Class from
http://blogs.taiga.nl/martijn/2008/08/27/paging-with-aspnet-mvc/
In your controller the call looks like:
return View(partnerList.ToPagedList(currentPageIndex, pageSize));
and in your view:
<div class="pager">
Seite: <%= Html.Pager(ViewData.Model.PageSize,
ViewData.Model.PageNumber,
ViewData.Model.TotalItemCount)%>
</div>
In my case it helped.
main_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.livewallpaper.profileview.loginact.Main2Activity">
<TextView
android:layout_weight="1"
android:layout_width="match_parent"
android:text="Title"
android:gravity="center"
android:layout_height="0dp" />
<LinearLayout
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp">
<EditText
android:hint="enter here"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:layout_weight="1"
android:text="signup for App"
android:gravity="bottom|center_horizontal"
android:layout_width="match_parent"
android:layout_height="0dp" />
</LinearLayout>
Use this in manifest
file
<activity android:name=".MainActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize"/>
Now the most important part!
Use theme like this in either Activity
or Application
tag.
android:theme="@style/AppTheme"
And the theme tooks like this
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="windowActionModeOverlay">true</item>
</style>
So I was missing the theme. Which made me frustrated all day.
You need to use background-image instead of backgroundImage. For example:
$(function() {
$('.home').click(function() {
$(this).css('background-image', 'url(images/tabs3.png)');
});
}):
Use prop() instead of attr() to set the value of checked
. Also use :checkbox
in find method instead of input
and be specific.
$("#news_list tr").click(function() {
var ele = $(this).find('input');
if(ele.is(':checked')){
ele.prop('checked', false);
$(this).removeClass('admin_checked');
}else{
ele.prop('checked', true);
$(this).addClass('admin_checked');
}
});
Use prop instead of attr for properties like checked
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method
If you wanna find just the word like 'are' in "How are you?" and not like 'are' in 'hare'
$word=" are ";
$str="How are you?";
if(strpos($word,$str) !== false){
echo 1;
}
open your browser,check whether Tomcat homepage is visible by below command.
http://ipaddress:portnumber
also check this
const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();
dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);
document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
_x000D_
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script src="https://momentjs.com/downloads/moment.js"></script>
</body>
</html>
_x000D_
One way to order by positive integers, when they are stored as varchar
, is to order by the length first and then the value:
order by len(registration_no), registration_no
This is particularly useful when the column might contain non-numeric values.
Note: in some databases, the function to get the length of a string might be called length()
instead of len()
.
json.dumps()
is used to decode JSON dataimport json
# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
'int': int_data,
'str': str_data,
'float': float_data,
'list': list_data,
'nested list': nested_list
}
# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4)) # the json data will be indented
output:
String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
1,
1.5,
[
"normal string",
1,
1.5
]
]
Dictionary : {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
| Python | JSON |
|:--------------------------------------:|:------:|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
json.loads()
is used to convert JSON data into Python data.import json
# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'
# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)
print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])
print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])
output:
arrayJson to list_data :
[1, 1.5, ['normal string', 1, 1.5]]
Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]
objectJson to dictionary :
{'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}
Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
| JSON | Python |
|:-------------:|:------:|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (real) | float |
| true | True |
| false | False |
Instead of using
response.sendRedirect("/demo.jsp");
Which does a permanent redirect to an absolute URL path,
Rather use RequestDispatcher
. Example:
RequestDispatcher dispatcher = request.getRequestDispatcher("demo.jsp");
dispatcher.forward(request, response);
select COUNT(*) from ALL_ALL_TABLES where OWNER='<Database-name>';
.....
public boolean hasLoop(Node start){
TreeSet<Node> set = new TreeSet<Node>();
Node lookingAt = start;
while (lookingAt.peek() != null){
lookingAt = lookingAt.next;
if (set.contains(lookingAt){
return false;
} else {
set.put(lookingAt);
}
return true;
}
// Inside our Node class:
public Node peek(){
return this.next;
}
Forgive me my ignorance (I'm still fairly new to Java and programming), but why wouldn't the above work?
I guess this doesn't solve the constant space issue... but it does at least get there in a reasonable time, correct? It will only take the space of the linked list plus the space of a set with n elements (where n is the number of elements in the linked list, or the number of elements until it reaches a loop). And for time, worst-case analysis, I think, would suggest O(nlog(n)). SortedSet look-ups for contains() are log(n) (check the javadoc, but I'm pretty sure TreeSet's underlying structure is TreeMap, whose in turn is a red-black tree), and in the worst case (no loops, or loop at very end), it will have to do n look-ups.
If the indices match then:
df['B'] = df1['E']
should work otherwise:
df['B'] = df1['E'].values
will work so long as the length of the elements matches
You can do
display/i $pc
and every time GDB stops, it will display the disassembly of the next instruction.
GDB-7.0
also supports set disassemble-next-line on
, which will disassemble the entire next line, and give you more of the disassembly context.
You are dynamically generating those elements so any listener applied on page load wont be available. I have edited your fiddle with the correct solution. Basically jQuery holds the event for later binding by attaching it to the parent Element and propagating it downward to the correct dynamically created element.
$('#musics').on('change', '#want',function(e) {
$(this).closest('.from-group').val(($('#want').is(':checked')) ? "yes" : "no");
var ans=$(this).val();
console.log(($('#want').is(':checked')));
});
>>> A = {'a':1, 'b':2, 'c':3}
>>> B = {'b':3, 'c':4, 'd':5}
>>> c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
>>> print(c)
{'a': 1, 'c': 7, 'b': 5, 'd': 5}
Code::Blocks is Great.
close your R studio and run it again as an administrator. That did the magic for me. Hope it works for you and anyone going through this too.
<meta http-equiv="pragma" content="no-cache" />
Also see https://stackoverflow.com/questions/126772/how-to-force-a-web-browser-not-to-cache-images
The validation was working for me on form submission, but it wasn't doing the reactive event driven validation on input to the chosen select lists.
To fix this I added the following to manually trigger the jquery validation event that gets added by the library:
$(".chosen-select").each(function() {
$(this).chosen().on("change", function() {
$(this).parents(".form-group").find("select.form-control").trigger("focusout.validate");
});
});
jquery.validate will now add the .valid
class to the underlying select list.
Caveat: This does require a consistent html pattern for your form inputs. In my case, each input filed is wrapped in a div.form-group
, and each input has .form-control
.
Look into the Thinktecture IdentityModel library -- it has full CORS support:
http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/
And it can dynamically emit the ACA-Origin you want.
To resolve this error:
bash:
$ eval `ssh-agent -s`
tcsh:
$ eval `ssh-agent -c`
Then use ssh-add
as you normally would.
Hot Tip:
I was always forgetting what to type for the above ssh-agent commands, so I created an alias in my .bashrc
file like this:
alias ssh-agent-cyg='eval `ssh-agent -s`'
Now instead of using ssh-agent
, I can use ssh-agent-cyg
E.g.
$ ssh-agent-cyg
SSH_AUTH_SOCK=/tmp/ssh-n16KsxjuTMiM/agent.32394; export SSH_AUTH_SOCK;
SSH_AGENT_PID=32395; export SSH_AGENT_PID;
echo Agent pid 32395;
$ ssh-add ~/.ssh/my_pk
Original Source of fix:
Exim 4 requires that AUTH command only be sent after the client issued EHLO - attempts to authenticate without EHLO would be rejected. Some mailservers require that EHLO be issued twice. PHPMailer apparently fails to do so. If PHPMailer does not allow you to force EHLO initiation, you really should switch to SwiftMailer 4.
Compiling other answers:
var test = {};
When using a number as a new property's key, the number turns into a string:
test[2300] = 'Some string';
console.log(test['2300']);
// Output: 'Some string'
When accessing the property's value using the same number, the number is turned into a string again:
console.log(test[2300]);
// Output: 'Some string'
When getting the keys from the object, though, they aren't going to be turned back into numbers:
for (var key in test) {
console.log(typeof key);
}
// Output: 'string'
ECMAScript 6 allows the use of the Map object (documentation, a comparison with Object). If your code is meant to be interpreted locally or the ECMAScript 6 compatibility table looks green enough for your purposes, consider using a Map:
var test = new Map();
test.set(2300, 'Some string');
console.log(test.get(2300));
// Output: 'Some string'
No type conversion is performed, for better and for worse:
console.log(test.get('2300'));
// Output: undefined
test.set('2300', 'Very different string');
console.log(test.get(2300));
// Output: 'Some string'
You could try the tips in this post Why your Android Studio takes forever to build - Part 2 One of the tips recommmends "Enable offline mode" among other things.
In addition to running it with mvn exec:java
, you can also run it with mvn exec:exec
mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath your.package.MainClass"
I am assuming you want to pass the database name as a parameter and not just run:
SELECT *
FROM DBName.sys.tables
WHERE Name LIKE '%XXX%'
If so, you could use dynamic SQL to add the dbname to the query:
DECLARE @DBName NVARCHAR(200) = 'YourDBName',
@TableName NVARCHAR(200) = 'SomeString';
IF NOT EXISTS (SELECT 1 FROM master.sys.databases WHERE Name = @DBName)
BEGIN
PRINT 'DATABASE NOT FOUND';
RETURN;
END;
DECLARE @SQL NVARCHAR(MAX) = ' SELECT Name
FROM ' + QUOTENAME(@DBName) + '.sys.tables
WHERE Name LIKE ''%'' + @Table + ''%''';
EXECUTE SP_EXECUTESQL @SQL, N'@Table NVARCHAR(200)', @TableName;
I had the same problem today, after upgrading node from v9 to v10.
My environment is set by docker and I had to remove this command from the my DockerFile :
npm link @angular/cli
It creates a symlink to the directory where node is installed.
I guess the angular/cli
module in it do not have the same version as the one in the node_modules dir of my project, and this causes the issue.
How about catching the exception that gets generated from the assertion failure? In your catch block you could output the data however you wanted to wherever. Then when you were done you could re-throw the exception. The test runner probably wouldn't know the difference.
Disclaimer: I haven't tried this with python's unit test framework but have with other unit test frameworks.
You can't, but... If you own both pages then...
1) You can send the data via query params (http://siteB.com/?key=value)
2) You can create an iframe of Site B inside site A and you can send post messages from one place to the other. As Site B is the owner of site B cookies it will be able to set whatever value you need by processing the correct post message. (You should prevent other unwanted senders to send messages to you! that is up to you and the mechanism you decide to use to prevent that from happening)
This error happened to me when I was using Visual Studio Code. I think it must have been because I was trying to build a project while there was an executable running in the same bin\debug folder. I stopped the executable, closed the folder, reopened, rebuilt, and the error went away.
import React from 'react';_x000D_
import {withRouter, Link} from "react-router-dom";_x000D_
_x000D_
const SidenavItems = (props) => {_x000D_
// create simple list of links_x000D_
const items = [_x000D_
{_x000D_
type: "navItem",_x000D_
icon: "home",_x000D_
text: "Home",_x000D_
link: "/",_x000D_
restricted: false_x000D_
},_x000D_
{_x000D_
type: "navItem",_x000D_
icon: "user-circle",_x000D_
text: "My Profile",_x000D_
link: "/user",_x000D_
restricted: false_x000D_
},_x000D_
{_x000D_
type: "navItem",_x000D_
icon: "sign-in",_x000D_
text: "Login",_x000D_
link: "/login",_x000D_
restricted: false_x000D_
},_x000D_
];_x000D_
_x000D_
const element = (item, i) => { // create elements (Links)_x000D_
// check if this is a current link on browser_x000D_
let active = "";_x000D_
_x000D_
if (props.location.pathname === item.link) {_x000D_
active = "active";_x000D_
}_x000D_
_x000D_
return (_x000D_
<div key={i} className={item.type}>_x000D_
<Link_x000D_
to={item.link}_x000D_
className={active} // className will be set to "active" _x000D_
> // or ""_x000D_
{item.text}_x000D_
</Link>_x000D_
</div>_x000D_
)_x000D_
};_x000D_
_x000D_
const showItems = () => { // print elements_x000D_
return items.map((item, i) => {_x000D_
return element(item, i)_x000D_
})_x000D_
};_x000D_
_x000D_
return (_x000D_
<div>_x000D_
{showItems()} // print all the links we created in list_x000D_
</div>_x000D_
)_x000D_
};_x000D_
export default withRouter(SidenavItems);
_x000D_
I needed to do this for a sales report that allows the user to choose a date range. The solution is similar to another answer, but I wanted to provide my example just to show you the practical real world use that I applied this to:
var reportHeader = `Product Sales History Report for ${$('#FromDate').val()} to ${$('#ToDate').val()}.` ;
```
You can also just Marshal.Copy the bitmap data. No intermediary memorystream etc. and a fast memory copy. This should work on both 24-bit and 32-bit bitmaps.
public static byte[] BitmapToByteArray(Bitmap bitmap)
{
BitmapData bmpdata = null;
try
{
bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
int numbytes = bmpdata.Stride * bitmap.Height;
byte[] bytedata = new byte[numbytes];
IntPtr ptr = bmpdata.Scan0;
Marshal.Copy(ptr, bytedata, 0, numbytes);
return bytedata;
}
finally
{
if (bmpdata != null)
bitmap.UnlockBits(bmpdata);
}
}
.
I would use JTidy - it is simlar to JSoup, but I don't know JSoup well. JTidy handles broken HTML and returns a w3c Document, so you can use this as a source to XSLT to extract the content you are really interested in. If you don't know XSLT, then you might as well go with JSoup, as the Document model is nicer to work with than w3c.
EDIT: A quick look on the JSoup website shows that JSoup may indeed be the better choice. It seems to support CSS selectors out the box for extracting stuff from the document. This may be a lot easier to work with than getting into XSLT.
Try This
import hashlib
user = input("Enter text here ")
h = hashlib.md5(user.encode())
h2 = h.hexdigest()
print(h2)
Code Snippet1:
NSMutableArray *array = [[NSMutableArray alloc] init];
NSArray * values = [dictionary allValues];
[array addObject:values];
Code Snippet2: If you want to add further
[array addObject:value1];
[array addObject:value2];
[array addObject:value3];
And so on
Also you can store key values of dictionary to array
NSArray *keys = [dictionary allKeys];
I used this and it works well:
string[] filePaths = Directory.GetFiles(Path.GetDirectoryName(dialog.FileName));
foreach (string file in filePaths)
{
if (comboBox1.SelectedItem.ToString() == "")
{
if (file.Contains("c"))
{
comboBox2.Items.Add(Path.GetFileName(file));
}
}
}
Gutch's code is close, but it'll only work right if:
The Approved Method is to do it the other way around. Open the existing document with a PdfStamper, and use the returned PdfContentByte from getOverContent() to write text (and whatever else you might need) directly to the page. No second document needed.
And you can use a ColumnText to handle layout and such for you... no need to get down and dirty with beginText(),setFontAndSize(),drawText(),drawText()...,endText().
Since people will be coming from Google, make sure you're in the right database.
Running SQL in the 'master' database will often return this error.
Summary:
The curl_exec
command in PHP is a bridge to use curl
from console. curl_exec makes it easy to quickly and easily do GET/POST requests, receive responses from other servers like JSON and download files.
Warning, Danger:
curl
is evil and dangerous if used improperly because it is all about getting data from out there in the internet. Someone can get between your curl and the other server and inject a rm -rf /
into your response, and then why am I dropped to a console and ls -l
doesn't even work anymore? Because you mis underestimated the dangerous power of curl. Don't trust anything that comes back from curl to be safe, even if you are talking to your own servers. You could be pulling back malware to relieve fools of their wealth.
These were done on Ubuntu 12.10
Basic curl from the commandline:
el@apollo:/home/el$ curl http://i.imgur.com/4rBHtSm.gif > mycat.gif
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 492k 100 492k 0 0 1077k 0 --:--:-- --:--:-- --:--:-- 1240k
Then you can open up your gif in firefox:
firefox mycat.gif
Glorious cats evolving Toxoplasma gondii to cause women to keep cats around and men likewise to keep the women around.
cURL example get request to hit google.com, echo to the commandline:
This is done through the phpsh terminal:
php> $ch = curl_init();
php> curl_setopt($ch, CURLOPT_URL, 'http://www.google.com');
php> curl_exec($ch);
Which prints and dumps a mess of condensed html and javascript (from google) to the console.
cURL example put the response text into a variable:
This is done through the phpsh terminal:
php> $ch = curl_init();
php> curl_setopt($ch, CURLOPT_URL, 'http://i.imgur.com/wtQ6yZR.gif');
php> curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
php> $contents = curl_exec($ch);
php> echo $contents;
The variable now contains the binary which is an animated gif of a cat, possibilities are infinite.
Do a curl from within a PHP file:
Put this code in a file called myphp.php:
<?php
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'http://www.google.com');
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
if (empty($buffer)){
print "Nothing returned from url.<p>";
}
else{
print $buffer;
}
?>
Then run it via commandline:
php < myphp.php
You ran myphp.php and executed those commands through the php interpreter and dumped a ton of messy html and javascript to screen.
You can do GET
and POST
requests with curl, all you do is specify the parameters as defined here: Using curl to automate HTTP jobs
Reminder of danger:
Be careful dumping curl output around, if any of it gets interpreted and executed, your box is owned and your credit card info will be sold to third parties and you'll get a mysterious $900 charge from an Alabama one-man flooring company that's a front for overseas credit card fraud crime ring.
You could use this script:
def run(runfile):
with open(runfile,"r") as rnf:
exec(rnf.read())
Syntax:
run("file.py")
In order to keep track of dependency issues, I like to use the conda installer, which simply boils down to:
conda install openpyxl
This works — it isn't what I'd use, but it 'works'. Let's create a script teredo
to set the environment variable TEREDO_WORMS
:
#!/bin/ksh
export TEREDO_WORMS=ukelele
exec $SHELL -i
It will be interpreted by the Korn shell, exports the environment variable, and then replaces itself with a new interactive shell.
Before running this script, we have SHELL
set in the environment to the C shell, and the environment variable TEREDO_WORMS
is not set:
% env | grep SHELL
SHELL=/bin/csh
% env | grep TEREDO
%
When the script is run, you are in a new shell, another interactive C shell, but the environment variable is set:
% teredo
% env | grep TEREDO
TEREDO_WORMS=ukelele
%
When you exit from this shell, the original shell takes over:
% exit
% env | grep TEREDO
%
The environment variable is not set in the original shell's environment. If you use exec teredo
to run the command, then the original interactive shell is replaced by the Korn shell that sets the environment, and then that in turn is replaced by a new interactive C shell:
% exec teredo
% env | grep TEREDO
TEREDO_WORMS=ukelele
%
If you type exit
(or Control-D), then your shell exits, probably logging you out of that window, or taking you back to the previous level of shell from where the experiments started.
The same mechanism works for Bash or Korn shell. You may find that the prompt after the exit commands appears in funny places.
Note the discussion in the comments. This is not a solution I would recommend, but it does achieve the stated purpose of a single script to set the environment that works with all shells (that accept the -i
option to make an interactive shell). You could also add "$@"
after the option to relay any other arguments, which might then make the shell usable as a general 'set environment and execute command' tool. You might want to omit the -i
if there are other arguments, leading to:
#!/bin/ksh
export TEREDO_WORMS=ukelele
exec $SHELL "${@-'-i'}"
The "${@-'-i'}"
bit means 'if the argument list contains at least one argument, use the original argument list; otherwise, substitute -i
for the non-existent arguments'.
Don't forget there is a workaround to get the readonly
fields set outside of any constructors using out
params.
A little messy but:
private readonly int _someNumber;
private readonly string _someText;
public MyClass(int someNumber) : this(data, null)
{ }
public MyClass(int someNumber, string someText)
{
Initialise(out _someNumber, someNumber, out _someText, someText);
}
private void Initialise(out int _someNumber, int someNumber, out string _someText, string someText)
{
//some logic
}
Further discussion here: http://www.adamjamesnaylor.com/2013/01/23/Setting-Readonly-Fields-From-Chained-Constructors.aspx
You can implement throwing exceptions on mysql query fail on your own. What you need is to write a wrapper for mysql_query function, e.g.:
// user defined. corresponding MySQL errno for duplicate key entry
const MYSQL_DUPLICATE_KEY_ENTRY = 1022;
// user defined MySQL exceptions
class MySQLException extends Exception {}
class MySQLDuplicateKeyException extends MySQLException {}
function my_mysql_query($query, $conn=false) {
$res = mysql_query($query, $conn);
if (!$res) {
$errno = mysql_errno($conn);
$error = mysql_error($conn);
switch ($errno) {
case MYSQL_DUPLICATE_KEY_ENTRY:
throw new MySQLDuplicateKeyException($error, $errno);
break;
default:
throw MySQLException($error, $errno);
break;
}
}
// ...
// doing something
// ...
if ($something_is_wrong) {
throw new Exception("Logic exception while performing query result processing");
}
}
try {
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'")
}
catch (MySQLDuplicateKeyException $e) {
// duplicate entry exception
$e->getMessage();
}
catch (MySQLException $e) {
// other mysql exception (not duplicate key entry)
$e->getMessage();
}
catch (Exception $e) {
// not a MySQL exception
$e->getMessage();
}
Add flutter_just_toast to your dependencies in your Pubspecs.yaml
dependencies:
flutter_just_toast: ^1.0.1
Next import package into your class:
import 'package:flutter_just_toast/flutter_just_toast.dart';
Implement Toast with message
Toast.show( message: "Your toast message",
duration: Delay.SHORT,
textColor: Colors.black);
Try this: http://jsfiddle.net/xA5B7/
var MyDate = new Date();
var MyDateString;
MyDate.setDate(MyDate.getDate() + 20);
MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
+ ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
+ MyDate.getFullYear();
EDIT:
To explain, .slice(-2)
gives us the last two characters of the string.
So no matter what, we can add "0"
to the day or month, and just ask for the last two since those are always the two we want.
So if the MyDate.getMonth()
returns 9
, it will be:
("0" + "9") // Giving us "09"
so adding .slice(-2)
on that gives us the last two characters which is:
("0" + "9").slice(-2)
"09"
But if MyDate.getMonth()
returns 10
, it will be:
("0" + "10") // Giving us "010"
so adding .slice(-2)
gives us the last two characters, or:
("0" + "10").slice(-2)
"10"
What others have posted about running the function repeatedly in a loop is correct.
For Linux (and BSD) you want to use clock_gettime().
#include <sys/time.h>
int main()
{
timespec ts;
// clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD
clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
}
For windows you want to use the QueryPerformanceCounter. And here is more on QPC
Apparently there is a known issue with QPC on some chipsets, so you may want to make sure you do not have those chipset. Additionally some dual core AMDs may also cause a problem. See the second post by sebbbi, where he states:
QueryPerformanceCounter() and QueryPerformanceFrequency() offer a bit better resolution, but have different issues. For example in Windows XP, all AMD Athlon X2 dual core CPUs return the PC of either of the cores "randomly" (the PC sometimes jumps a bit backwards), unless you specially install AMD dual core driver package to fix the issue. We haven't noticed any other dual+ core CPUs having similar issues (p4 dual, p4 ht, core2 dual, core2 quad, phenom quad).
EDIT 2013/07/16:
It looks like there is some controversy on the efficacy of QPC under certain circumstances as stated in http://msdn.microsoft.com/en-us/library/windows/desktop/ee417693(v=vs.85).aspx
...While QueryPerformanceCounter and QueryPerformanceFrequency typically adjust for multiple processors, bugs in the BIOS or drivers may result in these routines returning different values as the thread moves from one processor to another...
However this StackOverflow answer https://stackoverflow.com/a/4588605/34329 states that QPC should work fine on any MS OS after Win XP service pack 2.
This article shows that Windows 7 can determine if the processor(s) have an invariant TSC and falls back to an external timer if they don't. http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html Synchronizing across processors is still an issue.
Other fine reading related to timers:
See the comments for more details.
In the below mentioned link, ChromeDriver.exe for Windows 32 bit exist.
http://chromedriver.storage.googleapis.com/index.html?path=2.24/
It is working for me in Win7 64 bit.
- Create a Class
with public static final
fields.
- And then you can access these fields from any class using the Class_Name.Field_Name
.
- You can declare the class
as final
, so that the class
can't be extended(Inherited) and modify....
Assign a new Image
object to your PictureBox
's Image
property. To load an Image
from a file, you may use the Image.FromFile
method. In your particular case, assuming the current directory is one under bin
, this should load the image bin/Pics/image1.jpg
, for example:
pictureBox1.Image = Image.FromFile("../Pics/image1.jpg");
Additionally, if these images are static and to be used only as resources in your application, resources would be a much better fit than files.
async function FileToString (file) {
try {
let res = await file.raw.text();
console.log(res);
} catch (err) {
throw err;
}
}
I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.
I assume it was something to do with iostream manipulations in the constructor.
Here is the fix:
// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
cout << "Some text I was printing.." << endl;
};
// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
};
Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.
What happens when the string contains a duplicate character?
from my experience with index()
I saw that for duplicate you get back the same index.
For example:
s = 'abccde'
for c in s:
print('%s, %d' % (c, s.index(c)))
would return:
a, 0
b, 1
c, 2
c, 2
d, 4
In that case you can do something like that:
for i, character in enumerate(my_string):
# i is the position of the character in the string
To set volume to 0
AudioManager audioManager;
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
To set volume to full
AudioManager audioManager;
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);
the volume can be adjusted by changing the index value between 0 and 20
Yet another way to use Rscript for *Unix systems is Process Substitution.
Rscript <(zcat a.r)
# [1] "hello"
Which obviously does the same as the accepted answer, but this allows you to manipulate and run your file without saving it the power of the command line, e.g.:
Rscript <(sed s/hello/bye/ a.r)
# [1] "bye"
Similar to Rscript -e "Rcode"
it also allows to run without saving into a file. So it could be used in conjunction with scripts that generate R-code, e.g.:
Rscript <(echo "head(iris,2)")
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
As mentioned by @jerry you can add services with the below command.
update-rc.d <service> defaults
update-rc.d <service> start 20 3 4 5
update-rc.d -f <service> remove
To validate them check the above commands you can check /etc/rc*.d/ directory where service start with "k" means it will not execute during the boot and service start with "S" will start during the boot.
# for runlevel symlinks:
ls /etc/rc*.d/
In the below screenshot you can see apache2 starting in runlevel2(S02apache2) and stopping in runlevel1(K01apache2)
You can also check the service status with the below command where "+" means service is in running state "-" is in stopped.
service --status-all
OR
install sysv-rc-conf utility.
apt-get install sysv-rc-conf
example
sysv-rc-conf --level 2345 apach22 on
man sysv-rc-conf
version 4.7.1 was slightly different : for import:
import org.antlr.v4.runtime.*;
for the main segment - note the CharStreams:
CharStream in = CharStreams.fromString("12*(5-6)");
ExpLexer lexer = new ExpLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExpParser parser = new ExpParser(tokens);
I usually do not use any href and change the aspect with css, making them seems link. Thus you do not have to worry about link effect at all, except for the event handler of your application
a {
text-recoration: underline;
cursor: pointer;
}
In order to convert string to char
String str = "abcd";
char arr [] = new char[len]; // len is the length of the array
arr = str.toCharArray();
It's because command substitution is performed in a subshell, so while the subshell inherits the variables, changes to them are lost when the subshell ends.
Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment
If your SSH proxy connection is going to be used often, you don't have to pass them as parameters each time. you can add the following lines to ~/.ssh/config
Host foobar.example.com
ProxyCommand nc -X connect -x proxyhost:proxyport %h %p
ServerAliveInterval 10
then to connect use
ssh foobar.example.com
Source:
http://www.perkin.org.uk/posts/ssh-via-http-proxy-in-osx.html
This is it guys! FIXED!
Wait and see: https://bugzilla.mozilla.org/show_bug.cgi?id=649849
or workaround
For those wondering:
https://bugzilla.mozilla.org/show_bug.cgi?id=649849#c59
First, because the bug has a lot of hostile spam in it, it creates a hostile workplace for anyone who gets assigned to this.
Secondly, the person who has the ability to do this (which includes rewriting ) has been allocated to another project (b2g) for the time being and wont have time until that project get nearer to completion.
Third, even when that person has the time again, there is no guarantee that this will be a priority because, despite webkit having this, it breaks the spec for how is supposed to work (This is what I was told, I do not personally know the spec)
Now see https://wiki.mozilla.org/B2G/Schedule_Roadmap ;)
The page no longer exists and the bug hasn't be fixed but an acceptable workaround came from João Cunha, you guys can thank him for now!
Terminal type:
Last login: Thu Dec 20 08:28:43 on console
~ ? sudo spctl --master-disable
Password:
~ ? spctl --status
assessments disabled
~ ?
System Preferences->Security & Privacy
I haven’t actually done anything with font-face
, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.
The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.
Does Firefox download the font when you actually use it in a font
declaration? (e.g. h1 { font: 'DejaVu Serif';
)?
The port for the Vue-cli webpack template is found in your app root's myApp/config/index.js
.
All you have to do is modify the port
value inside the dev
block:
dev: {
proxyTable: {},
env: require('./dev.env'),
port: 4545,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
cssSourceMap: false
}
Now you can access your app with localhost:4545
also if you have .env
file better to set it from there
You can wrap and unwrap exceptions this way.
class A {
void foo() throws Exception {
throw new Exception();
}
};
interface Task {
void run() throws Exception;
}
static class TaskException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TaskException(Exception e) {
super(e);
}
}
void bar() throws Exception {
Stream<A> as = Stream.generate(()->new A());
try {
as.forEach(a -> wrapException(() -> a.foo())); // or a::foo instead of () -> a.foo()
} catch (TaskException e) {
throw (Exception)e.getCause();
}
}
static void wrapException(Task task) {
try {
task.run();
} catch (Exception e) {
throw new TaskException(e);
}
}
Is this what you are looking for?
https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant
types is optional
You can use the index of the array element to remove it from the array, the next time you use the $list
variable, you will see that the array is changed.
Try something like this
foreach($list as $itemIndex => &$item) {
if($item['status'] === false) {
unset($list[$itemIndex]);
}
}
Try:
tr -s ' ' <text.txt | cut -d ' ' -f4
From the tr
man page:
-s, --squeeze-repeats replace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that character
I ran the same code. There are two things to note here. 1. Give the entire path of the .xml files. 2. Give a key press event instruction at the end.
Add this block of code at the end and run your file, worked for me:
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('messigray.png',img)
cv2.destroyAllWindows()
For example, my code looked like
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_eye.xml')
img = cv2.imread('lena.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
#faces = face_cascade.detectMultiScale(gray)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('messigray.png',img)
cv2.destroyAllWindows()
My output looked like this:
while || true
is preferred one, but you can also do
var=$(echo $(exit 1)) # it shouldn't fail
I'm assuming cross-domain iFrame since presumably the risk would be lower if you controlled it yourself.
There is another way for gradle:
compileJava {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
EDIT: Unfortunately I have to correct myself.
Refer below https://stackoverflow.com/a/17935666/2488942 for a link to the w3 specs which include an example (unlike the ones I looked at earlier on).
But then.... Here is a nice article about it thanks to @Fez.
My original response was:
The way the w3 specs are structured:
4.3.4 Sections
4.3.4.1 The body element
4.3.4.2 The section element
4.3.4.3 The nav element
4.3.4.4 The article element
....
suggests to me that section
is higher level than article
. As mentioned in this answer section
groups thematically related content. Content within an article is in my opinion thematically related anyway, hence this, to me at least, then also suggests that section
groups at a higher level compared to article
.
I think it's meant to be used like this:
section: Chapter 1
nav: Ch. 1.1
Ch. 1.2
article: Ch. 1.1
some insightful text
article: Ch. 1.2
related to 1.1 but different topic
or for a news website:
section: News
article: This happened today
article: this happened in England
section: Sports
article: England - Ukraine 0:0
article: Italy books tickets to Brazil 2014
Lazy man can use this lib, Just import inside your project and
ImageView mImageView;
PhotoViewAttacher mAttacher;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Any implementation of ImageView can be used!
mImageView = (ImageView) findViewById(R.id.iv_photo);
// Set the Drawable displayed
Drawable bitmap = getResources().getDrawable(R.drawable.wallpaper);
mImageView.setImageDrawable(bitmap);
// Attach a PhotoViewAttacher, which takes care of all of the zooming functionality.
mAttacher = new PhotoViewAttacher(mImageView);
}
// If you later call mImageView.setImageDrawable/setImageBitmap/setImageResource/etc then you just need to call
mAttacher.update();
Based on Amith Koujalgi's answer, here's a simple module you can use for logging -
transcript.py:
"""
Transcript - direct print output to a file, in addition to terminal.
Usage:
import transcript
transcript.start('logfile.log')
print("inside file")
transcript.stop()
print("outside file")
"""
import sys
class Transcript(object):
def __init__(self, filename):
self.terminal = sys.stdout
self.logfile = open(filename, "a")
def write(self, message):
self.terminal.write(message)
self.logfile.write(message)
def flush(self):
# this flush method is needed for python 3 compatibility.
# this handles the flush command by doing nothing.
# you might want to specify some extra behavior here.
pass
def start(filename):
"""Start transcript, appending print output to given filename"""
sys.stdout = Transcript(filename)
def stop():
"""Stop transcript and return print functionality to normal"""
sys.stdout.logfile.close()
sys.stdout = sys.stdout.terminal
If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:
if ('withCredentials' in xhr) {
xhr.withCredentials = true;
}
After I removed these three lines, the app worked fine, as expected.
Hope it helps!
I'm using this:
$.fn.ifExists = function(fn) {
if (this.length) {
$(fn(this));
}
};
$("#element").ifExists(
function($this){
$this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});
}
);
Execute the chain only if a jQuery element exist - http://jsfiddle.net/andres_314/vbNM3/2/
Yes, Eclipse can be a pain, as almost any IDE can. Please remain factual, however.
Switching to a new workspace should help you. Eclipse has almost no settings that are stored outside your workspace.
Its a new operator for combined comparison. Similar to strcmp()
or version_compare() in behavior, but it can be used on all generic PHP values with the same semantics as <
, <=
, ==
, >=
, >
. It returns 0
if both operands are equal, 1
if the left is greater, and -1
if the right is greater. It uses exactly the same comparison rules as used by our existing comparison operators: <
, <=
, ==
, >=
and >
.
on OpenSUSE 13.1/13.2 its: /usr/lib64/jvm/java-1.6.0-openjdk-(version-number)
version-number can be 1.7.x 1.8.x etc. check software manager witch version you have installed...
André
If you need fractional number, then this is the answer for you:
android:inputType="numberDecimal"
I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar
import net.sf.json.JSONObject;
...
public void send()
{
//put attributes
Map m = New HashMap();
m.put("send_to","[email protected]");
m.put("email_subject","this is a test email");
m.put("email_content","test email content");
//generate JSON Object
JSONObject json = JSONObject.fromObject(content);
String message = json.toString();
...
}
public void receive(String jsonMessage)
{
//parse attributes
JSONObject json = JSONObject.fromObject(jsonMessage);
String to = (String) json.get("send_to");
String title = (String) json.get("email_subject");
String content = (String) json.get("email_content");
...
}
More samples here http://json-lib.sourceforge.net/usage.html
Exact same thing, just omit the -c
option. Apache's docs on it here.
htpasswd /etc/apache2/.htpasswd newuser
Also, htpasswd
typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).
The long boring solution, which is not involved with CLI, you can manually navigate to:
your local repo folder ? .git folder (hidden) ? config file
then choose your text editor to open it and look for url located under the [remote "origin"] section.
You could create a git repo and setup a link to the node git repo as a dependency. Then any user who clones the repo could also install node.
#git submodule [--quiet] add [-b branch] [-f|--force]
git submodule add /var/Node-repo.git common
You could easily package a script up to automatically clone the git repo you have hosted somewhere and "install" from one that one script file.
#!/bin/sh
#clone git repo
git clone your-repo.git
this will help all of you to find your own correct details use
npm ls dist-tag
this will then show the correct info so you don't guess the version file location etc
enjoy :)
It looks much like a list of Django ORM model instances.
Why not sort them on query like this:
ut = Tag.objects.order_by('-count')
You can get value of id,name or value in this way. class name my_class
var id_value = $('.my_class').$(this).attr('id'); //get id value
var name_value = $('.my_class').$(this).attr('name'); //get name value
var value = $('.my_class').$(this).attr('value'); //get value any input or tag
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
My problem was similar. I got a payload
POST request when a user clicked a button
from my slackbot. The Content-Type
was application/x-www-form-urlencoded
. I used Flask, Python3.
I tried this solution and it didn't work
@app.route('/process_data', methods=['POST'])
def process_data():
req_data = request.get_json(force=True)
language = req_data['language']
return 'The language value is: {}'.format(language)
My solution 1 was:
from urllib.parse import parse_qs
# Some code
@ app.route('/slack/request_handler', methods=['POST'])
def request_handler():
# request.get_data() returned a bytestring
# parse_qs() returned a dict from a bytestring. This dict has 1 pair
# I tried payload_dict.keys() to see what keys in the dict and it had one key only
payload_dict = parse_qs(request.get_data())
# Get the value of the key from payload_dict
# Value of the key from payload_dict is an array, length = 1
payload_dict_value_arr = payload_dict[b'payload']
# Get data from the index[0] of the array payload_dict_value_arr
data = payload_dict_value_arr[0]
# convert a string (representation of a Dict)) to a Dict
# Note that if you have single quotes as a part of your keys or values this will
# fail due to improper character replacement.
# This solution is only recommended if you have a strong aversion
# to the eval solution.
datajson = json.loads(data)
# get value of key "channel"
channel = datajson["channel"]
print(channel) {'id': 'D01ACC2E8S3', 'name': 'directmessage'}
My solution 2, a bit shorter:
@ app.route('/slack/request_handler', methods=['POST'])
def request_handler():
payload = request.form # return an ImmutableMultiDict with 1 pair
a1 = payload['payload'] # get value of key 'payload'
# Note that if you have single quotes as a part of your keys or values this will
# fail due to improper character replacement.
# convert a string (representation of a Dict)) to a Dict
a2 = json.loads(a1)
# get value of key "channel"
channel = a2["channel"]
print(channel) # {'id': 'D01ACC2E8S3', 'name': 'directmessage'}
mikyra's answer is good.The fact just like what he said.
[jason@rh5 test]$ stat test.txt
File: `test.txt'
Size: 0 Blocks: 8 IO Block: 4096 regular empty file
Device: 802h/2050d Inode: 588720 Links: 1
Access: (0664/-rw-rw-r--) Uid: ( 500/ jason) Gid: ( 500/ jason)
Access: 2013-03-14 01:58:12.000000000 -0700
Modify: 2013-03-14 01:58:12.000000000 -0700
Change: 2013-03-14 01:58:12.000000000 -0700
if you want to verify wich file was created first,you can structure your file name by appending system date when you create a series of files.
You can check the android VLC it can stream and play video, if you want to indagate more, you can check their GIT to analyze what their do. Good luck!
The simplest possible solution if you know the value
document.querySelector('option[value=" + value +"]').selected = true
I do it like this:
$(window).bind('unload', function () {
if(event.clientY < 0) {
alert('Thank you for using this app.');
endSession(); // here you can do what you want ...
}
});
window.onbeforeunload = function () {
$(window).unbind('unload');
//If a string is returned, you automatically ask the
//user if he wants to logout or not...
//return ''; //'beforeunload event';
if (event.clientY < 0) {
alert('Thank you for using this service.');
endSession();
}
}
I had a background image, not big in size, but with weird dimensions - therefore the stretching and bad performance. I made a method with parameters Context, a View and a drawable ID(int) that will match the device screen size. Use this in e.g a Fragments onCreateView to set the background.
public void setBackground(Context context, View view, int drawableId){
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),drawableId);
bitmap = Bitmap.createScaledBitmap(bitmap, Resources.getSystem().
getDisplayMetrics().widthPixels,
Resources.getSystem().getDisplayMetrics().heightPixels,
true);
BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(),
bitmap);
view.setBackground(bitmapDrawable);
}
I've used HttpClient in .NET 4.0 applications on numerous occasions. If you are familiar with NuGet, you can do an Install-Package Microsoft.Net.Http to add it to your project. See the link below for further details.
Use DateTime.ToString
with the specified format MM.dd.yyyy
:
this.TextBox3.Text = DateTime.Now.ToString("MM.dd.yyyy");
Here, MM
means the month from 01 to 12, dd
means the day from 01 to 31 and yyyy
means the year as a four-digit number.
The currently added directory is already committed in the repository. So delete the directory in the repository and commit the same directory again.
I've used ng-change:
Date.prototype.addDays = function(days) {_x000D_
var dat = new Date(this.valueOf());_x000D_
dat.setDate(dat.getDate() + days);_x000D_
return dat;_x000D_
}_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
_x000D_
app.controller('DateController', ['$rootScope', '$scope',_x000D_
function($rootScope, $scope) {_x000D_
function init() {_x000D_
$scope.startDate = new Date();_x000D_
$scope.endDate = $scope.startDate.addDays(14);_x000D_
}_x000D_
_x000D_
_x000D_
function load() {_x000D_
alert($scope.startDate);_x000D_
alert($scope.endDate);_x000D_
}_x000D_
_x000D_
init();_x000D_
// public methods_x000D_
$scope.load = load;_x000D_
$scope.setStart = function(date) {_x000D_
$scope.startDate = date;_x000D_
};_x000D_
$scope.setEnd = function(date) {_x000D_
$scope.endDate = date;_x000D_
};_x000D_
_x000D_
}_x000D_
]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div data-ng-controller="DateController">_x000D_
<label class="item-input"> <span class="input-label">Start</span>_x000D_
<input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<label class="item-input"> <span class="input-label">End</span>_x000D_
<input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<button button="button" ng-disabled="planningForm.$invalid" ng-click="load()" class="button button-positive">_x000D_
Run_x000D_
</button>_x000D_
</div <label class="item-input"> <span class="input-label">Start</span>_x000D_
<input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<label class="item-input"> <span class="input-label">End</span>_x000D_
<input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
</label>
_x000D_
include() needs a full file path, relative to the file system's root directory.
This should work:
include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");
How I account for my site being behind an Amazon AWS Elastic Load Balancer (ELB):
public class GetPublicIp {
/// <summary>
/// account for possbility of ELB sheilding the public IP address
/// </summary>
/// <returns></returns>
public static string Execute() {
try {
Console.WriteLine(string.Join("|", new List<object> {
HttpContext.Current.Request.UserHostAddress,
HttpContext.Current.Request.Headers["X-Forwarded-For"],
HttpContext.Current.Request.Headers["REMOTE_ADDR"]
})
);
var ip = HttpContext.Current.Request.UserHostAddress;
if (HttpContext.Current.Request.Headers["X-Forwarded-For"] != null) {
ip = HttpContext.Current.Request.Headers["X-Forwarded-For"];
Console.WriteLine(ip + "|X-Forwarded-For");
}
else if (HttpContext.Current.Request.Headers["REMOTE_ADDR"] != null) {
ip = HttpContext.Current.Request.Headers["REMOTE_ADDR"];
Console.WriteLine(ip + "|REMOTE_ADDR");
}
return ip;
}
catch (Exception ex) {
Console.Error.WriteLine(ex.Message);
}
return null;
}
}
If you want user readable data but still detailed, you can use platform.platform()
>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'
platform
also has some other useful methods:
>>> platform.system()
'Windows'
>>> platform.release()
'XP'
>>> platform.version()
'5.1.2600'
Here's a few different possible calls you can make to identify where you are
import platform
import sys
def linux_distribution():
try:
return platform.linux_distribution()
except:
return "N/A"
print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))
The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version
e.g. Solaris on sparc gave:
Python version: ['2.6.4 (r264:75706, Aug 4 2010, 16:53:32) [C]']
dist: ('', '', '')
linux_distribution: ('', '', '')
system: SunOS
machine: sun4u
platform: SunOS-5.9-sun4u-sparc-32bit-ELF
uname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc')
version: Generic_122300-60
mac_ver: ('', ('', '', ''), '')
Why not consider creating your data class(es) as just a subclassed XmlDocument, then you get all of that for free. You don't need to serialize or create any off-doc nodes at all, and you get structure you want.
If you want to make it more sophisticated, write a base class that is a subclass of XmlDocument, then give it basic accessors, and you're set.
Here's a generic type I put together for a project...
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
namespace FWFWLib {
public abstract class ContainerDoc : XmlDocument {
protected XmlElement root = null;
protected const string XPATH_BASE = "/$DATA_TYPE$";
protected const string XPATH_SINGLE_FIELD = "/$DATA_TYPE$/$FIELD_NAME$";
protected const string DOC_DATE_FORMAT = "yyyyMMdd";
protected const string DOC_TIME_FORMAT = "HHmmssfff";
protected const string DOC_DATE_TIME_FORMAT = DOC_DATE_FORMAT + DOC_TIME_FORMAT;
protected readonly string datatypeName = "containerDoc";
protected readonly string execid = System.Guid.NewGuid().ToString().Replace( "-", "" );
#region startup and teardown
public ContainerDoc( string execid, string datatypeName ) {
root = this.DocumentElement;
this.datatypeName = datatypeName;
this.execid = execid;
if( null == datatypeName || "" == datatypeName.Trim() ) {
throw new InvalidDataException( "Data type name can not be blank" );
}
Init();
}
public ContainerDoc( string datatypeName ) {
root = this.DocumentElement;
this.datatypeName = datatypeName;
if( null == datatypeName || "" == datatypeName.Trim() ) {
throw new InvalidDataException( "Data type name can not be blank" );
}
Init();
}
private ContainerDoc() { /*...*/ }
protected virtual void Init() {
string basexpath = XPATH_BASE.Replace( "$DATA_TYPE$", datatypeName );
root = (XmlElement)this.SelectSingleNode( basexpath );
if( null == root ) {
root = this.CreateElement( datatypeName );
this.AppendChild( root );
}
SetFieldValue( "createdate", DateTime.Now.ToString( DOC_DATE_FORMAT ) );
SetFieldValue( "createtime", DateTime.Now.ToString( DOC_TIME_FORMAT ) );
}
#endregion
#region setting/getting data fields
public virtual void SetFieldValue( string fieldname, object val ) {
if( null == fieldname || "" == fieldname.Trim() ) {
return;
}
fieldname = fieldname.Replace( " ", "_" ).ToLower();
string xpath = XPATH_SINGLE_FIELD.Replace( "$FIELD_NAME$", fieldname ).Replace( "$DATA_TYPE$", datatypeName );
XmlNode node = this.SelectSingleNode( xpath );
if( null != node ) {
if( null != val ) {
node.InnerText = val.ToString();
}
} else {
node = this.CreateElement( fieldname );
if( null != val ) {
node.InnerText = val.ToString();
}
root.AppendChild( node );
}
}
public virtual string FieldValue( string fieldname ) {
if( null == fieldname ) {
fieldname = "";
}
fieldname = fieldname.ToLower().Trim();
string rtn = "";
XmlNode node = this.SelectSingleNode( XPATH_SINGLE_FIELD.Replace( "$FIELD_NAME$", fieldname ).Replace( "$DATA_TYPE$", datatypeName ) );
if( null != node ) {
rtn = node.InnerText;
}
return rtn.Trim();
}
public virtual string ToXml() {
return this.OuterXml;
}
public override string ToString() {
return ToXml();
}
#endregion
#region io
public void WriteTo( string filename ) {
TextWriter tw = new StreamWriter( filename );
tw.WriteLine( this.OuterXml );
tw.Close();
tw.Dispose();
}
public void WriteTo( Stream strm ) {
TextWriter tw = new StreamWriter( strm );
tw.WriteLine( this.OuterXml );
tw.Close();
tw.Dispose();
}
public void WriteTo( TextWriter writer ) {
writer.WriteLine( this.OuterXml );
}
#endregion
}
}
There's a property spring.resources.staticLocations
that can be set in the application.properties
. Note that this will override the default locations. See org.springframework.boot.autoconfigure.web.ResourceProperties
.
No, there isn't.
JSON can be written into local storage using the JSON.stringify to serialize a JS object. You cannot write to a JSON file using only JS. Only cookies or local storage
var obj = {"nissan": "sentra", "color": "green"};
localStorage.setItem('myStorage', JSON.stringify(obj));
And to retrieve the object later
var obj = JSON.parse(localStorage.getItem('myStorage'));
My code works well using data-dismiss.
<li class="step1">
<a href="#" class="button-popup" data-dismiss="modal" data-toggle="modal" data-target="#lightbox1">
<p class="text-label">Step 1</p>
<p class="text-text">Plan your Regime</p>
</a>
</li>
<li class="step2">
<a href="#" class="button-popup" data-dismiss="modal" data-toggle="modal" data-target="#lightbox2">
<p class="text-label">Step 2</p>
<p class="text-text">Plan your menu</p>
</a>
</li>
<li class="step3 active">
<a href="#" class="button-popup" data-toggle="modal" data-dismiss="modal" data-target="#lightbox3">
<p class="text-label">Step 3</p>
<p class="text-text">This Step is Undone.</p>
</a>
</li>
Plain and simple, to fetch the submodules:
git submodule update --init --recursive
And now proceed updating them to the latest master branch (for example):
git submodule foreach git pull origin master
Another way to assign a row number in a query is to use the DCount
function.
SELECT *, DCount("[ID]","[mytable]","[ID]<=" & [ID]) AS row_id
FROM [mytable]
WHERE row_id=15
A dialect is a form of the language that is spoken by a particular group of people.
Here, in context of hibernate framework, When hibernate wants to talk(using queries) with the database it uses dialects.
The SQL dialect's are derived from the Structured Query Language which uses human-readable expressions to define query statements.
A hibernate dialect gives information to the framework of how to convert hibernate queries(HQL) into native SQL queries.
The dialect of hibernate can be configured using below property:
hibernate.dialect
Here, is a complete list of hibernate dialects.
Note: The dialect property of hibernate is not mandatory.