Json.NET does this...
string json = @"{""key1"":""value1"",""key2"":""value2""}";
var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
More examples: Serializing Collections with Json.NET
Lots of hate for the Convert class here... Just to balance a little bit, there is one advantage for Convert - if you are handed an object,
Convert.ToDouble(o);
can just return the value easily if o is already a Double (or an int or anything readily castable).
Using Double.Parse or Double.TryParse is great if you already have it in a string, but
Double.Parse(o.ToString());
has to go make the string to be parsed first and depending on your input that could be more expensive.
A comment is produced using the REM command which is short for "Remark".
REM Comment here...
Clearly! We can make a function to return a CSS class name with following fully example.
CSS
<style>
.Red {
color: Red;
}
.Yellow {
color: Yellow;
}
.Blue {
color: Blue;
}
.Green {
color: Green;
}
.Gray {
color: Gray;
}
.b{
font-weight: bold;
}
</style>
JS
<script>
angular.module('myapp', [])
.controller('ExampleController', ['$scope', function ($scope) {
$scope.MyColors = ['It is Red', 'It is Yellow', 'It is Blue', 'It is Green', 'It is Gray'];
$scope.getClass = function (strValue) {
if (strValue == ("It is Red"))
return "Red";
else if (strValue == ("It is Yellow"))
return "Yellow";
else if (strValue == ("It is Blue"))
return "Blue";
else if (strValue == ("It is Green"))
return "Green";
else if (strValue == ("It is Gray"))
return "Gray";
}
}]);
</script>
And then
<body ng-app="myapp" ng-controller="ExampleController">
<h2>AngularJS ng-class if example</h2>
<ul >
<li ng-repeat="icolor in MyColors" >
<p ng-class="[getClass(icolor), 'b']">{{icolor}}</p>
</li>
</ul>
<hr/>
<p>Other way using : ng-class="{'class1' : expression1, 'class2' : expression2,'class3':expression2,...}"</p>
<ul>
<li ng-repeat="icolor in MyColors">
<p ng-class="{'Red':icolor=='It is Red','Yellow':icolor=='It is Yellow','Blue':icolor=='It is Blue','Green':icolor=='It is Green','Gray':icolor=='It is Gray'}" class="b">{{icolor}}</p>
</li>
</ul>
You can refer to full code page at ng-class if example
You can create a new MongoDB ObjectId
like this using mongoose:
var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();
I also had this error I took this part of code from .csproj file:
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
If you used the Visual Studio 2012 ASP.NET Web Forms Application template then you would have gotten that reference. I'm assuming it's the one you would get via Nuget instead of the framework System.Data.Entity reference.
The VS equivalent of a makefile is a "Solution" (over-simplified, I know).
Its possible you don't need to know depending on what you are doing with it.
String myString = object.toString();
or if object can be null
String myString = String.valueOf(object);
Unusual filenames (such as a file containing the valid \n
character can wreak havoc with this kind of parsing. Here's a way to do it in Perl:
perl -le '@sorted = map {$_->[0]}
sort {$a->[1] <=> $b->[1]}
map {[$_, -M $_]}
@ARGV;
print $sorted[0]
' b2*
That's a Schwartzian transform used there.
Or You can use
grep -n . file1 |tail -LineNumberToStartWith|grep regEx
This will take care of numbering the lines in the file
grep -n . file1
This will print the last-LineNumberToStartWith
tail -LineNumberToStartWith
And finally it will grep your desired lines(which will include line number as in orignal file)
grep regEX
@CodeReaper, @BennyHill: It works as expected.
However, I wonder the time complexity for having millions of rows in the table? Apparently, it took about 5ms
to execute for having 5k records on a correctly indexed table.
My Query:
SET status = '1'
WHERE id IN (
SELECT id
FROM (
SELECT c2.id FROM clusters as c2
WHERE c2.assign_to_user_id IS NOT NULL
AND c2.id NOT IN (
SELECT c1.id FROM clusters AS c1
LEFT JOIN cluster_flags as cf on c1.last_flag_id = cf.id
LEFT JOIN flag_types as ft on ft.id = cf.flag_type_id
WHERE ft.slug = 'closed'
)
) x)```
Or is there something we can improve on my query above?
You should not delete the data in box by pressing "delete", i think thats the problem , because excel will still detected the box as "" <- still have value, u should delete by right click the box and click delete.
if you want to start application with cmd use this code:
string YourApplicationPath = "C:\\Program Files\\App\\MyApp.exe"
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.FileName = "cmd.exe";
processInfo.WorkingDirectory = Path.GetDirectoryName(YourApplicationPath);
processInfo.Arguments = "/c START " + Path.GetFileName(YourApplicationPath);
Process.Start(processInfo);
The functionality is already present in atom via the Symbols View package you don't need to install anything.
The command you are searching for is symbols-view:go-to-declaration (Jump to the symbol under the cursor) which is bound by default to cmd-alt-down on macOS and ctrl-alt-down on Linux.
just note that it will work only if you will have generated tags for your project, either via this package or via ctags (exuberant or not)
I used Rafid's suggestion of using AJAX.
This worked for me:
var url = "http://www.example.com/file.json";
var jsonFile = new XMLHttpRequest();
jsonFile.open("GET",url,true);
jsonFile.send();
jsonFile.onreadystatechange = function() {
if (jsonFile.readyState== 4 && jsonFile.status == 200) {
document.getElementById("id-of-element").innerHTML = jsonFile.responseText;
}
}
I basically(almost literally) copied this code from http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get2 so credit to them for everything.
I dont have much knowledge of how this works but you don't have to know how your brakes work to use them ;)
Hope this helps!
@POST
@Path ("Employee")
@Consumes("application/json")
@Produces("application/json")
public JSONObject postEmployee(JSONObject jsonObject)throws Exception{
return jsonObject;
}
All you have to do is chant the magick incantation:
npm test -- SomeTestFileToRun
The standalone --
is *nix magic for marking the end of options, meaning (for NPM) that everything after that is passed to the command being run, in this case jest
. As an aside, you can display Jest usage notes by saying
npm test -- --help
Anyhow, chanting
npm test -- Foo
runs the tests in the named file (FooBar.js
). You should note, though, that:
Jest treats the name as case-sensitive, so if you're using a case-insensitive, but case-preserving file system (like Windows NTFS), you might encounter what appears to be oddness going on.
Jest appears to treat the specification as a prefix.
So the above incantation will
FooBar.js
, Foo.js
and FooZilla.js
foo.js
If your problem is like the following while using Google Chrome:
[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]
Then create a batch file by following these steps:
Open notepad in Desktop.
start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit
This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.
Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.
In the detached window (Tool Options), the name of the view (Paintbrush) is a grab-bar.
Put your cursor over the grab-bar, click and drag it to the dock area in the main window in order to reattach it to the main window.
Add the Picasso library in Dependency
dependencies {
...
implementation 'com.squareup.picasso:picasso:2.71828'
...
}
Sync The Project Create one imageview in Layout
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
Add the Internet permission in Manifest file
<uses-permission android:name="android.permission.INTERNET" />
//Initialize ImageView
ImageView imageView = (ImageView) findViewById(R.id.imageView);
//Loading image from below url into imageView
Picasso.get()
.load("YOUR IMAGE URL HERE")
.into(imageView);
Maybe you should try removing "new" keyword and see if works.
Because last time I got this error when I tried creating Typeface
something like this:
Typeface typeface = new Typeface().create("Arial",Typeface.BOLD);
To Change it permanently in ubuntu do the following
in the ubuntu command line
sudo nano /etc/mysql/my.cnf
Then add the following
[mysqld]
sql_mode=
len(os.sched_getaffinity(0))
is what you usually want
https://docs.python.org/3/library/os.html#os.sched_getaffinity
os.sched_getaffinity(0)
(added in Python 3) returns the set of CPUs available considering the sched_setaffinity
Linux system call, which limits which CPUs a process and its children can run on.
0
means to get the value for the current process. The function returns a set()
of allowed CPUs, thus the need for len()
.
multiprocessing.cpu_count()
and os.cpu_count()
on the other hand just returns the total number of physical CPUs.
The difference is especially important because certain cluster management systems such as Platform LSF limit job CPU usage with sched_getaffinity
.
Therefore, if you use multiprocessing.cpu_count()
, your script might try to use way more cores than it has available, which may lead to overload and timeouts.
We can see the difference concretely by restricting the affinity with the taskset
utility, which allows us to control the affinity of a process.
Minimal taskset
example
For example, if I restrict Python to just 1 core (core 0) in my 16 core system:
taskset -c 0 ./main.py
with the test script:
main.py
#!/usr/bin/env python3
import multiprocessing
import os
print(multiprocessing.cpu_count())
print(os.cpu_count())
print(len(os.sched_getaffinity(0)))
then the output is:
16
16
1
Vs nproc
nproc
does respect the affinity by default and:
taskset -c 0 nproc
outputs:
1
and man nproc
makes that quite explicit:
print the number of processing units available
Therefore, len(os.sched_getaffinity(0))
behaves like nproc
by default.
nproc
has the --all
flag for the less common case that you want to get the physical CPU count without considering taskset:
taskset -c 0 nproc --all
os.cpu_count
documentation
The documentation of os.cpu_count
also briefly mentions this https://docs.python.org/3.8/library/os.html#os.cpu_count
This number is not equivalent to the number of CPUs the current process can use. The number of usable CPUs can be obtained with
len(os.sched_getaffinity(0))
The same comment is also copied on the documentation of multiprocessing.cpu_count
: https://docs.python.org/3/library/multiprocessing.html#multiprocessing.cpu_count
From the 3.8 source under Lib/multiprocessing/context.py
we also see that multiprocessing.cpu_count
just forwards to os.cpu_count
, except that the multiprocessing
one throws an exception instead of returning None if os.cpu_count
fails:
def cpu_count(self):
'''Returns the number of CPUs in the system'''
num = os.cpu_count()
if num is None:
raise NotImplementedError('cannot determine number of cpus')
else:
return num
3.8 availability: systems with a native sched_getaffinity
function
The only downside of this os.sched_getaffinity
is that this appears to be UNIX only as of Python 3.8.
cpython 3.8 seems to just try to compile a small C hello world with a sched_setaffinity
function call during configuration time, and if not present HAVE_SCHED_SETAFFINITY
is not set and the function will likely be missing:
psutil.Process().cpu_affinity()
: third-party version with a Windows port
The third-party psutil
package (pip install psutil
) had been mentioned at: https://stackoverflow.com/a/14840102/895245 but not the cpu_affinity
function: https://psutil.readthedocs.io/en/latest/#psutil.Process.cpu_affinity
Usage:
import psutil
print(len(psutil.Process().cpu_affinity()))
This function does the same as the standard library os.sched_getaffinity
on Linux, but they have also implemented it for Windows by making a call to the GetProcessAffinityMask
Windows API function:
So in other words: those Windows users have to stop being lazy and send a patch to the upstream stdlib :-)
Tested in Ubuntu 16.04, Python 3.5.2.
Use an URL
instead of File
for any access that is not on your local computer.
URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner s = new Scanner(url.openStream());
Actually, URL is even more generally useful, also for local access (use a file:
URL), jar files, and about everything that one can retrieve somehow.
The way above interprets the file in your platforms default encoding. If you want to use the encoding indicated by the server instead, you have to use a URLConnection and parse it's content type, like indicated in the answers to this question.
About your Error, make sure your file compiles without any errors - you need to handle the exceptions. Click the red messages given by your IDE, it should show you a recommendation how to fix it. Do not start a program which does not compile (even if the IDE allows this).
Here with some sample exception-handling:
try {
URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner s = new Scanner(url.openStream());
// read from your scanner
}
catch(IOException ex) {
// there was some connection problem, or the file did not exist on the server,
// or your URL was not in the right format.
// think about what to do now, and put it here.
ex.printStackTrace(); // for now, simply output it.
}
Don't care if you are a moderator. I wrote my text towards my audience not as a technical writer
All you guys need to learn to navigate with tools that predate GPS. Something like a sextant, octant, backstaff or an astrolabe.
If you have receive the signal from 3 different locations then you only need to measure the signal strength and make a ratio from those locations. Simple triangle calculation where a2+b2=c2. The stronger the signal strength the closer the device is to the receiver.
val viewTreeObserver: ViewTreeObserver = videoView.viewTreeObserver;
if (viewTreeObserver.isAlive) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
//Remove Listener
videoView.viewTreeObserver.removeOnGlobalLayoutListener(this);
//View Dimentions
viewWidth = videoView.width;
viewHeight = videoView.height;
//View Location
val point = IntArray(2)
videoView.post {
videoView.getLocationOnScreen(point) // or getLocationInWindow(point)
viewPositionX = point[0]
viewPositionY = point[1]
}
}
});
}
Go to the Preferences menu command under menu Settings, and select Language Menu/Tab Settings, depending on your version. Earlier versions use Tab Settings. Later versions use Language. Click the Replace with space check box. Set the size to 4.
See documentation: http://docs.notepad-plus-plus.org/index.php/Built-in_Languages#Tab_settings
I tried a bunch of these ideas to get HTTPS working, but the key for me was adding the protocol mapping. Here's what my server config file looks like, this works for both HTTP and HTTPS client connections:
<system.serviceModel>
<protocolMapping>
<add scheme="https" binding="wsHttpBinding" bindingConfiguration="TransportSecurityBinding" />
</protocolMapping>
<services>
<service name="FeatureService" behaviorConfiguration="HttpsBehavior">
<endpoint address="soap" binding="wsHttpBinding" contract="MyServices.IFeature" bindingConfiguration="TransportSecurityBinding" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="HttpsBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="TransportSecurityBinding" maxReceivedMessageSize="2147483647">
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
If you want to be able to think it as a 2D array rather than being forced to think in term of a list of lists (much more natural in my opinion), you can do the following:
import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()
The result is a list (not a NumPy array), and you can overwrite the individual positions with numbers, strings, whatever.
using System.IO;
...
Directory.CreateDirectory(@"C:\MP_Upload");
Directory.CreateDirectory does exactly what you want: It creates the directory if it does not exist yet. There's no need to do an explicit check first.
Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing.
(This also means that all directories along the path are created if needed: CreateDirectory(@"C:\a\b\c\d")
suffices, even if C:\a
does not exist yet.)
Let me add a word of caution about your choice of directory, though: Creating a folder directly below the system partition root C:\
is frowned upon. Consider letting the user choose a folder or creating a folder in %APPDATA%
or %LOCALAPPDATA%
instead (use Environment.GetFolderPath for that). The MSDN page of the Environment.SpecialFolder enumeration contains a list of special operating system folders and their purposes.
The UUID stands for Universally Unique Identifier. UUID is an simple 128 bit digit which uniquely distributed across the world.
Bluetooth sends data over air and all nearby device can receive it. Let's suppose, sometimes you have to send some important files via Bluetooth and all near by devices can access it in range. So when you pair with the other devices, they simply share the UUID number and match before sharing the files. When you send any file then your device encrypt that file with appropriate device UUID and share over the network. Now all Bluetooth devices in the range can access the encrypt file but they required right UUID number. So Only right UUID devices have access to encrypt the file and others will reject cause of wrong UUID.
In short, you can use UUID as a secret password for sharing files between any two Bluetooth devices.
How to randomly select an item from a list?
Assume I have the following list:
foo = ['a', 'b', 'c', 'd', 'e']
What is the simplest way to retrieve an item at random from this list?
If you want close to truly random, then I suggest secrets.choice
from the standard library (New in Python 3.6.):
>>> from secrets import choice # Python 3 only
>>> choice(list('abcde'))
'c'
The above is equivalent to my former recommendation, using a SystemRandom
object from the random
module with the choice
method - available earlier in Python 2:
>>> import random # Python 2 compatible
>>> sr = random.SystemRandom()
>>> foo = list('abcde')
>>> foo
['a', 'b', 'c', 'd', 'e']
And now:
>>> sr.choice(foo)
'd'
>>> sr.choice(foo)
'e'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'b'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'c'
>>> sr.choice(foo)
'c'
If you want a deterministic pseudorandom selection, use the choice
function (which is actually a bound method on a Random
object):
>>> random.choice
<bound method Random.choice of <random.Random object at 0x800c1034>>
It seems random, but it's actually not, which we can see if we reseed it repeatedly:
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
This is not about whether random.choice is truly random or not. If you fix the seed, you will get the reproducible results -- and that's what seed is designed for. You can pass a seed to SystemRandom, too.
sr = random.SystemRandom(42)
Well, yes you can pass it a "seed" argument, but you'll see that the SystemRandom
object simply ignores it:
def seed(self, *args, **kwds):
"Stub method. Not used for a system random number generator."
return None
I was actually running into some strange errors with mp4's a while ago. What fixed it for me was re-encoding the video using known supported codecs (H.264 & MP3).
I actually used the VLC player to do so and it worked fine afterward. I converted using the mentioned codecs H.264/MP3. That solved it for me.
Maybe the problem is not in the format
but in the JavaScript
implementation of the play/ pause
methods. May I suggest visiting the following link where Google developer explains it in a good way?
Additionally, you could choose to use the newer webp
format, which Chrome supports out of the box, but be careful with other browsers. Check the support for it before implementation. Here's a link that describes the mentioned format.
On that note: I've created a small script
that easily converts all standard formats to webp
. You can easily configure it to fit your needs. Here's the Github repo of the same projects.
"C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn\Sqlservr.exe"
or if you feel brave, locate the alias in the registry and delete it there.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo\
This concise example demonstrates common way how to create custom tooltip in d3.
var w = 500;_x000D_
var h = 150;_x000D_
_x000D_
var dataset = [5, 10, 15, 20, 25];_x000D_
_x000D_
// firstly we create div element that we can use as_x000D_
// tooltip container, it have absolute position and_x000D_
// visibility: hidden by default_x000D_
_x000D_
var tooltip = d3.select("body")_x000D_
.append("div")_x000D_
.attr('class', 'tooltip');_x000D_
_x000D_
var svg = d3.select("body")_x000D_
.append("svg")_x000D_
.attr("width", w)_x000D_
.attr("height", h);_x000D_
_x000D_
// here we add some circles on the page_x000D_
_x000D_
var circles = svg.selectAll("circle")_x000D_
.data(dataset)_x000D_
.enter()_x000D_
.append("circle");_x000D_
_x000D_
circles.attr("cx", function(d, i) {_x000D_
return (i * 50) + 25;_x000D_
})_x000D_
.attr("cy", h / 2)_x000D_
.attr("r", function(d) {_x000D_
return d;_x000D_
})_x000D_
_x000D_
// we define "mouseover" handler, here we change tooltip_x000D_
// visibility to "visible" and add appropriate test_x000D_
_x000D_
.on("mouseover", function(d) {_x000D_
return tooltip.style("visibility", "visible").text('radius = ' + d);_x000D_
})_x000D_
_x000D_
// we move tooltip during of "mousemove"_x000D_
_x000D_
.on("mousemove", function() {_x000D_
return tooltip.style("top", (event.pageY - 30) + "px")_x000D_
.style("left", event.pageX + "px");_x000D_
})_x000D_
_x000D_
// we hide our tooltip on "mouseout"_x000D_
_x000D_
.on("mouseout", function() {_x000D_
return tooltip.style("visibility", "hidden");_x000D_
});
_x000D_
.tooltip {_x000D_
position: absolute;_x000D_
z-index: 10;_x000D_
visibility: hidden;_x000D_
background-color: lightblue;_x000D_
text-align: center;_x000D_
padding: 4px;_x000D_
border-radius: 4px;_x000D_
font-weight: bold;_x000D_
color: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
There are more than a couple of mistakes in the code.
Since you have not defined any default values for any of the function arguments, it is necessary to pass both arguments while calling the function --> hello(sys.argv[2], sys.argv[2])
import sys
def hello(a,b):
print ("hello and that's your sum:")
sum=float(a)+float(b)
print (sum)
if __name__ == "__main__":
hello(sys.argv[1], sys.argv[2])
Also, using "C:\Python27>hello 1 1" to run the code looks fine but you have to make sure that the file is in one of the directories that Python knows about (PATH env variable). So, please use the full path to validate the code. Something like:
C:\Python34>python C:\Users\pranayk\Desktop\hello.py 1 1
python setup.py install
You may need administrator privileges for step 5. What you do here thus depends on your operating system. For example in Ubuntu you would say sudo python setup.py install
EDIT- thanks to kwatford (see first comment)
To bypass the need for administrator privileges during step 5 above you may be able to make use of the --user flag. In this way you can install the package only for the current user.
The docs say:
Files will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE). Here are the values for UNIX, including Mac OS X:
More details can be found here: http://docs.python.org/2.7/install/index.html
Since you're using formatters for the rest of it, just use DecimalFormat:
import java.text.DecimalFormat;
DecimalFormat xFormat = new DecimalFormat("000")
System.out.print(xFormat.format(x + 1) + " ");
Alternative you could do whole job in whole line using printf:
System.out.printf("%03d %s %s %s \n", x + 1, // the payment number
formatter.format(monthlyInterest), // round our interest rate
formatter.format(principleAmt),
formatter.format(remainderAmt));
The most important thing, that all are missing here is... The launchMode of FirstActivity must be singleTop. If it is singleInstance, the onActivityResult in FragmentA will be called just after calling the startActivityForResult method. So, It will not wait for calling of the finish() method in SecondActivity.
So go through the following steps, It will definitely work as it worked for me too after a long research.
In AndroidManifest.xml file, make launchMode of FirstActivity.Java as singleTop.
<activity
android:name=".FirstActivity"
android:label="@string/title_activity_main"
android:launchMode="singleTop"
android:theme="@style/AppTheme.NoActionBar" />
In FirstActivity.java, override onActivityResult method. As this will call the onActivityResult of FragmentA.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
In FragmentA.Java, override onActivityResult method
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("FragmentA.java","onActivityResult called");
}
Call startActivityForResult(intent, HOMEWORK_POST_ACTIVITY);
from FragmentA.Java
Call finish();
method in SecondActivity.java
Hope this will work.
Worth mentioning: you should download the x64 version!
From the main download page (https://www.iis.net/downloads/microsoft/url-rewrite) click "additional downloads" (under the main download button) and download the x64 version (because for some reason - the default download version is x86)
The URLs are passed in the request: request.getRequestURL()
.
If you mean other sites that are linking to you? You want to capture the HTTP Referrer, which you can do by calling:
request.getHeader("referer");
>>> u'a?ä'.encode('ascii', 'ignore')
'a'
Decode the string you get back, using either the charset in the the appropriate meta
tag in the response or in the Content-Type
header, then encode.
The method encode(encoding, errors)
accepts custom handlers for errors. The default values, besides ignore
, are:
>>> u'a?ä'.encode('ascii', 'replace')
b'a??'
>>> u'a?ä'.encode('ascii', 'xmlcharrefreplace')
b'aあä'
>>> u'a?ä'.encode('ascii', 'backslashreplace')
b'a\\u3042\\xe4'
See https://docs.python.org/3/library/stdtypes.html#str.encode
you can do it by Dynamic Web Project –> RightClick –> Java EE Tools –> Generate Deployment Descriptor Stub.
Take a look at OAuth 2.0 playground.You will get an overview of the protocol.It is basically an environment(like any app) that shows you the steps involved in the protocol.
I just wasted my time on this and wanted to add an additional case where this error presents itself.
SQL Error (1292): Truncated incorrect DOUBLE value: 'N0003'
Test data
CREATE TABLE `table1 ` (
`value1` VARCHAR(50) NOT NULL
);
INSERT INTO table1 (value1) VALUES ('N0003');
CREATE TABLE `table2 ` (
`value2` VARCHAR(50) NOT NULL
);
INSERT INTO table2 (value2)
SELECT value1
FROM table1
WHERE 1
ORDER BY value1+0
The problem is ORDER BY value1+0
- type casting.
I know that it does not answer the question but this is the first result on Google for this error and it should have other examples where this error presents itself.
Try using Response.SetCookie()
, because Response.Cookies.Add()
can cause multiple cookies to be added, whereas SetCookie
will update an existing cookie.
Looks like you forgot the @ in variable declaration. Also I remember having problems with SET
in MySql a long time ago.
Try
DECLARE @FOO varchar(7);
DECLARE @oldFOO varchar(7);
SELECT @FOO = '138';
SELECT @oldFOO = CONCAT('0', @FOO);
update mypermits
set person = @FOO
where person = @oldFOO;
Convert the image to a byte[]
and store that in the database.
Add this column to your model:
public byte[] Content { get; set; }
Then convert your image to a byte array and store that like you would any other data:
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using(var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
public Image ByteArrayToImage(byte[] byteArrayIn)
{
using(var ms = new MemoryStream(byteArrayIn))
{
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
Source: Fastest way to convert Image to Byte array
var image = new ImageEntity()
{
Content = ImageToByteArray(image)
};
_context.Images.Add(image);
_context.SaveChanges();
When you want to get the image back, get the byte array from the database and use the ByteArrayToImage
and do what you wish with the Image
This stops working when the byte[]
gets to big. It will work for files under 100Mb
If you are generating XML files programatically, you may want to look at the XMLBeans library. Using a command line tool, XMLBeans will automatically generate and package up a set of Java objects based on an XSD. You can then use these objects to build an XML document based on this schema.
It has built-in support for schema validation, and can convert Java objects to an XML document and vice-versa.
Castor and JAXB are other Java libraries that serve a similar purpose to XMLBeans.
If you are on Linux, then start the 'mysqld' with strace
, for eg strace ./mysqld
.
Among all the other system calls, you will find something like:
stat64("/etc/my.cnf", 0xbfa3d7fc) = -1 ENOENT (No such file or directory)
stat64("/etc/mysql/my.cnf", {st_mode=S_IFREG|0644, st_size=4227, ...}) = 0
open("/etc/mysql/my.cnf", O_RDONLY|O_LARGEFILE) = 3
So, as you can see..it lists the .cnf files, that it attempts to use and finally uses.
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
do you work with a 3d tool such as maya? for maya you can look at http://www.inka3d.com
If you are you trying to attach a child view to the RelativeLayout? you can do by following
RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, item, true);
From ScottGu's blog:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
Also see this.
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.
Wikipedia
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
How about this?
Get-ADGroupMember 'Group name' | measure-object | select count
Get all the values from MySQL:
$post = array();
while($row = mysql_fetch_assoc($result))
{
$posts[] = $row;
}
Then, to get each value:
<?php
foreach ($posts as $row)
{
foreach ($row as $element)
{
echo $element."<br>";
}
}
?>
To echo the values. Or get each element from the $post variable
For those looking for a quick wget install on Mac, check out Quentin Stafford-Fraser's precompiled binary here, which has been around for over a decade:
https://statusq.org/archives/2008/07/30/1954/
MD5 for 2008 wget.zip: 24a35d499704eecedd09e0dd52175582
MD5 for 2005 wget.zip: c7b48ec3ff929d9bd28ddb87e1a76ffb
No make/install/port/brew/curl junk. Just download, install, and run. Works with Mac OS X 10.3-10.12+.
There are a lot of sources for selenium - here is good one for simple use Selenium, and here is a example snippet too Selenium Examples
You can find a lot of good sources to use selenium, it's not too hard to get it set up and start using it.
Now you can also use Doctrine ORM Transformations to convert entities to nested arrays of scalars and back
No, that's not quite right.
EAX is the full 32-bit value
AX is the lower 16-bits
AL is the lower 8 bits
AH is the bits 8 through 15 (zero-based)
So AX is composed of AH:AL halves, and is itself the low half of EAX. (The upper half of EAX isn't directly accessible as a 16-bit register; you can shift or rotate EAX if you want to get at it.)
For completeness, in addition to the above, which was based on a 32-bit CPU, 64-bit Intel/AMD CPUs have
RAX, which hold a 64-bit value, and where EAX is mapped to the lower 32 bits.
All of this also applies to EBX/RBX, ECX/RCX, and EDX/RDX. The other registers like EDI/RDI have a DI low 16-bit partial register, but no high-8 part, and the low-8 DIL is only accessible in 64-bit mode: Assembly registers in 64-bit architecture
Writing AL, AH, or AX merges into the full AX/EAX/RAX, leaving other bytes unmodified for historical reasons. (In 32 or 64-bit code, prefer a movzx eax, byte [mem]
or movzx eax, word [mem]
load if you don't specifically want this merging: Why doesn't GCC use partial registers?)
Writing EAX zero-extends into RAX. (Why do x86-64 instructions on 32-bit registers zero the upper part of the full 64-bit register?)
I've experienced a problem with length of None, which leads to Internal Server Error: TypeError: object of type 'NoneType' has no len()
My workaround is just displaying 0 if object is None and calculate length of other types, like list in my case:
{{'0' if linked_contacts == None else linked_contacts|length}}
htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.
From the Differences Between DTDs and Schema section of the Converting a DTD into a Schema article:
The critical difference between DTDs and XML Schema is that XML Schema utilize an XML-based syntax, whereas DTDs have a unique syntax held over from SGML DTDs. Although DTDs are often criticized because of this need to learn a new syntax, the syntax itself is quite terse. The opposite is true for XML Schema, which are verbose, but also make use of tags and XML so that authors of XML should find the syntax of XML Schema less intimidating.
The goal of DTDs was to retain a level of compatibility with SGML for applications that might want to convert SGML DTDs into XML DTDs. However, in keeping with one of the goals of XML, "terseness in XML markup is of minimal importance," there is no real concern with keeping the syntax brief.
[...]
So what are some of the other differences which might be especially important when we are converting a DTD? Let's take a look.
Typing
The most significant difference between DTDs and XML Schema is the capability to create and use datatypes in Schema in conjunction with element and attribute declarations. In fact, it's such an important difference that one half of the XML Schema Recommendation is devoted to datatyping and XML Schema. We cover datatypes in detail in Part III of this book, "XML Schema Datatypes."
[...]
Occurrence Constraints
Another area where DTDs and Schema differ significantly is with occurrence constraints. If you recall from our previous examples in Chapter 2, "Schema Structure" (or your own work with DTDs), there are three symbols that you can use to limit the number of occurrences of an element: *, + and ?.
[...]
Enumerations
So, let's say we had a element, and we wanted to be able to define a size attribute for the shirt, which allowed users to choose a size: small, medium, or large. Our DTD would look like this:
<!ELEMENT item (shirt)> <!ELEMENT shirt (#PCDATA)> <!ATTLIST shirt size_value (small | medium | large)>
[...]
But what if we wanted
size
to be an element? We can't do that with a DTD. DTDs do not provide for enumerations in an element's text content. However, because of datatypes with Schema, when we declared the enumeration in the preceding example, we actually created asimpleType
calledsize_values
which we can now use with an element:<xs:element name="size" type="size_value">
[...]
It's simple and follow the small Steps to proceed:
$cd project and execute $git init --bare
Let's say this project.git folder is present at your ip with address inside home_folder/workspace/project.git
, forex- ec2 - /home/ubuntu/workspace/project.git
Now in your local machine, $cd
into the project folder which you want to push to git execute the below commands:
git init .
git remote add origin [email protected]:/home/ubuntu/workspace/project.git
git add .
git commit -m "Initial commit"
Below is an optional command but found it has been suggested as i was working to setup the same thing
git config --global remote.origin.receivepack "git receive-pack"
git pull origin master
git push origin master
This should work fine and will push the local code to the remote git repository.
To check the remote fetch url, cd project_folder/.git
and cat config
, this will give the remote url being used for pull and push operations.
You can also use an alternative way, after creating the project.git
folder on git, clone the project and copy the entire content into that folder. Commit the changes and it should be the same way. While cloning make sure you have access or the key being is the secret key for the remote server being used for deployment.
First, let's clear up some terminology: "asynchronous" (async
) means that it may yield control back to the calling thread before it starts. In an async
method, those "yield" points are await
expressions.
This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".
To futher confuse the issue, async
is very different than "awaitable"; there are some async
methods whose return types are not awaitable, and many methods returning awaitable types that are not async
.
Enough about what they aren't; here's what they are:
async
keyword allows an asynchronous method (that is, it allows await
expressions). async
methods may return Task
, Task<T>
, or (if you must) void
.Task
and Task<T>
.So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run
:
private Task<int> DoWorkAsync() // No async because the method does not need await
{
return Task.Run(() =>
{
return 1 + 2;
});
}
(But this pattern is a poor approach; see below).
But if your question is "how do I create an async
method that can yield back to its caller instead of blocking", the answer is to declare the method async
and use await
for its "yielding" points:
private async Task<int> GetWebPageHtmlSizeAsync()
{
var client = new HttpClient();
var html = await client.GetAsync("http://www.example.com/");
return html.Length;
}
So, the basic pattern of things is to have async
code depend on "awaitables" in its await
expressions. These "awaitables" can be other async
methods or just regular methods returning awaitables. Regular methods returning Task
/Task<T>
can use Task.Run
to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T>
or one of its shortcuts (TaskFactory.FromAsync
, Task.FromResult
, etc). I don't recommend wrapping an entire method in Task.Run
; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run
:
private int DoWork()
{
return 1 + 2;
}
private void MoreSynchronousProcessing()
{
// Execute it directly (synchronously), since we are also a synchronous method.
var result = DoWork();
...
}
private async Task DoVariousThingsFromTheUIThreadAsync()
{
// I have a bunch of async work to do, and I am executed on the UI thread.
var result = await Task.Run(() => DoWork());
...
}
I have an async
/await
intro on my blog; at the end are some good followup resources. The MSDN docs for async
are unusually good, too.
I understand the original post is for Oracle 10 but this is for reference by anyone else who finds it via Google.
Under Oracle 12c, I found that that my registry$history is empty. This works instead:
select * from registry$sqlpatch;
Sometimes I use an attribute of a function for caching already computed values. You can also have a generic decorator that generalizes this approach. Be aware of concurrency issues and side effects of such functions!
You do not include a <scope>
tag in your dependency. If you add it, your dependency becomes something like:
<dependency>
<groupId>org.openrdf.sesame</groupId>
<artifactId>sesame-runtime</artifactId>
<version>2.7.2</version>
<scope> ... </scope>
</dependency>
The "scope" tag tells maven at which stage of the build your dependency is needed. Examples for the values to put inside are "test", "provided" or "runtime" (omit the quotes in your pom). I do not know your dependency so I cannot tell you what value to choose. Please consult the Maven documentation and the documentation of your dependency.
The answer which suggests something like taskkill /f /im java.exe
will probably work, but if you want to kill only one java process instead of all, I can suggest doing it with the help of window titles. Expample:
start "MyProgram" "C:/Program Files/Java/jre1.8.0_201/bin/java.exe" -jar MyProgram.jar
taskkill /F /FI "WINDOWTITLE eq MyProgram" /T
I have faced this type of error. to call a function from the razor.
public ActionResult EditorAjax(int id, int? jobId, string type = ""){}
solved that by changing the line
from
<a href="/ScreeningQuestion/EditorAjax/5&jobId=2&type=additional" />
to
<a href="/ScreeningQuestion/EditorAjax/?id=5&jobId=2&type=additional" />
where my route.config is
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new string[] { "RPMS.Controllers" } // Parameter defaults
);
So, simplejson.loads takes a json string and returns a data structure, which is why you are getting that type error there.
simplejson.dumps(data) comes back with
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'
Which is a json array, which is what you want, since you gave this a python array.
If you want to get an "object" type syntax you would instead do
>>> data2 = {'apple':'cat', 'banana':'dog', 'pear':'fish'}
>>> simplejson.dumps(data2)
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
which is javascript will come out as an object.
I think the problem is that when you're trying to compile testpoint.c, it includes point.h but it doesn't know about point.c. Since point.c has the definition for create
, not having point.c will cause the compilation to fail.
I'm not familiar with MinGW, but you need to tell the compiler to look for point.c. For example with gcc you might do this:
gcc point.c testpoint.c
As others have pointed out, you also need to remove one of your main
functions, since you can only have one.
You could try using PHP in your web page...something like this:
<html><body>
<form method="post" name="pingform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Host to ping:</h1>
<input type="text" name="tgt_host" value='<?php echo $_POST['tgt_host']; ?>'><br>
<input type="submit" name="submit" value="Submit" >
</form></body>
</html>
<?php
$tgt_host = $_POST['tgt_host'];
$output = shell_exec('ping -c 10 '. $tgt_host.');
echo "<html><body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Ping Results: " . $output . ".\");</script>
</body></html>";
?>
This is not tested so it may have typos etc...but I am confident it would work. Could be improved too...
global.myNumber; //Delclaration of the global variable - undefined
global.myNumber = 5; //Global variable initialized to value 5.
var myNumberSquared = global.myNumber * global.myNumber; //Using the global variable.
Node.js is different from client Side JavaScript when it comes to global variables. Just because you use the word var at the top of your Node.js script does not mean the variable will be accessible by all objects you require such as your 'basic-logger' .
To make something global just put the word global and a dot in front of the variable's name. So if I want company_id to be global I call it global.company_id. But be careful, global.company_id and company_id are the same thing so don't name global variable the same thing as any other variable in any other script - any other script that will be running on your server or any other place within the same code.
First of all, wave bye-bye to those quotes:
background-image: url(nickcage.jpg); // No quotes around the file name
Next, if your html, css and image are all in the same directory then removing the quotes should fix it. If, however, your css or image are in subdirectories of where your html lives, you'll want to make sure you correctly path to the image:
background-image: url(../images/nickcage.jpg); // css and image live in subdorectories
background-image: url(images/nickcage.jpg); // css lives with html but images is a subdirectory
Hope it helps.
I am new to AJAX and I have tried this and it works well.
function q1mrks(country,m) {
// alert("hellow");
if (country.length==0) {
//alert("hellow");
document.getElementById("q1mrks").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("q1mrks").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../location/cal_marks.php?q1mrks="+country+"&marks="+m,true);
//mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
xmlhttp.send();
}
This code works well :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
var options = {};
$("#c").hide();
$("#d").hide();
$("#a").click(function(){
$("#c").toggle( "slide", options, 500 );
$("#d").hide();
});
$("#b").click(function(){
$("#d").toggle( "slide", options, 500 );
$("#c").hide();
});
});
</script>
<style>
nav{
float:left;
max-width:300px;
width:300px;
margin-top:100px;
}
article{
margin-top:100px;
height:100px;
}
#c,#d{
padding:10px;
border:1px solid olive;
margin-left:100px;
margin-top:100px;
background-color:blue;
}
button{
border:2px solid blue;
background-color:white;
color:black;
padding:10px;
}
</style>
</head>
<body>
<header>
<center>hi</center>
</header>
<nav>
<button id="a">Register 1</button>
<br>
<br>
<br>
<br>
<button id="b">Register 2</button>
</nav>
<article id="c">
<form>
<label>User name:</label>
<input type="text" name="123" value="something"/>
<br>
<br>
<label>Password:</label>
<input type="text" name="456" value="something"/>
</form>
</article>
<article id="d">
<p>Hi</p>
</article>
</body>
</html>
Reference:W3schools.com and jqueryui.com
Note:This is a example code don't forget to add all the script tags in order to achieve proper functioning of the code.
You could add a span before the link with a specific class like so:
<div class="btn btn_red"><span class="icon"></span><a href="#">Crimson</a><span></span></div>
And then give that a specific width and a background image just like you are doing with the button itself.
.btn span.icon {
background: url(imgs/icon.png) no-repeat;
float: left;
width: 10px;
height: 40px;
}
I am no CSS guru but off the top of my head I think that should work.
Try cleaning the project and rebuild, if doesn't work try disabling the Instant Run from Settings>Build>Instant Run in case you are running someone else's code.
If the structure of your xml (or text in general) is fixed, the easiest way is using cut
. For your specific case:
echo '<table name="content_analyzer" primary-key="id">
<type="global" />
</table>
<table name="content_analyzer2" primary-key="id">
<type="global" />
</table>
<table name="content_analyzer_items" primary-key="id">
<type="global" />
</table>' | grep name= | cut -f2 -d '"'
const buildFormData = (formData: FormData, data: FormVal, parentKey?: string) => {
if (isArray(data)) {
data.forEach((el) => {
buildFormData(formData, el, parentKey)
})
} else if (typeof data === "object" && !(data instanceof File)) {
Object.keys(data).forEach((key) => {
buildFormData(formData, (data as FormDataNest)[key], parentKey ? `${parentKey}.${key}` : key)
})
} else {
if (isNil(data)) {
return
}
let value = typeof data === "boolean" || typeof data === "number" ? data.toString() : data
formData.append(parentKey as string, value)
}
}
export const getFormData = (data: Record<string, FormDataNest>) => {
const formData = new FormData()
buildFormData(formData, data)
return formData
}
const data = {
filePhotos: imageArray,
}
yourAjaxCall({
...,
data: getFormData(data)
})
Screenshot from Chrome dev tools - Network - Headers:
const data = {
nested: {
a: 1,
b: ["hello", "world"],
c: {
d: 2,
e: ["hello", "world"],
}
}
}
yourAjaxCall({
...,
data: getFormData(data)
})
If you are fine using 3rd-party library. You can check request-ip.
You can use it is by
import requestIp from 'request-ip';
app.use(requestIp.mw())
app.use((req, res) => {
const ip = req.clientIp;
});
The source code is quite long, so I won't copy here, you can check at https://github.com/pbojinov/request-ip/blob/master/src/index.js
Basically,
It looks for specific headers in the request and falls back to some defaults if they do not exist.
The user ip is determined by the following order:
X-Client-IP
X-Forwarded-For
(Header may return multiple IP addresses in the format: "client IP, proxy 1 IP, proxy 2 IP", so we take the the first one.)CF-Connecting-IP
(Cloudflare)Fastly-Client-Ip
(Fastly CDN and Firebase hosting header when forwared to a cloud function)True-Client-Ip
(Akamai and Cloudflare)X-Real-IP
(Nginx proxy/FastCGI)X-Cluster-Client-IP
(Rackspace LB, Riverbed Stingray)X-Forwarded
,Forwarded-For
andForwarded
(Variations of #2)req.connection.remoteAddress
req.socket.remoteAddress
req.connection.socket.remoteAddress
req.info.remoteAddress
If an IP address cannot be found, it will return
null
.
Disclose: I am not associated with the library.
Complete step-by-step instructions for running the accelerated emulator can be found on the official Android developers website:
Caution: As of SDK Tools Revision 17, the virtual machine acceleration feature for the emulator is experimental; be alert for incompatibilities and errors when using this feature.
df.insert(loc, column_name, value)
This will work if there is no other column with the same name. If a column, with your provided name already exists in the dataframe, it will raise a ValueError.
You can pass an optional parameter allow_duplicates
with True
value to create a new column with already existing column name.
Here is an example:
>>> df = pd.DataFrame({'b': [1, 2], 'c': [3,4]})
>>> df
b c
0 1 3
1 2 4
>>> df.insert(0, 'a', -1)
>>> df
a b c
0 -1 1 3
1 -1 2 4
>>> df.insert(0, 'a', -2)
Traceback (most recent call last):
File "", line 1, in
File "C:\Python39\lib\site-packages\pandas\core\frame.py", line 3760, in insert
self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
File "C:\Python39\lib\site-packages\pandas\core\internals\managers.py", line 1191, in insert
raise ValueError(f"cannot insert {item}, already exists")
ValueError: cannot insert a, already exists
>>> df.insert(0, 'a', -2, allow_duplicates = True)
>>> df
a a b c
0 -2 -1 1 3
1 -2 -1 2 4
You can use fireEvent on IE 8 or lower, and W3C's dispatchEvent on most other browsers. To create the event you want to fire, you can use either createEvent
or createEventObject
depending on the browser.
Here is a self-explanatory piece of code (from prototype) that fires an event dataavailable
on an element
:
var event; // The custom event that will be created
if(document.createEvent){
event = document.createEvent("HTMLEvents");
event.initEvent("dataavailable", true, true);
event.eventName = "dataavailable";
element.dispatchEvent(event);
} else {
event = document.createEventObject();
event.eventName = "dataavailable";
event.eventType = "dataavailable";
element.fireEvent("on" + event.eventType, event);
}
You don't need a library beyond the standard one - just use Charset. (You can just use the String constructors and getBytes methods, but personally I don't like just working with the names of character encodings. Too much room for typos.)
EDIT: As pointed out in comments, you can still use Charset instances but have the ease of use of the String methods: new String(bytes, charset) and String.getBytes(charset).
See "URL Encoding (or: 'What are those "%20
" codes in URLs?')".
So Nodejs comes with the default global variable called '__fileName'
that holds the current file being executed
My advice is to pass the __fileName to a service from any file , so that the retrieval of the fileName is made dynamic
Below, I make use of the fileName string and then split it based on the path.sep
. Note path.sep avoids issues with posix file seperators and windows file seperators (issues with '/' and '\'). It is much cleaner. Getting the substring and getting only the last seperated name and subtracting it with the actulal length by 3 speaks for itself.
You can write a service like this (Note this is in typescript , but you can very well write it in js )
export class AppLoggingConstants {
constructor(){
}
// Here make sure the fileName param is actually '__fileName'
getDefaultMedata(fileName: string, methodName: string) {
const appName = APP_NAME;
const actualFileName = fileName.substring(fileName.lastIndexOf(path.sep)+1, fileName.length - 3);
//const actualFileName = fileName;
return appName+ ' -- '+actualFileName;
}
}
export const AppLoggingConstantsInstance = new AppLoggingConstants();
No, there is no better way.
Actually you have an error in your pattern. What you want is:
DecimalFormat df = new DecimalFormat("#.00");
Note the "00"
, meaning exactly two decimal places.
If you use "#.##"
(#
means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d);
prints just "3"
, not "3.00"
.
Using self.location.reload()
will reload the iframe.
<iframe src="https://vivekkumar11432.wordpress.com/" width="300" height="300"></iframe>_x000D_
<br><br>_x000D_
<input type='button' value="Reload" onclick="self.location.reload();" />
_x000D_
You can't: DataFrame
columns are Series
, by definition. That said, if you make the dtype
(the type of all the elements) datetime-like, then you can access the quantities you want via the .dt
accessor (docs):
>>> df["TimeReviewed"] = pd.to_datetime(df["TimeReviewed"])
>>> df["TimeReviewed"]
205 76032930 2015-01-24 00:05:27.513000
232 76032930 2015-01-24 00:06:46.703000
233 76032930 2015-01-24 00:06:56.707000
413 76032930 2015-01-24 00:14:24.957000
565 76032930 2015-01-24 00:23:07.220000
Name: TimeReviewed, dtype: datetime64[ns]
>>> df["TimeReviewed"].dt
<pandas.tseries.common.DatetimeProperties object at 0xb10da60c>
>>> df["TimeReviewed"].dt.year
205 76032930 2015
232 76032930 2015
233 76032930 2015
413 76032930 2015
565 76032930 2015
dtype: int64
>>> df["TimeReviewed"].dt.month
205 76032930 1
232 76032930 1
233 76032930 1
413 76032930 1
565 76032930 1
dtype: int64
>>> df["TimeReviewed"].dt.minute
205 76032930 5
232 76032930 6
233 76032930 6
413 76032930 14
565 76032930 23
dtype: int64
If you're stuck using an older version of pandas
, you can always access the various elements manually (again, after converting it to a datetime-dtyped Series). It'll be slower, but sometimes that isn't an issue:
>>> df["TimeReviewed"].apply(lambda x: x.year)
205 76032930 2015
232 76032930 2015
233 76032930 2015
413 76032930 2015
565 76032930 2015
Name: TimeReviewed, dtype: int64
/index.html
<!doctype html>
<html>
<head>
<title>My Application</title>
<!-- load application bundle asynchronously -->
<script async src="/app.js"></script>
<style type="text/css">
/* pre-rendered critical path CSS (see isomorphic-style-loader) */
</style>
</head>
<body>
<div id="app">
<!-- pre-rendered markup of your JavaScript app (see isomorphic apps) -->
</div>
</body>
</html>
/app.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
function run() {
ReactDOM.render(<App />, document.getElementById('app'));
}
const loadedStates = ['complete', 'loaded', 'interactive'];
if (loadedStates.includes(document.readyState) && document.body) {
run();
} else {
window.addEventListener('DOMContentLoaded', run, false);
}
(IE9+)
Note: Having <script async src="..."></script>
in the header ensures that the browser will start downloading JavaScript bundle before HTML content is loaded.
The following will return 1..10000 and is not so slow
SELECT @row := @row + 1 AS row FROM
(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t,
(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2,
(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t3,
(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t4,
(SELECT @row:=0) numbers;
The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable
.
So for that, here is what I did, when I came across the same problem.
string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };
foreach (string ColName in ColumnsToBeDeleted)
{
if (dt.Columns.Contains(ColName))
dt.Columns.Remove(ColName);
}
FWIW, htpasswd -n username
will output the result directly to stdout, and avoid touching files altogether.
I'd prefer to use [:punct:]
for that. Also, a-zA-Z09-9
could be just [:alnum:]
:
[[ $TEST =~ ^[[:alnum:][:blank:][:punct:]]+$ ]]
This is the simplest wat to get the File object to which a certain URL object is pointing at:
File file=new File(url.toURI());
Now, for your concrete questions:
- finding all resources in the META-INF "directory":
You can indeed get the File object pointing to this URL
Enumeration<URL> en=getClass().getClassLoader().getResources("META-INF");
if (en.hasMoreElements()) {
URL metaInf=en.nextElement();
File fileMetaInf=new File(metaInf.toURI());
File[] files=fileMetaInf.listFiles();
//or
String[] filenames=fileMetaInf.list();
}
- all resources named bla.xml (recursivly)
In this case, you'll have to do some custom code. Here is a dummy example:
final List<File> foundFiles=new ArrayList<File>();
FileFilter customFilter=new FileFilter() {
@Override
public boolean accept(File pathname) {
if(pathname.isDirectory()) {
pathname.listFiles(this);
}
if(pathname.getName().endsWith("bla.xml")) {
foundFiles.add(pathname);
return true;
}
return false;
}
};
//rootFolder here represents a File Object pointing the root forlder of your search
rootFolder.listFiles(customFilter);
When the code is run, you'll get all the found ocurrences at the foundFiles
List.
Eclipse has got the concept of incremental builds.This is incredibly useful as it saves a lot of time.
How is this Useful
Say you just changed a single .java file. The incremental builders will be able to compile the code without having to recompile everything(which will take more time).
Now what's the problem with Maven Plugins
Most of the maven plugins aren't designed for incremental builds and hence it creates trouble for m2e. m2e doesn't know if the plugin goal is something which is crucial or if it is irrelevant. If it just executes every plugin when a single file changes, it's gonna take lots of time.
This is the reason why m2e relies on metadata information to figure out how the execution should be handled. m2e has come up with different options to provide this metadata information and the order of preference is as below(highest to lowest)
1,2 refers to specifying pluginManagement section in the tag of your pom file or any of it's parents. M2E reads this configuration to configure the project.Below snippet instructs m2e to ignore the jslint
and compress
goals of the yuicompressor-maven-plugin
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>net.alchim31.maven</groupId>
<artifactId>yuicompressor-maven-plugin</artifactId>
<versionRange>[1.0,)</versionRange>
<goals>
<goal>compress</goal>
<goal>jslint</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
3) In case you don't prefer polluting your pom file with this metadata, you can store this in an external XML file(option 3). Below is a sample mapping file which instructs m2e to ignore the jslint
and compress
goals of the yuicompressor-maven-plugin
<?xml version="1.0" encoding="UTF-8"?>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>net.alchim31.maven</groupId>
<artifactId>yuicompressor-maven-plugin</artifactId>
<versionRange>[1.0,)</versionRange>
<goals>
<goal>compress</goal>
<goal>jslint</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore/>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
4) In case you don't like any of these 3 options, you can use an m2e connector(extension) for the maven plugin.The connector will in turn provide the metadata to m2e. You can see an example of the metadata information within a connector at this link . You might have noticed that the metadata refers to a configurator. This simply means that m2e will delegate the responsibility to that particular java class supplied by the extension author.The configurator can configure the project(like say add additional source folders etc) and decide whether to execute the actual maven plugin during an incremental build(if not properly managed within the configurator, it can lead to endless project builds)
Refer these links for an example of the configuratior(link1,link2). So in case the plugin is something which can be managed via an external connector then you can install it. m2e maintains a list of such connectors contributed by other developers.This is known as the discovery catalog. m2e will prompt you to install a connector if you don't already have any lifecycle mapping metadata for the execution through any of the options(1-6) and the discovery catalog has got some extension which can manage the execution.
The below image shows how m2e prompts you to install the connector for the build-helper-maven-plugin. .
5)m2e encourages the plugin authors to support incremental build and supply lifecycle mapping within the maven-plugin itself.This would mean that users won't have to use any additional lifecycle mappings or connectors.Some plugin authors have already implemented this
6) By default m2e holds the lifecycle mapping metadata for most of the commonly used plugins like the maven-compiler-plugin and many others.
Now back to the question :You can probably just provide an ignore life cycle mapping in 1, 2 or 3 for that specific goal which is creating trouble for you.
The current answers are outdated. You should be able to use #error version
(at the top of any C# file in the project, or nearly anywhere in the code). The compiler treats this in a special way and reports a compiler error, CS8304, indicating the language version, and also the compiler version. The message of CS8304 is something that looks like the following:
error CS8304: Compiler version: '3.7.0-3.20312.3 (ec484126)'. Language version: 6.
Completely distinct rows:
public static DataTable Dictinct(this dt) => dt.DefaultView.ToTable(true);
Distinct by particular row(s) (Note that the columns mentioned in "distinctCulumnNames" will be returned in resulting DataTable):
public static DataTable Dictinct(this dt, params string[] distinctColumnNames) =>
dt.DefaultView.ToTable(true, distinctColumnNames);
Distinct by particular column (preserves all columns in given DataTable):
public static void Distinct(this DataTable dataTable, string distinctColumnName)
{
var distinctResult = new DataTable();
distinctResult.Merge(
.GroupBy(row => row.Field<object>(distinctColumnName))
.Select(group => group.First())
.CopyToDataTable()
);
if (distinctResult.DefaultView.Count < dataTable.DefaultView.Count)
{
dataTable.Clear();
dataTable.Merge(distinctResult);
dataTable.AcceptChanges();
}
}
Update only works on updating querysets. If you want to update multiple fields at the same time, say from a dict for a single object instance you can do something like:
obj.__dict__.update(your_dict)
obj.save()
Bear in mind that your dictionary will have to contain the correct mapping where the keys need to be your field names and the values the values you want to insert.
Go to
JBoss\jboss-eap-6.1\modules\system\layers\base\javax\servlet\api\main
include JAR
jboss-servlet-api_3.0_spec-1.0.2.Final-redhat-1.jar
For me it worked
@datenstation had the correct concept. Here is a working example that uses CTE to cache variable's names:
CREATE VIEW vwImportant_Users AS
WITH params AS (
SELECT
varType='%Admin%',
varMinStatus=1)
SELECT status, name
FROM sys.sysusers, params
WHERE status > varMinStatus OR name LIKE varType
SELECT * FROM vwImportant_Users
also via JOIN
WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
SELECT status, name
FROM sys.sysusers INNER JOIN params ON 1=1
WHERE status > varMinStatus OR name LIKE varType
also via CROSS APPLY
WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
SELECT status, name
FROM sys.sysusers CROSS APPLY params
WHERE status > varMinStatus OR name LIKE varType
Use the component:
<Route exact path="/details/:id" component={DetailsPage} />
And you should be able to access the id
using:
this.props.match.params.id
Inside the DetailsPage
component
Basic overview of hashing and encryption/decryption techniques are.
Hashing:
If you hash any plain text again you can not get the same plain text from hashed text. Simply, It's a one-way process.
Encryption and Decryption:
If you encrypt any plain text with a key again you can get same plain text by doing decryption on encrypted text with same(symetric)/diffrent(asymentric) key.
UPDATE: To address the points mentioned in the edited question.
1. When to use hashes vs encryptions
Hashing is useful if you want to send someone a file. But you are afraid that someone else might intercept the file and change it. So a way that the recipient can make sure that it is the right file is if you post the hash value publicly. That way the recipient can compute the hash value of the file received and check that it matches the hash value.
Encryption is good if you say have a message to send to someone. You encrypt the message with a key and the recipient decrypts with the same (or maybe even a different) key to get back the original message. credits
2. What makes a hash or encryption algorithm different (from a theoretical/mathematical level) i.e. what makes hashes irreversible (without aid of a rainbow tree)
Basically hashing is an operation that loses information but not encryption. Let's look at the difference in simple mathematical way for our easy understanding, of course both have much more complicated mathematical operation with repetitions involved in it
Encryption/Decryption (Reversible):
Addition:
4 + 3 = 7
This can be reversed by taking the sum and subtracting one of the addends
7 - 3 = 4
Multiplication:
4 * 5 = 20
This can be reversed by taking the product and dividing by one of the factors
20 / 4 = 5
So, here we could assume one of the addends/factors is a decrpytion key and result(7,20) is an excrypted text.
Hashing (Not Reversible):
Modulo division:
22 % 7 = 1
This can not be reversed because there is no operation that you can do to the quotient and the dividend to reconstitute the divisor (or vice versa).
Can you find an operation to fill in where the '?' is?
1 ? 7 = 22 1 ? 22 = 7
So hash functions have the same mathematical quality as modulo division and looses the information.
In javascript, it is not possible but yes with the help of “Web Clips” we can create a "add to home screen" icon or shortcut in iPhone( by the code file of .mobileconfig)
http://appdistro.cttapp.com/webclip/
after create a mobileconfig file we can pass this url in iphone safari browser install certificate and after done it check your iphone home screen there is a shortcut icon of your Web page or webapp..
I assume you have your JS file declared inside the <head>
tag so it keeps it consistent, like standard, then in your JS make sure the canvas initialization is after the page is loaded:
window.onload = function () {
var myCanvas = document.getElementById('canvas');
var ctx = myCanvas.getContext('2d');
}
There is no need to use jQuery just to initialize a canvas, it's very evident most of the programmers all around the world use it unnecessarily and the accepted answer is a probe of that.
You can also capitalize the first letter of the match using \I1
and \I2
etc instead of $1
and $2
.
The 100% working solution
public static function rmdir_recursive($directory, $delete_parent = null)
{
$files = glob($directory . '/{,.}[!.,!..]*',GLOB_MARK|GLOB_BRACE);
foreach ($files as $file) {
if (is_dir($file)) {
self::rmdir_recursive($file, 1);
} else {
unlink($file);
}
}
if ($delete_parent) {
rmdir($directory);
}
}
On a Unix/Linux box you could just run 'wget' but this is not really an option if you're writing a cross-platform client. Of course this assumes that you don't really want to do much with the data you download between the point of downloading it and it hitting the disk.
For me it was the apache server hosted on a t2.micro linux EC2 instance, not the EC2 instance itself.
I fixed it by doing:
sudo su
service httpd restart
Use:
$ deactivate
If this doesn't work, try
$ source deactivate
Anyone who knows how Bash source
works will think that's odd, but some wrappers/workflows around virtualenv implement it as a complement/counterpart to source activate
. Your mileage may vary.
Yes, if bar is not None
is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar:
will execute if bar
is any kind of zero or empty container, or False
.
Many people do use not bar
where they really do mean bar is not None
.
The transient
keyword in Java is used to indicate that a field should not be part of the serialization (which means saved, like to a file) process.
From the Java Language Specification, Java SE 7 Edition, Section 8.3.1.3. transient
Fields:
Variables may be marked
transient
to indicate that they are not part of the persistent state of an object.
For example, you may have fields that are derived from other fields, and should only be done so programmatically, rather than having the state be persisted via serialization.
Here's a GalleryImage
class which contains an image and a thumbnail derived from the image:
class GalleryImage implements Serializable
{
private Image image;
private transient Image thumbnailImage;
private void generateThumbnail()
{
// Generate thumbnail.
}
private void readObject(ObjectInputStream inputStream)
throws IOException, ClassNotFoundException
{
inputStream.defaultReadObject();
generateThumbnail();
}
}
In this example, the thumbnailImage
is a thumbnail image that is generated by invoking the generateThumbnail
method.
The thumbnailImage
field is marked as transient
, so only the original image
is serialized rather than persisting both the original image and the thumbnail image. This means that less storage would be needed to save the serialized object. (Of course, this may or may not be desirable depending on the requirements of the system -- this is just an example.)
At the time of deserialization, the readObject
method is called to perform any operations necessary to restore the state of the object back to the state at which the serialization occurred. Here, the thumbnail needs to be generated, so the readObject
method is overridden so that the thumbnail will be generated by calling the generateThumbnail
method.
For additional information, the Discover the secrets of the Java Serialization API article (which was originally available on the Sun Developer Network) has a section which discusses the use of and presents a scenario where the transient
keyword is used to prevent serialization of certain fields.
In my case I was getting these errors during installation of an apk on a device:
Error during Sync: An existing connection was forcibly closed by the remote host
Error during Sync: EOF
Unable to open connection to: localhost/127.0.0.1:5037, due to: java.net.ConnectException: Connection refused: connect
That led to:
java.io.IOException: EOF
Error while Installing APK
Restarting a device and adb devices didn't help.
I replaced a data-cable
and installed the apk.
-w
is the GCC-wide option to disable warning messages.
That's because you defined your own version of name
for your enum, and getByName
doesn't use that.
getByName("COLUMN_HEADINGS")
would probably work.
One can use a plain ImageView in his xml and make it clickable (android:clickable="true")? You only have to use as src an image that has been shaped like a button i.e round corners.
A difference not yet mentioned: size limit
void *malloc(size_t size)
can only allocate up to SIZE_MAX
.
void *calloc(size_t nmemb, size_t size);
can allocate up about SIZE_MAX*SIZE_MAX
.
This ability is not often used in many platforms with linear addressing. Such systems limit calloc()
with nmemb * size <= SIZE_MAX
.
Consider a type of 512 bytes called disk_sector
and code wants to use lots of sectors. Here, code can only use up to SIZE_MAX/sizeof disk_sector
sectors.
size_t count = SIZE_MAX/sizeof disk_sector;
disk_sector *p = malloc(count * sizeof *p);
Consider the following which allows an even larger allocation.
size_t count = something_in_the_range(SIZE_MAX/sizeof disk_sector + 1, SIZE_MAX)
disk_sector *p = calloc(count, sizeof *p);
Now if such a system can supply such a large allocation is another matter. Most today will not. Yet it has occurred for many years when SIZE_MAX
was 65535. Given Moore's law, suspect this will be occurring about 2030 with certain memory models with SIZE_MAX == 4294967295
and memory pools in the 100 of GBytes.
None of the above worked for me... found out something wrong with my init method on my appDelegate. If you are implementing the init method make sure you do it correctly
i had this:
- (id)init {
if (!self) {
self = [super init];
sharedInstance = self;
}
return sharedInstance;
}
and changed it to this:
- (id)init {
if (!self) {
self = [super init];
}
sharedInstance = self;
return sharedInstance;
}
where "sharedInstance" its a pointer to my appDelegate singleton
try {
SimpleDateFormat format = new SimpleDateFormat("hh:mm a"); //if 24 hour format
// or
SimpleDateFormat format = new SimpleDateFormat("HH:mm"); // 12 hour format
java.util.Date d1 =(java.util.Date)format.parse(your_Time);
java.sql.Time ppstime = new java.sql.Time(d1.getTime());
} catch(Exception e) {
Log.e("Exception is ", e.toString());
}
Well i am trying to open a .vbs within a batch file without having to click open but the answer to this question is ...
SET APPDATA=%CD%
start (your file here without the brackets with a .vbs if it is a vbd file)
As RAND
produces a number 0 <= v < 1.0 (see documentation) you need to use ROUND
to ensure that you can get the upper bound (500 in this case) and the lower bound (100 in this case)
So to produce the range you need:
SELECT name, address, ROUND(100.0 + 400.0 * RAND()) AS random_number
FROM users
Anything you want to use for bitwise operations must be between 0x80000000 (-2147483648 or -2^31) and 0x7fffffff (2147483647 or 2^31 - 1).
The console will tell you that 0x80000000 equals +2147483648, but 0x80000000 & 0x80000000 equals -2147483648.
This would work:
declare @test varchar(100)
set @test = 'this is a test'
while charindex(' ',@test ) > 0
begin
set @test = replace(@test, ' ', ' ')
end
select @test
In MacBook press command+, and then go to plug-in and search for Lombok and then install it.
It will work without restarting IntelliJ IDEA IDE if doesn't work then please try with restart.
Many thanks
In Angular 2+, you can set route to default page by adding this route to your route module. In this case login is my target route for the default page.
{path:'',redirectTo:'login', pathMatch: 'full' },
It seems that if you specify table-layout: fixed;
on the table
element, then your styles for td
should take effect. This will also affect how the cells are sized, though.
Sitepoint discusses the table-layout methods a little here: http://reference.sitepoint.com/css/tableformatting
"|Howdy".replace(new RegExp("^\\|"),"");
(note the double escaping. \\
needed, to have an actually single slash in the string, that then leads to escaping of |
in the regExp).
Only few characters need regExp-Escaping., among them the pipe operator.
Yahoo is very easy to use and provides customized data. Use the following page to learn more.
finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT=pder=.csv
WARNING - there are a few tutorials out there on the web that show you how to do this, but the region where you put in the stock symbols causes an error if you use it as posted. You will get a "MISSING FORMAT VALUE". The tutorials I found omits the commentary around GOOG.
Example URL for GOOG: http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,GOOG&f=nsl1op&e=.csv
On Centos 7.8 and PHP 7.3
yum install php-soap
service httpd restart
You'd have to define alphanumerics exactly, but
/^(\w{3,5})$/
Should match any digit/character/_ combination of length 3-5.
If you also need the dash, make sure to escape it ( add it, like this: :\-
)
/^([\w\-]{3,5})$/
Also: the ^
anchor means that the sequence has to start at the beginning of the line (character string), and the $
that it ends at the end of the line (character string). So your value
string mustn't contain anything else, or it won't match.
MailSystem.NET contains all your need for IMAP4. It's free & open source.
(I'm involved in the project)
You can simply use datetime diff and format for calculating difference.
<?php
$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y-%m-%d %H:%i:%s');
?>
For more information OF DATETIME format, refer: here
You can change the interval format in the way,you want.
Here is the working example
P.S. These features( diff() and format()) work with >=PHP 5.3.0 only
This is my sample code for load static variable
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class OnelinkConfig {
public static int MODULE_CODE;
public static int DEFAULT_PAGE;
public static int DEFAULT_SIZE;
@Autowired
public void loadOnelinkConfig(@Value("${onelink.config.exception.module.code}") int code,
@Value("${onelink.config.default.page}") int page, @Value("${onelink.config.default.size}") int size) {
MODULE_CODE = code;
DEFAULT_PAGE = page;
DEFAULT_SIZE = size;
}
}
you can also pyramid of stars like this
for (var i = 5; i >= 1; i--) {
var py = "";
for (var j = i; j >= 1; j--) {
py += j;
}
console.log(py);
}
Make sure that all functions with non-void return type have a return
statement.
While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.
Just delete .npmrc folder in c:users>'username' and try running the command it will be resolved !
Definitely a network/proxy thing. I connect via wifi and a corporate gateway. Deleted workspace, reinstalled GGTS - still hangs. Turn off the network - launches fine.
In terms of how len()
actually works, this is its C implementation:
static PyObject *
builtin_len(PyObject *module, PyObject *obj)
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
{
Py_ssize_t res;
res = PyObject_Size(obj);
if (res < 0) {
assert(PyErr_Occurred());
return NULL;
}
return PyLong_FromSsize_t(res);
}
Py_ssize_t
is the maximum length that the object can have. PyObject_Size()
is a function that returns the size of an object. If it cannot determine the size of an object, it returns -1. In that case, this code block will be executed:
if (res < 0) {
assert(PyErr_Occurred());
return NULL;
}
And an exception is raised as a result. Otherwise, this code block will be executed:
return PyLong_FromSsize_t(res);
res
which is a C
integer, is converted into a Python int
(which is still called a "Long" in the C code because Python 2 had two types for storing integers) and returned.
var myString = "echoHello";
window[myString] = function() {
alert("Hello!");
}
echoHello();
Say no to the evil eval. Example here: https://jsfiddle.net/Shaz/WmA8t/
From the main menu bar, select command link File > Import.... The Import wizard opens.
Select General > Existing Project into Workspace and click Next.
Choose either Select root directory or Select archive file and click the associated Browse to locate the directory or file containing the projects.
Under Projects select the project or projects which you would like to import.
Click Finish to start the import.
This happens because you're trying to serialize the EF object collection directly. Since department has an association to employee and employee to department, the JSON serializer will loop infinetly reading d.Employee.Departments.Employee.Departments etc...
To fix this right before the serialization create an anonymous type with the props you want
example (psuedo)code:
departments.select(dep => new {
dep.Id,
Employee = new {
dep.Employee.Id, dep.Employee.Name
}
});
atoi can do that for you
Example:
char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234
Rather than keeping everything string-based, you should use a class which is designed to represent a file system path.
If you're using Java 7 or Java 8, you should strongly consider using java.nio.file.Path
; Path.resolve
can be used to combine one path with another, or with a string. The Paths
helper class is useful too. For example:
Path path = Paths.get("foo", "bar", "baz.txt");
If you need to cater for pre-Java-7 environments, you can use java.io.File
, like this:
File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");
If you want it back as a string later, you can call getPath()
. Indeed, if you really wanted to mimic Path.Combine
, you could just write something like:
public static String combine(String path1, String path2)
{
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
getApplicationContext()
this is used for application level and refer to all activities.
getContext() and getBaseContext()
is most probably same .these are reffered only current activity which is live.
this
is refer current class object always.
Use the option NSCaseInsensitiveSearch with rangeOfString:options:
NSString *me = @"toBe" ;
NSString *target = @"abcdetobe" ;
NSRange range = [target rangeOfString: me options: NSCaseInsensitiveSearch];
NSLog(@"found: %@", (range.location != NSNotFound) ? @"Yes" : @"No");
if (range.location != NSNotFound) {
// your code
}
Output result is found:Yes
The options can be "or'ed" together and include:
NSCaseInsensitiveSearch NSLiteralSearch NSBackwardsSearch and more
Might help someone:
when you have a formGroup in a modal (entrycomponent), then you have to import ReactiveFormsModule also in the module where the modal is instantiated.
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).2 hours spent to get into details.
Note that the answer for question is already given at https://stackoverflow.com/a/31159284/984471
However, the question has keys that are not usual ones,
A clear & general example with explanation, is below that provides some more clarity:
.
let m1 = new Map();
m1.set(6,1); // key 6 is number and type is preserved (can be strings too)
m1.set(10,1);
m1.set(100,1);
m1.set(1,1);
console.log(m1);
// "string" sorted (even if keys are numbers) - default behaviour
let m2 = new Map( [...m1].sort() );
// ...is destructuring into individual elements
// then [] will catch elements in an array
// then sort() sorts the array
// since Map can take array as parameter to its constructor, a new Map is created
console.log('m2', m2);
// number sorted
let m3 = new Map([...m1].sort((a, b) => {
if (a[0] > b[0]) return 1;
if (a[0] == b[0]) return 0;
if (a[0] < b[0]) return -1;
}));
console.log('m3', m3);
// Output
// Map { 6 => 1, 10 => 1, 100 => 1, 1 => 1 }
// m2 Map { 1 => 1, 10 => 1, 100 => 1, 6 => 1 }
// Note: 1,10,100,6 sorted as strings, default.
// Note: if the keys were string the sort behavior will be same as this
// m3 Map { 1 => 1, 6 => 1, 10 => 1, 100 => 1 }
// Note: 1,6,10,100 sorted as number, looks correct for number keys
Hope that helps.
It accepts only a string value of "true"
to represent boolean true
. Best what you can do is
boolean uses_votes = "1".equals(o.get("uses_votes"));
Or if the Map
actually represents an "entitiy", I think a Javabean is way much better. Or if it represents configuration settings, you may want to take a look into Apache Commons Configuration.
script1.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170
This error happens due to a security measure which won't let scripts be executed on your system without you having approved of it. You can do so by opening up a powershell with administrative rights (search for powershell in the main menu and select Run as administrator from the context menu) and entering:
set-executionpolicy remotesigned
update on someone else his answer transparant sides instead of white so it works on other color backgrounds too.
body {_x000D_
background: url(http://s1.picswalls.com/wallpapers/2016/03/29/beautiful-nature-backgrounds_042320876_304.jpg)_x000D_
}_x000D_
_x000D_
div {_x000D_
background: url(https://www.w3schools.com/w3css/img_avatar3.png) center center;_x000D_
background-size: contain;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
margin: 50px;_x000D_
border: 5px solid white;_x000D_
box-shadow: 0px 0 rgba(0, 0, 0, 0), 0px 0 rgba(0, 0, 0, 0), 0 7px 7px -5px black;_x000D_
}
_x000D_
<div>_x000D_
</div>
_x000D_
That's not a good practice and there is no mechanism to do that because of that. The right way to accomplish what you want is inheritance.
Take a look into the class documentation.
A little example:
class Employee(object):
def __init__(self, age, sex, siblings=0):
self.age = age
self.sex = sex
self.siblings = siblings
def born_on(self):
today = datetime.date.today()
return today - datetime.timedelta(days=self.age*365)
class Boss(Employee):
def __init__(self, age, sex, siblings=0, bonus=0):
self.bonus = bonus
Employee.__init__(self, age, sex, siblings)
This way Boss has everything Employee
has, with also his own __init__
method and own members.
In the spirit of functional programming, let's make our components a bit easier to work with by using abstractions.
// converts components into mappable functions
var mappable = function(component){
return function(x, i){
return component({key: i}, x);
}
}
// maps on 2-dimensional arrays
var map2d = function(m1, m2, xss){
return xss.map(function(xs, i, arr){
return m1(xs.map(m2), i, arr);
});
}
var td = mappable(React.DOM.td);
var tr = mappable(React.DOM.tr);
var th = mappable(React.DOM.th);
Now we can define our render like this:
render: function(){
return (
<table>
<thead>{this.props.titles.map(th)}</thead>
<tbody>{map2d(tr, td, this.props.rows)}</tbody>
</table>
);
}
An alternative to our map2d would be a curried map function, but people tend to shy away from currying.
They are two formats of representation of information. While JSON was designed to be more compact, XML was design to be more readable.
If you are using GitBash
Step one:
netstat -ano | findstr :8080
Step two:
taskkill /PID typeyourPIDhere /F
(/F
forcefully terminates the process)
bash:
for f in *.xls ; do xls2csv "$f" "${f%.xls}.csv" ; done
I am seeing starkly different runtimes when I take a for loop in g++ 4.7.0 and using
std::vector<double> x;
std::vector<double> y;
std::vector<double> prod;
for (int i = 0; i < 5000000; i++)
{
double r1 = ((double)rand() / double(RAND_MAX)) * 5;
double r2 = ((double)rand() / double(RAND_MAX)) * 5;
x.push_back(r1);
y.push_back(r2);
}
int sz = x.size();
#pragma omp parallel for
for (int i = 0; i< sz; i++)
prod[i] = x[i] * y[i];
the serial code (no openmp
) runs in 79 ms.
the "parallel for" code runs in 29 ms.
If I omit the for
and use #pragma omp parallel
, the runtime shoots up to 179ms,
which is slower than serial code. (the machine has hw concurrency of 8)
the code links to libgomp
There are very good answers with detailed explanation to this post. I just would like to refer that there is another explanation with visual representation for the meaning of Frame, Bounds, Center, Transform, Bounds Origin in WWDC 2011 video Understanding UIKit Rendering starting from @4:22 till 20:10
= my() {};
means that there's an anonymous implementation, not simple instantiation of an object, which should have been : = my()
. You can never instantiate an abstract class.
<%
String session_val = (String)session.getAttribute("sessionval");
System.out.println("session_val"+session_val);
%>
<html>
<head>
<script type="text/javascript">
var session_obj= '<%=session_val%>';
alert("session_obj"+session_obj);
</script>
</head>
</html>
You can fake the disabled effect using CSS.
pointer-events:none;
You might also want to change colors etc.
This's simple and works like a charm :) just declare your enum like this and you can use it on HTML template
statusEnum: typeof StatusEnum = StatusEnum;
Other answers are doing a good job of summarizing the requirements of main
. I want to gather references to where those requirements are documented.
The most authoritative source is the VM
spec (second edition cited). As main
is not a language feature, it is not considered in the Java Language Specification.
Another good resource is the documentation for the application launcher itself:
See the docs from django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest
You need to specify a field in latest(). eg.
obj= Model.objects.filter(testfield=12).latest('testfield')
Or if your model’s Meta specifies get_latest_by, you can leave off the field_name
argument to earliest() or latest()
. Django will use the field specified in get_latest_by
by default.
SELECT TRUNC(SYSDATE,'D') "1ST_DAY", TRUNC(SYSDATE,'D') + 6 LAST_DAY FROM DUAL
It is very clear from your exception that it is trying to connect to localhost
and not to 10.101.3.229
exception snippet : Could not connect to SMTP host: localhost, port: 25;
1.) Please check if there are any null check which is setting localhost as default value
2.) After restarting, if it is working fine, then it means that only at first-run, the proper value is been taken from Properties and from next run the value is set to default. So keep the property-object as a singleton one and use it all-over your project
I think this is what you want:
document.getElementById('tag-id').innerHTML = '<ol><li>html data</li></ol>';
Keep in mind that innerHTML is not accessible for all types of tags when using IE. (table elements for example)
I have had to unpack a .ab
-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.
Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab
-file is password-protected.
Usage:java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]
Example:
Let's say, you've got a file test.ab
, which is not password-protected, you're using Windows and want the resulting .tar
-Archive to be called test.tar
. Then your command should be:
java.exe -jar abe.jar unpack test.ab test.tar ""
var today = new Date(); _x000D_
_x000D_
var formattedtoday = today.getDate() + '-' + (today.getMonth() + 1) + '-' + today.getFullYear();_x000D_
_x000D_
alert(formattedtoday);
_x000D_
Use functools.partial, not lambdas! And ofc Perform is a useless function, you can pass around functions directly.
for func in [Action1, partial(Action2, p), partial(Action3, p, r)]:
func()
There are 10^6 values in a range of 10^8, so there's one value per hundred code points on average. Store the distance from the Nth point to the (N+1)th. Duplicate values have a skip of 0. This means that the skip needs an average of just under 7 bits to store, so a million of them will happily fit into our 8 million bits of storage.
These skips need to be encoded into a bitstream, say by Huffman encoding. Insertion is by iterating through the bitstream and rewriting after the new value. Output by iterating through and writing out the implied values. For practicality, it probably wants to be done as, say, 10^4 lists covering 10^4 code points (and an average of 100 values) each.
A good Huffman tree for random data can be built a priori by assuming a Poisson distribution (mean=variance=100) on the length of the skips, but real statistics can be kept on the input and used to generate an optimal tree to deal with pathological cases.
Here is something that might help. Use the root privileges. if you have .bin then simply add the execution permission to the bin file.
chmod a+x jdk*.bin
next step is to run the .bin file which is simply
./jdk*.bin in the location you want to install.
you are done.
If you have a folder and sub-folder full of wav's you want to convert, put below command in a file, save it in a .bat file in the root of the folder where you wan to convert, and then run the bat file
for /R %%g in (*.wav) do start /b /wait "" "C:\ffmpeg-4.0.1-win64-static\bin\ffmpeg" -threads 16 -i "%%g" -acodec libmp3lame "%%~dpng.mp3" && del "%%g"
Another method to disable link
element.removeAttribute('href');
anchor tag without href would react as disabled/plain text
<a> w/o href </a>
instead of <a href="#"> with href </a>
see jsFiddel
hope this is heplful.
Here's a simpler one that takes dst in to account
CREATE FUNCTION [dbo].[UtcToLocal]
(
@p_utcDatetime DATETIME
)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(MINUTE, DATEDIFF(MINUTE, GETUTCDATE(), @p_utcDatetime), GETDATE())
END
Here is my solution - The method takes an array of integers(assuming the range between 0 to 100) as input and returns the number of occurrences of each element.
let's say the input is [21,34,43,21,21,21,45,65,65,76,76,76]
.
So the output would be in a map and it is: {34=1, 21=4, 65=2, 76=3, 43=1, 45=1}
public Map<Integer, Integer> countOccurrence(int[] numbersToProcess) {
int[] possibleNumbers = new int[100];
Map<Integer, Integer> result = new HashMap<Integer, Integer>();
for (int i = 0; i < numbersToProcess.length; ++i) {
possibleNumbers[numbersToProcess[i]] = possibleNumbers[numbersToProcess[i]] + 1;
result.put(numbersToProcess[i], possibleNumbers[numbersToProcess[i]]);
}
return result;
}
I just got another case to display backslash \
with Razor and Java Script.
My @Model.AreaName
looks like Name1\Name2\Name3 so when I display it all backslashes are gone and I see Name1Name2Name3
I found solution to fix it:
var areafullName = JSON.parse("@Html.Raw(HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(Model.AreaName)))");
Don't forget to add @using Newtonsoft.Json
on top of chtml
page.
Download the map file and the uncompressed version of jQuery.
Put them with the minified version:
Include minified version into your HTML:
Check in Google Chrome:
Get familiar with Debugging JavaScript
If I understand you correctly, you need to use -SearchBase:
Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *
Note that Get-ADUser defaults to using
-SearchScope Subtree
so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).
Your PHP script (external file 'email.php') should look like this:
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];
//send email
mail("[email protected]", "51 Deep comment from" .$email, $message);
}
?>
Yes:
bigInt.sign = !(number < 0);
The !
operator always evaluates to true
or false
. When converted to int
, these become 1
and 0
respectively.
Of course this is equivalent to:
bigInt.sign = (number >= 0);
Here the parentheses are redundant but I add them for clarity. All of the comparison and relational operator evaluate to true
or false
.
Java's substring
method fails when you try and get a substring starting at an index which is longer than the string.
An easy alternative is to use Apache Commons StringUtils.substring
:
public static String substring(String str, int start)
Gets a substring from the specified String avoiding exceptions.
A negative start position can be used to start n characters from the end of the String.
A null String will return null. An empty ("") String will return "".
StringUtils.substring(null, *) = null
StringUtils.substring("", *) = ""
StringUtils.substring("abc", 0) = "abc"
StringUtils.substring("abc", 2) = "c"
StringUtils.substring("abc", 4) = ""
StringUtils.substring("abc", -2) = "bc"
StringUtils.substring("abc", -4) = "abc"
Parameters:
str - the String to get the substring from, may be null
start - the position to start from, negative means count back from the end of the String by this many characters
Returns:
substring from start position, null if null String input
Note, if you can't use Apache Commons lib for some reason, you could just grab the parts you need from the source
// Substring
//-----------------------------------------------------------------------
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start {@code n}
* characters from the end of the String.</p>
*
* <p>A {@code null} String will return {@code null}.
* An empty ("") String will return "".</p>
*
* <pre>
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
* StringUtils.substring("abc", 0) = "abc"
* StringUtils.substring("abc", 2) = "c"
* StringUtils.substring("abc", 4) = ""
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @return substring from start position, {@code null} if null String input
*/
public static String substring(final String str, int start) {
if (str == null) {
return null;
}
// handle negatives, which means last n characters
if (start < 0) {
start = str.length() + start; // remember start is negative
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return EMPTY;
}
return str.substring(start);
}
Just for the reference, if you work in scripts (batch processing), not in stored procedure, flushing output is triggered by the GO command, e.g.
print 'test'
print 'test'
go
In general, my conclusion is following: output of mssql script execution, executing in SMS GUI or with sqlcmd.exe, is flushed to file, stdoutput, gui window on first GO statement or until the end of the script.
Flushing inside of stored procedure functions differently, since you can not place GO inside.
Reference: tsql Go statement
None of those answers was not helpful for me.
Finally I have found reason and solution. The reason was a lot of CSS3 filters (filter, -webkit-filter).
Solution
I have added detection of WebView in web page script in order to add class "lowquality" to HTML body. BTW. You can easily track WebView by setting user-agent in WebView settings. Then I created new CSS rule
body.lowquality * { filter: none !important; }
like Answers above, if you do bootstrap 4 just add few line of css to .carousel , carousel-inner ,carousel-item and img as follows
.carousel .carousel-inner{
height:500px
}
.carousel-inner .carousel-item img{
min-height:200px;
//prevent it from stretch in screen size < than 768px
object-fit:cover
}
@media(max-width:768px){
.carousel .carousel-inner{
//prevent it from adding a white space between carousel and container elements
height:auto
}
}
You can try with the below commands:
hduser@master:~$ sudo /etc/init.d/mysql stop
[ ok ] Stopping mysql (via systemctl): mysql.service.
hduser@master:~$ sudo /etc/init.d/mysql start
[ ok ] Starting mysql (via systemctl): mysql.service.
To get the data of a specific field,
$form->get('fieldName')->getData();
Or for all the form data
$form->getData();
Link to docs: https://symfony.com/doc/2.7/forms.html
long millisecond = beginupd.getTime();
Date.getTime()
JavaDoc states:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
According to Apple's latest document You need to use
appStoreLink = "https://itunes.apple.com/us/app/apple-store/id375380948?mt=8"
or
SKStoreProductViewController
I know this is an old post, but I found it through Google, and after playing with it think I have an easier solution. If I'm wrong please point it out, 'cuz I'd like to know, but this worked for my purposes at least (It's based off of ICR's response):
for (int x = 0; x < array.GetLength(0); x++)
{
Console.Write(array[x, 0], array[x,1], array[x,2]);
}
Since the both dimensions are limited, either one can be simple numbers, and thus avoid a nested for loop. I admit I'm new to C#, so please, if there's a reason not to do it, please tell me...
instance.__class__.__name__
example:
>>> class A():
pass
>>> a = A()
>>> a.__class__.__name__
'A'
In Python 3.8 the dirs_exist_ok
keyword argument was added to shutil.copytree()
:
dirs_exist_ok
dictates whether to raise an exception in casedst
or any missing parent directory already exists.
So, the following will work in recent versions of Python, even if the destination directory already exists:
shutil.copytree(src, dest, dirs_exist_ok=True) # 3.8+ only!
One major benefit is that it's more flexible than distutils.dir_util.copy_tree()
as it takes additional arguments on files to ignore, etc. There is also a draft PEP (PEP 632, associated discussion), which suggests that distutils
may be deprecated and then removed in future versions of Python 3.
To access the memory of an object directly (to do a "core dump") you'll need to head into unsafe code.
If you want something more compact than BinaryWriter or a raw memory dump will give you, then you need to write some custom serialisation code that extracts the critical information from the object and packs it in an optimal way.
edit P.S. It's very easy to wrap the BinaryWriter approach into a DeflateStream to compress the data, which will usually roughly halve the size of the data.
If you have "something" and need 'something', use replace(col, "\"", "\'")
and viceversa.
You can do it like this:
SELECT * FROM ... WHERE name LIKE 'someone'
(It's not the solution, but in some cases is very convenient)
"The LIKE operator does a pattern matching comparison. The operand to the right contains the pattern, the left hand operand contains the string to match against the pattern. A percent symbol ("%") in the pattern matches any sequence of zero or more characters in the string. An underscore ("_") in the pattern matches any single character in the string. Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching). (A bug: SQLite only understands upper/lower case for ASCII characters. The LIKE operator is case sensitive for unicode characters that are beyond the ASCII range. For example, the expression 'a' LIKE 'A' is TRUE but 'æ' LIKE 'Æ' is FALSE.)."
This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
You can set application.properties
:
spring.jackson.default-property-inclusion=non_null
or application.yaml
:
spring:
jackson:
default-property-inclusion: non_null
http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
Seems like the problem is with the date format.
var d = "17-09-2013 10:08",
dArr = d.split('-'),
ts = new Date(dArr[1] + "-" + dArr[0] + "-" + dArr[2]).getTime(); // 1379392680000
As suggested by Guido García in their answer here:
import java.util.HashMap;
public class CaseInsensitiveMap extends HashMap<String, String> {
@Override
public String put(String key, String value) {
return super.put(key.toLowerCase(), value);
}
// not @Override because that would require the key parameter to be of type Object
public String get(String key) {
return super.get(key.toLowerCase());
}
}
Or