The PictureBox.Load(string url) method "sets the ImageLocation to the specified URL and displays the image indicated."
You can use this code:
def is_valid(string):
words = string.split('_')
for word in words:
if not word.istitle():
return False, word
return True, words
x="Alpha_beta_Gamma"
assert is_valid(x)==(False,'beta')
x="Alpha_Beta_Gamma"
assert is_valid(x)==(True,['Alpha', 'Beta', 'Gamma'])
This way you know if is valid and what word is wrong
It means
myclass *p = NULL;
*p = ...; // illegal: dereferencing NULL pointer
... = *p; // illegal: dereferencing NULL pointer
p->meth(); // illegal: equivalent to (*p).meth(), which is dereferencing NULL pointer
myclass *p = /* some legal, non-NULL pointer */;
*p = ...; // Ok
... = *p; // Ok
p->meth(); // Ok, if myclass::meth() exists
basically, almost anything involving (*p)
or implicitly involving (*p)
, e.g. p->...
which is a shorthand for (*p). ...
; except for pointer declaration.
I hate commenting on such a screwed up situation, but the easiest way to not rejigger all of your invariants is to create a phantom vertex in your graph that acts as a proxy back to the incestuous dad.
Example for Gradient Border
Using border-image css property
Credits to : border-image in Mozilla
.grad-border {_x000D_
height: 1px;_x000D_
width: 85%;_x000D_
margin: 0 auto;_x000D_
display: flex;_x000D_
}_x000D_
.left-border, .right-border {_x000D_
width: 50%;_x000D_
border-bottom: 2px solid #695f52;_x000D_
display: inline-block;_x000D_
}_x000D_
.left-border {_x000D_
border-image: linear-gradient(270deg, #b3b3b3, #fff) 1;_x000D_
}_x000D_
.right-border {_x000D_
border-image: linear-gradient(90deg, #b3b3b3, #fff) 1;_x000D_
}
_x000D_
<div class="grad-border">_x000D_
<div class="left-border"></div>_x000D_
<div class="right-border"></div>_x000D_
</div>
_x000D_
Try in this way -
public class SummaryMapActivity extends FragmentActivity implements LocationListener{
private GoogleMap mMap;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.summary_mapview);
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
mMap.setMyLocationEnabled(true);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
mMap.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
If you want optimize way means use TOP
Keyword, So the nth max and min salaries query as follows but the queries look like a tricky as in reverse order by using aggregate function names:
N maximum salary:
SELECT MIN(EmpSalary)
FROM Salary
WHERE EmpSalary IN(SELECT TOP N EmpSalary FROM Salary ORDER BY EmpSalary DESC)
for Ex: 3 maximum salary:
SELECT MIN(EmpSalary)
FROM Salary
WHERE EmpSalary IN(SELECT TOP 3 EmpSalary FROM Salary ORDER BY EmpSalary DESC)
N minimum salary:
SELECT MAX(EmpSalary)
FROM Salary
WHERE EmpSalary IN(SELECT TOP N EmpSalary FROM Salary ORDER BY EmpSalary ASC)
for Ex: 3 minimum salary:
SELECT MAX(EmpSalary)
FROM Salary
WHERE EmpSalary IN(SELECT TOP 3 EmpSalary FROM Salary ORDER BY EmpSalary ASC)
Dim myStringArray() As String
*code*
redim myStringArray(size_of_your_array)
Then you can do something static like this:
myStringArray = { item_1, item_2, ... }
Or something iterative like this:
Dim x
For x = 0 To size_of_your_array
myStringArray(x) = data_source(x).Name
Next x
This is what we called Composite Formatting of the .NET Framework to convert the value of an object to its text representation and embed that representation in a string. The resulting string is written to the output stream.
The overloaded Console.WriteLine Method (String, Object)Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.
Did you try using the UIButton
from the Interface builder (that has rounded corners) and experimenting with the settings to make it look like a label. if all you want is to display static text within.
with open('file.txt', 'r') as searchfile:
for line in searchfile:
if 'searchphrase' in line:
print line
With apologies to senderle who I blatantly copied.
type=submit
it is a Submit Button type=button
it is just a button, It does not submit your form inputs. and also you don't want to use both of these
You can use echo and prefix "\033", simple:
Artisan::command('mycommand', function () {
echo "\033======== Start ========\n";
});
And change color text:
if (App::environment() === 'production') {
echo "\033[0;33m======== WARNING ========\033[0m\n";
}
Here is a more modern way of doing this:
name1 : str = input("What's your name? ")
age1 : int = int(input ("how old are you? "))
twentyone : int = 21 - age1
print('Hi, {}, you will be 21 in: {} years'.format(name1, twentyone))
From what I can tell, per the documentation here: http://jqueryui.com/demos/tabs/#event-select, it seems as though you're not quite initializing it right. The demos state that you need a main wrapped <div>
element, with a <ul>
or possibly <ol>
element representing the tabs, and then an element for each tab page (presumable a <div>
or <p>
, possibly a <section>
if we're using HTML5). Then you call $().tabs() on the main <div>
, not the <ul>
element.
After that, you can bind to the tabsselect event no problem. Check out this fiddle for basic, basic example:
Try this
Sub Txt2Col()
Dim rng As Range
Set rng = [C7]
Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))
rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings
Update: button click event to act on another sheet
Private Sub CommandButton1_Click()
Dim rng As Range
Dim sh As Worksheet
Set sh = Worksheets("Sheet2")
With sh
Set rng = .[C7]
Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))
rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=True,
Space:=False,
Other:=False, _
FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
TrailingMinusNumbers:=True
End With
End Sub
Note the .
's (eg .Range
) they refer to the With
statement object
Ideally, there should only be two scenarios of when an iOS application would need to accept an un-trusted certificate.
Scenario A: You are connected to a test environment which is using a self-signed certificate.
Scenario B: You are Proxying HTTPS
traffic using a MITM Proxy like Burp Suite, Fiddler, OWASP ZAP, etc.
The Proxies will return a certificate signed by a self-signed CA so that the proxy is able to capture HTTPS
traffic.
Production hosts should never use un-trusted certificates for obvious reasons.
If you need to have the iOS simulator accept an un-trusted certificate for testing purposes it is highly recommended that you do not change application logic in order disable the built in certificate validation provided by the NSURLConnection
APIs. If the application is released to the public without removing this logic, it will be susceptible to man-in-the-middle attacks.
The recommended way to accept un-trusted certificates for testing purposes is to import the Certificate Authority(CA) certificate which signed the certificate onto your iOS Simulator or iOS device. I wrote up a quick blog post which demonstrates how to do this which an iOS Simulator at:
For those who use Visual Assist, vertical guidelines can be enabled from Display
section in Visual Assist's options:
Here's my approach to achieve this behavior.
For a more comprehensive solution involving ILookup<TKey, TElement>
, check out my other answer.
public abstract class Lookup<TKey, TElement> : KeyedCollection<TKey, ICollection<TElement>>
{
protected override TKey GetKeyForItem(ICollection<TElement> item) =>
item
.Select(b => GetKeyForItem(b))
.Distinct()
.SingleOrDefault();
protected abstract TKey GetKeyForItem(TElement item);
public void Add(TElement item)
{
var key = GetKeyForItem(item);
if (Dictionary != null && Dictionary.TryGetValue(key, out var collection))
collection.Add(item);
else
Add(new List<TElement> { item });
}
public void Remove(TElement item)
{
var key = GetKeyForItem(item);
if (Dictionary != null && Dictionary.TryGetValue(key, out var collection))
{
collection.Remove(item);
if (collection.Count == 0)
Remove(key);
}
}
}
Usage:
public class Item
{
public string Key { get; }
public string Value { get; set; }
public Item(string key, string value = null) { Key = key; Value = value; }
}
public class Lookup : Lookup<string, Item>
{
protected override string GetKeyForItem(Item item) => item.Key;
}
static void Main(string[] args)
{
var toRem = new Item("1", "different");
var single = new Item("2", "single");
var lookup = new Lookup()
{
new Item("1", "hello"),
new Item("1", "hello2"),
new Item(""),
new Item("", "helloo"),
toRem,
single
};
lookup.Remove(toRem);
lookup.Remove(single);
}
Note: the key must be immutable (or remove and re-add upon key-change).
arrOfObj.map(o => {
o.isActive = true;
return o;
});
I know this is an old post however thought I'd throw my simple solution into the mix since no one has suggested it.
I use the current directory to determine the current environment then flip the connection string and environment variable. This works great so long as you have a naming convention for your site folders such as test/beta/sandbox.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var dir = Environment.CurrentDirectory;
string connectionString;
if (dir.Contains("test", StringComparison.OrdinalIgnoreCase))
{
connectionString = new ConnectionStringBuilder(server: "xxx", database: "xxx").ConnectionString;
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
}
else
{
connectionString = new ConnectionStringBuilder(server: "xxx", database: "xxx").ConnectionString;
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Production");
}
optionsBuilder.UseSqlServer(connectionString);
optionsBuilder.UseLazyLoadingProxies();
optionsBuilder.EnableSensitiveDataLogging();
}
The header()
function in PHP does this, but make sure that you call it before any other file contents are sent to the browser or else you will receive an error.
JavaScript is an alternative if you have already sent the file contents.
You are POSTing the json incorrectly -- but even if it were correct, you would not be able to test using print_r($_POST)
(read why here). Instead, on your second page, you can nab the incoming request using file_get_contents("php://input")
, which will contain the POSTed json. To view the received data in a more readable format, try this:
echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';
In your code, you are indicating Content-Type:application/json
, but you are not json-encoding all of the POST data -- only the value of the "customer" POST field. Instead, do something like this:
$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( array( "customer"=> $data ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
echo "<pre>$result</pre>";
Sidenote: You might benefit from using a third-party library instead of interfacing with the Shopify API directly yourself.
on delete button click event
public void delete(View v){
ListView listview1;
ArrayList<E> datalist;
final int position = listview1.getPositionForView((View) v.getParent());
datalist.remove(position);
myAdapter.notifyDataSetChanged();
}
EUREKA I found it!
With the current Studio 1.3 each project has a local.properties
file where you can edit the SDK!
You can use npm link to create a symbolic link to your global package in your projects folder.
Example:
$ npm install -g express
$ cd [local path]/project
$ npm link express
All it does is create a local node_modules folder and then create a symlink express -> [global directory]/node_modules/express which can then be resolved by require('express')
(function(window) {
var proxied = window.alert;
window.alert = function() {
return proxied.apply(window, arguments);
};
}(this));
alert(13, 37);
This issue happened when I accidently renamed the line
apply plugin: 'com.android.application'
on file app/build.gradle
to some other name. So, I fixed it by changing it to what it was.
Use this function to get the client MAC address:
function GetClientMac(){
$macAddr=false;
$arp=`arp -n`;
$lines=explode("\n", $arp);
foreach($lines as $line){
$cols=preg_split('/\s+/', trim($line));
if ($cols[0]==$_SERVER['REMOTE_ADDR']){
$macAddr=$cols[2];
}
}
return $macAddr;
}
How are you loading the values into the drop down list or determining which value to select? If you are doing this using Ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.
If you are using one of jQuery's Ajax methods, you can specify a callback function and then put $("._statusDDL").val(2);
into your callback function.
This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it took longer than 300 ms.
Confirm answer Ondrej Skopek
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.slf4j.LoggerFactory;
var rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(Level.TRACE);
You will get result:
2020-05-14 14:01:16,644 TRACE [] [o.a.k.c.m.Metrics] Test worker Registered metric named MetricName [name=bufferpool-wait-time-total, group=producer-metrics, description=The total time an appender waits for space allocation., tags={client-id=producer-2}]
Here http://www.alteridem.net/2007/08/22/the-yield-statement-in-c/ is very good example:
public static IEnumerable<int> Range( int min, int max ) { while ( true ) { if ( min >= max ) { yield break; } yield return min++; } }
and explanation, that if a yield break
statement is hit within a method, execution of that method stops with no return. There are some time situations, when you don't want to give any result, then you can use yield break.
That method must be called on the Dispose
method of objects that implements the IDisposable
, in this way the GC wouldn't call the finalizer another time if someones calls the Dispose
method.
If you've got pagination you also sort the data by some key. Why not let API clients include the key of the last element of the previously returned collection in the URL and add a WHERE
clause to your SQL query (or something equivalent, if you're not using SQL) so that it returns only those elements for which the key is greater than this value?
Yes, I just solved the problem today.
Then you can choose the SDK like below :
Hope this helps you.
Starting git 1.8.5 (Q4 2013), you will be able to "use a Git command, but without having to change directories".
Just like "
make -C <directory>
", "git -C <directory> ...
" tells Git to go there before doing anything else.
See commit 44e1e4 by Nazri Ramliy:
It takes more keypresses to invoke Git command in a different directory without leaving the current directory:
(cd ~/foo && git status)
git --git-dir=~/foo/.git --work-tree=~/foo status
GIT_DIR=~/foo/.git GIT_WORK_TREE=~/foo git status(cd ../..; git grep foo)
for d in d1 d2 d3; do (cd $d && git svn rebase); done
The methods shown above are acceptable for scripting but are too cumbersome for quick command line invocations.
With this new option, the above can be done with fewer keystrokes:
git -C ~/foo status
git -C ../.. grep foo
for d in d1 d2 d3; do git -C $d svn rebase; done
Since Git 2.3.4 (March 2015), and commit 6a536e2 by Karthik Nayak (KarthikNayak
), git
will treat "git -C '<path>'
" as a no-op when <path>
is empty.
'
git -C ""
' unhelpfully dies with error "Cannot change to ''
", whereas the shell treats cd ""' as a no-op.
Taking the shell's behavior as a precedent, teachgit
to treat -C ""' as a no-op, as well.
4 years later, Git 2.23 (Q3 2019) documents that 'git -C ""
' works and doesn't change directory
It's been behaving so since 6a536e2 (
git
: treat "git -C '<path>'
" as a no-op when<path>
is empty, 2015-03-06, Git v2.3.4).
That means the documentation now (finally) includes:
If '
<path>
' is present but empty, e.g.-C ""
, then the current working directory is left unchanged.
You can see git -C
used with Git 2.26 (Q1 2020), as an example.
See commit b441717, commit 9291e63, commit 5236fce, commit 10812c2, commit 62d58cd, commit b87b02c, commit 9b92070, commit 3595d10, commit f511bc0, commit f6041ab, commit f46c243, commit 99c049b, commit 3738439, commit 7717242, commit b8afb90 (20 Dec 2019) by Denton Liu (Denton-L
).
(Merged by Junio C Hamano -- gitster
-- in commit 381e8e9, 05 Feb 2020)
t1507
: inlinefull_name()
Signed-off-by: Denton Liu
Before, we were running
test_must_fail full_name
. However,test_must_fail
should only be used on git commands.
Inlinefull_name()
so that we can usetest_must_fail
on thegit
command directly.When
full_name()
was introduced in 28fb84382b ("Introduce<branch>@{upstream}
notation", 2009-09-10, Git v1.7.0-rc0 -- merge), thegit -C
option wasn't available yet (since it was introduced in 44e1e4d67d ("git
: run in a directory given with -C option", 2013-09-09, Git v1.8.5-rc0 -- merge listed in batch #5)).
As a result, the helper function removed the need to manuallycd
each time. However, sincegit -C
is available now, we can just use that instead and inlinefull_name()
.
Try this:
Date date = new Date(logEvent.timeSTamp);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateFormatted = formatter.format(date);
See SimpleDateFormat for a description of other format strings that the class accepts.
See runnable example using input of 1200 ms.
I've been looking for an easy to use tool for this type of testing for a while now. I just came across this the other day: Network Delay Simulator
If you're running Windows, you should check it out. It was super easy to set up and get going, and seems to work really well. It allows you to define bandwidth, latency, and packet loss in each direction. The other really nice thing is that you can define "Flow Match Conditions" so that it only affects the traffic you want it to. Oh yeah, and it's free.
It's Varargs :)
The varargs short for variable-length arguments is a feature that allows the method to accept variable number of arguments (zero or more). With varargs it has become simple to create methods that need to take a variable number of arguments. The feature of variable argument has been added in Java 5.
Syntax of varargs
A vararg is secified by three ellipsis (three dots) after the data type, its general form is
return_type method_name(data_type ... variableName){
}
Need for varargs
Prior to Java 5, in case there was a need of variable number of arguments, there were two ways to handle it
If the max number of arguments, a method can take was small and known, then overloaded versions of the method could be created. If the maximum number of arguments a method could take was large or/and unknown then the approach was to put those arguments in an array and pass them to a method which takes array as a parameter. These 2 approaches were error-prone - constructing an array of parameters every time and difficult to maintain - as the addition of new argument may result in writing a new overloaded method.
Advantages of varargs
Offers a much simpler option. Less code as no need to write overloaded methods.
Example of varargs
public class VarargsExample {
public void displayData(String ... values){
System.out.println("Number of arguments passed " + values.length);
for(String s : values){
System.out.println(s + " ");
}
}
public static void main(String[] args) {
VarargsExample vObj = new VarargsExample();
// four args
vObj.displayData("var", "args", "are", "passed");
//three args
vObj.displayData("Three", "args", "passed");
// no-arg
vObj.displayData();
}
}
Output
Number of arguments passed 4
var
args
are
passed
Number of arguments passed 3
Three
args
passed
Number of arguments passed 0
It can be seen from the program that length is used here to find the number of arguments passed to the method. It is possible because varargs are implicitly passed as an array. Whatever arguments are passed as varargs are stored in an array which is referred by the name given to varargs. In this program array name is values. Also note that method is called with different number of argument, first call with four arguments, then three arguments and then with zero arguments. All these calls are handled by the same method which takes varargs.
Restriction with varargs
It is possible to have other parameters with varargs parameter in a method, however in that case, varargs parameter must be the last parameter declared by the method.
void displayValues(int a, int b, int … values) // OK
void displayValues(int a, int b, int … values, int c) // compiler error
Another restriction with varargs is that there must be only one varargs parameter.
void displayValues(int a, int b, int … values, int … moreValues) // Compiler error
Overloading varargs Methods
It is possible to overload a method that takes varargs parameter. Varargs method can be overloaded by -
Types of its vararg parameter can be different. By adding other parameters. Example of overloading varargs method
public class OverloadingVarargsExp {
// Method which has string vararg parameter
public void displayData(String ... values){
System.out.println("Number of arguments passed " + values.length);
for(String s : values){
System.out.println(s + " ");
}
}
// Method which has int vararg parameter
public void displayData(int ... values){
System.out.println("Number of arguments passed " + values.length);
for(int i : values){
System.out.println(i + " ");
}
}
// Method with int vararg and one more string parameter
public void displayData(String a, int ... values){
System.out.println(" a " + a);
System.out.println("Number of arguments passed " + values.length);
for(int i : values){
System.out.println(i + " ");
}
}
public static void main(String[] args) {
OverloadingVarargsExp vObj = new OverloadingVarargsExp();
// four string args
vObj.displayData("var", "args", "are", "passed");
// two int args
vObj.displayData(10, 20);
// One String param and two int args
vObj.displayData("Test", 20, 30);
}
}
Output
Number of arguments passed 4
var
args
are
passed
Number of arguments passed 2
10
20
a Test
Number of arguments passed 2
20
30
Varargs and overloading ambiguity
In some cases call may be ambiguous while we have overloaded varargs method. Let's see an example
public class OverloadingVarargsExp {
// Method which has string vararg parameter
public void displayData(String ... values){
System.out.println("Number of arguments passed " + values.length);
for(String s : values){
System.out.println(s + " ");
}
}
// Method which has int vararg parameter
public void displayData(int ... values){
System.out.println("Number of arguments passed " + values.length);
for(int i : values){
System.out.println(i + " ");
}
}
public static void main(String[] args) {
OverloadingVarargsExp vObj = new OverloadingVarargsExp();
// four string args
vObj.displayData("var", "args", "are", "passed");
// two int args
vObj.displayData(10, 20);
// This call is ambiguous
vObj.displayData();
}
}
In this program when we make a call to displayData() method without any parameter it throws error, because compiler is not sure whether this method call is for displayData(String ... values)
or displayData(int ... values)
Same way if we have overloaded methods where one has the vararg
method of one type and another method has one parameter and vararg
parameter of the same type, then also we have the ambiguity -
As Exp -
displayData(int ... values)
and displayData(int a, int ... values)
These two overloaded methods will always have ambiguity.
Set it in the JAVA_OPTS
variable in [path to tomcat]/bin/catalina.sh. Under windows there is a console where you can set it up or you use the catalina.bat.
JAVA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5
To set value in the ComboBox
cmbEmployeeStatus.Text="Something";
Note that if the object you are talking about has a custom property model (such as DataRowView
etc for DataTable
), then you need to use TypeDescriptor
; the good news is that this still works fine for regular classes (and can even be much quicker than reflection):
foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) {
Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj));
}
This also provides easy access to things like TypeConverter
for formatting:
string fmt = prop.Converter.ConvertToString(prop.GetValue(obj));
I had the same issue with a Java application using tibco dll originally intended to run on Win XP. To get it to work on Windows 7, I made the application point to 32-bit JRE. Waiting to see if there is another solution.
With the option FollowSymLinks enabled:
$ rg "FollowSymLinks" /etc/httpd/
/etc/httpd/conf/httpd.conf
269: Options Indexes FollowSymLinks
you need all the directories in symlink to be executable by the user httpd is using.
so for this general use case:
cd /path/to/your/web
sudo ln -s $PWD /srv/http/
You can check owner an permissions with namei:
$ namei -m /srv/http/web
f: /srv/http/web
drwxr-xr-x /
drwxr-xr-x srv
drwxr-xr-x http
lrwxrwxrwx web -> /path/to/your/web
drwxr-xr-x /
drwxr-xr-x path
drwx------ to
drwxr-xr-x your
drwxr-xr-x web
In my case to
directory was only executable for my user:
Enable execution by others solve it:
chmod o+x /path/to
See the non executable directory could be different, or you need to affect groups instead others, that depends on your case.
As Grodriguez says, Integer
objects are immutable. The problem here is that you're trying to increment the int
value of the player ID rather than the ID itself. In Java 5+, you can just write playerID++
.
As a side note, never ever call Integer
's constructor. Take advantage of autoboxing by just assigning int
s to Integer
s directly, like Integer foo = 5
. This will use Integer.valueOf(int)
transparently, which is superior to the constructor because it doesn't always have to create a new object.
You can create a button in window1 and double click on it. It will create a new click handler, where inside you can write something like this:
var window2 = new Window2();
window2.Show();
Given this .env
file:
DB_NAME=foo
DB_USER=bar
DB_PASSWORD=baz
And this mongo-init.sh
file:
mongo --eval "db.auth('$MONGO_INITDB_ROOT_USERNAME', '$MONGO_INITDB_ROOT_PASSWORD'); db = db.getSiblingDB('$DB_NAME'); db.createUser({ user: '$DB_USER', pwd: '$DB_PASSWORD', roles: [{ role: 'readWrite', db: '$DB_NAME' }] });"
This docker-compose.yml
will create the admin database and admin user, authenticate as the admin user, then create the real database and add the real user:
version: '3'
services:
# app:
# build: .
# env_file: .env
# environment:
# DB_HOST: 'mongodb://mongodb'
mongodb:
image: mongo:4
environment:
MONGO_INITDB_ROOT_USERNAME: admin-user
MONGO_INITDB_ROOT_PASSWORD: admin-password
DB_NAME: $DB_NAME
DB_USER: $DB_USER
DB_PASSWORD: $DB_PASSWORD
ports:
- 27017:27017
volumes:
- db-data:/data/db
- ./mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh
volumes:
db-data:
You will need to define the repository outside of buildscript
. The buildscript
configuration block only sets up the repositories and dependencies for the classpath of your build script but not your application.
For posterity, I think this is quicker:
a = np.array([np.array(list()) for _ in y])
You might even be able to pass in a generator (i.e. [] -> ()), in which case the inner list is never fully stored in memory.
Responding to comment below:
>>> import numpy as np
>>> y = range(10)
>>> a = np.array([np.array(list) for _ in y])
>>> a
array([array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object)], dtype=object)
If you want to find out whether a whole word is in a space-separated list of words, simply use:
def contains_word(s, w):
return (' ' + w + ' ') in (' ' + s + ' ')
contains_word('the quick brown fox', 'brown') # True
contains_word('the quick brown fox', 'row') # False
This elegant method is also the fastest. Compared to Hugh Bothwell's and daSong's approaches:
>python -m timeit -s "def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ')" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 0.351 usec per loop
>python -m timeit -s "import re" -s "def contains_word(s, w): return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search(s)" "contains_word('the quick brown fox', 'brown')"
100000 loops, best of 3: 2.38 usec per loop
>python -m timeit -s "def contains_word(s, w): return s.startswith(w + ' ') or s.endswith(' ' + w) or s.find(' ' + w + ' ') != -1" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 1.13 usec per loop
Edit: A slight variant on this idea for Python 3.6+, equally fast:
def contains_word(s, w):
return f' {w} ' in f' {s} '
An empty string is a string with zero length or no character.
Null
is absence of data.
var TableIDvalue = "myTable";_x000D_
var TableLastSortedColumn = -1;_x000D_
_x000D_
function SortTable() {_x000D_
var sortColumn = parseInt(arguments[0]);_x000D_
var type = arguments.length > 1 ? arguments[1] : 'T';_x000D_
var dateformat = arguments.length > 2 ? arguments[2] : '';_x000D_
var table = document.getElementById(TableIDvalue);_x000D_
var tbody = table.getElementsByTagName("tbody")[0];_x000D_
var rows = tbody.getElementsByTagName("tr");_x000D_
_x000D_
var arrayOfRows = new Array();_x000D_
_x000D_
type = type.toUpperCase();_x000D_
_x000D_
dateformat = dateformat.toLowerCase();_x000D_
_x000D_
for (var i = 0, len = rows.length; i < len; i++) {_x000D_
arrayOfRows[i] = new Object;_x000D_
arrayOfRows[i].oldIndex = i;_x000D_
var celltext = rows[i].getElementsByTagName("td")[sortColumn].innerHTML.replace(/<[^>]*>/g, "");_x000D_
if (type == 'D') {_x000D_
arrayOfRows[i].value = GetDateSortingKey(dateformat, celltext);_x000D_
} else {_x000D_
var re = type == "N" ? /[^\.\-\+\d]/g : /[^a-zA-Z0-9]/g;_x000D_
arrayOfRows[i].value = celltext.replace(re, "").substr(0, 25).toLowerCase();_x000D_
}_x000D_
}_x000D_
_x000D_
if (sortColumn == TableLastSortedColumn) {_x000D_
arrayOfRows.reverse();_x000D_
} else {_x000D_
TableLastSortedColumn = sortColumn;_x000D_
switch (type) {_x000D_
case "N":_x000D_
arrayOfRows.sort(CompareRowOfNumbers);_x000D_
break;_x000D_
case "D":_x000D_
arrayOfRows.sort(CompareRowOfNumbers);_x000D_
break;_x000D_
default:_x000D_
arrayOfRows.sort(CompareRowOfText);_x000D_
}_x000D_
}_x000D_
var newTableBody = document.createElement("tbody");_x000D_
_x000D_
for (var i = 0, len = arrayOfRows.length; i < len; i++) {_x000D_
newTableBody.appendChild(rows[arrayOfRows[i].oldIndex].cloneNode(true));_x000D_
}_x000D_
table.replaceChild(newTableBody, tbody);_x000D_
}_x000D_
_x000D_
function CompareRowOfText(a, b) {_x000D_
var aval = a.value;_x000D_
var bval = b.value;_x000D_
return (aval == bval ? 0 : (aval > bval ? 1 : -1));_x000D_
}_x000D_
_x000D_
function deleteRow(i) {_x000D_
document.getElementById('myTable').deleteRow(i)_x000D_
}
_x000D_
<table id="myTable" border="1">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>_x000D_
<input type="button" onclick="javascript: SortTable(0, 'T');" value="SORT" /></th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Shaa</td>_x000D_
<td>ABC</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cnubha</td>_x000D_
<td>XYZ</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Fine</td>_x000D_
<td>MNO</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Amit</td>_x000D_
<td>PQR</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Sultan</td>_x000D_
<td>FGH</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Hello</td>_x000D_
<td>UST</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
_x000D_
</tbody>_x000D_
</table>
_x000D_
You should be able to use the "client.ResponseHeaders[..]" call, see this link for examples of getting stuff back from the response
What's wrong with
func (e *Easy)SetStringOption(option Option, param string)
func (e *Easy)SetLongOption(option Option, param long)
and so on?
Problem I found in Windows server 2016 was that the permissions were wrong on the temp directory used by PHP. I added IUSR.
For the record, none of the aforementioned Git Python libraries seem to contain a "git status" equivalent, which is really the only thing I would want since dealing with the rest of the git commands via subprocess is so easy.
KeyboardInterrupt and signals are only seen by the process (ie the main thread)... Have a look at Ctrl-c i.e. KeyboardInterrupt to kill threads in python
in your question, both buffer and byteArray seem to be byte[]. So:
ImageElement image = ImageElement.FromBinary(buffer);
CSS:
html,
body {
height: 100%;
}
.container {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
HTML:
<div class="container">
<div>
example
</div>
</div>
For Word Wrapping in Php Storm 1. Select File from the menu 2. From File select setting 3. From setting select Editor 4. Select General from Editor 5. In general checked Use soft wraps in editor from Soft wraps section
Here is how to integrate CSS star rating into an HTML form without using javascript (only html and css):
CSS:
.txt-center {
text-align: center;
}
.hide {
display: none;
}
.clear {
float: none;
clear: both;
}
.rating {
width: 90px;
unicode-bidi: bidi-override;
direction: rtl;
text-align: center;
position: relative;
}
.rating > label {
float: right;
display: inline;
padding: 0;
margin: 0;
position: relative;
width: 1.1em;
cursor: pointer;
color: #000;
}
.rating > label:hover,
.rating > label:hover ~ label,
.rating > input.radio-btn:checked ~ label {
color: transparent;
}
.rating > label:hover:before,
.rating > label:hover ~ label:before,
.rating > input.radio-btn:checked ~ label:before,
.rating > input.radio-btn:checked ~ label:before {
content: "\2605";
position: absolute;
left: 0;
color: #FFD700;
}
HTML:
<div class="txt-center">
<form>
<div class="rating">
<input id="star5" name="star" type="radio" value="5" class="radio-btn hide" />
<label for="star5">?</label>
<input id="star4" name="star" type="radio" value="4" class="radio-btn hide" />
<label for="star4">?</label>
<input id="star3" name="star" type="radio" value="3" class="radio-btn hide" />
<label for="star3">?</label>
<input id="star2" name="star" type="radio" value="2" class="radio-btn hide" />
<label for="star2">?</label>
<input id="star1" name="star" type="radio" value="1" class="radio-btn hide" />
<label for="star1">?</label>
<div class="clear"></div>
</div>
</form>
</div>
Please check the demo
Try this:
function createcodes() {
$('.authors-list tr').each(function () {
//processing this row
//how to process each cell(table td) where there is checkbox
$(this).find('td input:checked').each(function () {
// it is checked, your code here...
});
});
}
I faced this issue too. I was using jquery.poptrox.min.js
for image popping and zooming and I received an error which said:
“Uncaught TypeError: a.indexOf is not a function” error.
This is because indexOf
was not supported in 3.3.1/jquery.min.js
so a simple fix to this is to change it to an old version 2.1.0/jquery.min.js
.
This fixed it for me.
Original article: https://helpdeskgeek.com/networking/simulate-slow-internet-connection-testing/
Simulate Slow Connection using Chrome Go ahead and install Chrome if you don’t already have it installed on your system. Once you do, open a new tab and then press CTRL + SHIFT + I to open the developer tools window or click on the hamburger icon, then More tools and then Developer tools.
This will bring up the Developer Tools window, which will probably be docked on the right side of the screen. I prefer it docked at the bottom of the screen since you can see more data. To do this, click on the three vertical dots and then click on the middle dock position.
Now go ahead and click on the Network tab. On the right, you should see a label called No Throttling.
If you click on that, you’ll get a dropdown list of a pre-configured speed that you can use to simulate a slow connection.
The choices range from Offline to WiFi and the numbers are shown as Latency, Download, Upload. The slowest is GPRS followed by Regular 2G, then Good 2G, then Regular 3G, Good 3G, Regular 4G, DSL and then WiFi. Pick one of the options and then reload the page you are on or type in another URL in the address bar. Just make sure you are in the same tab where the developer tools are being displayed. The throttling only works for the tab you have it enabled for.
If you want to use your own specific values, you can click the Add button under Custom. Click on the Add Custom Profile button to add a new profile.
When using GPRS, it took www.google.com a whopping 16 seconds to load! Overall, this is a great tool that is built right into Chrome that you can use for testing your website load time on slower connections. If you have any questions, feel free to comment. Enjoy!
If you don't have the correct .map file and you don't want to edit lines in bootstrap.css you can create a dummy .map file.
In my case I was seeing the error:
GET /bootstrap.css.map not found.
So I created an empty bootstrap.css.map in the /public directory and the error stopped.
I got this error for another reason. I was mistaking adding both the v4 AND the v13 support library. This was not necessary for me since my minSdkVersion is 15.
I fixed it by only including the v13 support library. Also, make sure to check mark the library in your exported library build path in eclipse. I also moved it to the top.
If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.
$('#note').find('#textid');
You can also use jQuery selectors to basically achieve the same thing:
$('#note #textid');
Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.
On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.
Update 2020.03.10
It's a breeze to use native JS for this:
document.querySelector('#note #textid');
If you want to first find #note
then #textid
you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(
var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;
Here's another, simpler solution (underline's width is not most accurate but it was good enough for me)
I have a UIView (_view_underline)
that has White background, height of 1 pixel and I update its width everytime I update the text
// It's a shame you have to do custom stuff to underline text
- (void) underline {
float width = [[_txt_title text] length] * 10.0f;
CGRect prev_frame = [_view_underline frame];
prev_frame.size.width = width;
[_view_underline setFrame:prev_frame];
}
When you're doing this
var model = @Html.Raw(Json.Encode(Model));
You're probably getting a JSON string, and not a JavaScript object.
You need to parse it in to an object:
var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);
You can use async/await
for this. I would explain more, but there's nothing really to it. It's just a regular for
loop but I added the await
keyword before the construction of your Promise
What I like about this is your Promise can resolve a normal value instead of having a side effect like your code (or other answers here) include. This gives you powers like in The Legend of Zelda: A Link to the Past where you can affect things in both the Light World and the Dark World – ie, you can easily work with data before/after the Promised data is available without having to resort to deeply nested functions, other unwieldy control structures, or stupid IIFEs.
// where DarkWorld is in the scary, unknown future
// where LightWorld is the world we saved from Ganondorf
LightWorld ... await DarkWorld
So here's what that will look like ...
const someProcedure = async n =>_x000D_
{_x000D_
for (let i = 0; i < n; i++) {_x000D_
const t = Math.random() * 1000_x000D_
const x = await new Promise(r => setTimeout(r, t, i))_x000D_
console.log (i, x)_x000D_
}_x000D_
return 'done'_x000D_
}_x000D_
_x000D_
someProcedure(10).then(x => console.log(x)) // => Promise_x000D_
// 0 0_x000D_
// 1 1_x000D_
// 2 2_x000D_
// 3 3_x000D_
// 4 4_x000D_
// 5 5_x000D_
// 6 6_x000D_
// 7 7_x000D_
// 8 8_x000D_
// 9 9_x000D_
// done
_x000D_
See how we don't have to deal with that bothersome .then
call within our procedure? And async
keyword will automatically ensure that a Promise
is returned, so we can chain a .then
call on the returned value. This sets us up for great success: run the sequence of n
Promises, then do something important – like display a success/error message.
In addition to Fuji's response, we can make the handler reusable turning it into an attached property:
public static class HyperlinkExtensions
{
public static bool GetIsExternal(DependencyObject obj)
{
return (bool)obj.GetValue(IsExternalProperty);
}
public static void SetIsExternal(DependencyObject obj, bool value)
{
obj.SetValue(IsExternalProperty, value);
}
public static readonly DependencyProperty IsExternalProperty =
DependencyProperty.RegisterAttached("IsExternal", typeof(bool), typeof(HyperlinkExtensions), new UIPropertyMetadata(false, OnIsExternalChanged));
private static void OnIsExternalChanged(object sender, DependencyPropertyChangedEventArgs args)
{
var hyperlink = sender as Hyperlink;
if ((bool)args.NewValue)
hyperlink.RequestNavigate += Hyperlink_RequestNavigate;
else
hyperlink.RequestNavigate -= Hyperlink_RequestNavigate;
}
private static void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
}
And use it like this:
<TextBlock>
<Hyperlink NavigateUri="https://stackoverflow.com"
custom:HyperlinkExtensions.IsExternal="true">
Click here
</Hyperlink>
</TextBlock>
While only a few lines are required to plot multiple/overlapping histograms in ggplot2, the results are't always satisfactory. There needs to be proper use of borders and coloring to ensure the eye can differentiate between histograms.
The following functions balance border colors, opacities, and superimposed density plots to enable the viewer to differentiate among distributions.
Single histogram:
plot_histogram <- function(df, feature) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)))) +
geom_histogram(aes(y = ..density..), alpha=0.7, fill="#33AADE", color="black") +
geom_density(alpha=0.3, fill="red") +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
print(plt)
}
Multiple histogram:
plot_multi_histogram <- function(df, feature, label_column) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)), fill=eval(parse(text=label_column)))) +
geom_histogram(alpha=0.7, position="identity", aes(y = ..density..), color="black") +
geom_density(alpha=0.7) +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
plt + guides(fill=guide_legend(title=label_column))
}
Usage:
Simply pass your data frame into the above functions along with desired arguments:
plot_histogram(iris, 'Sepal.Width')
plot_multi_histogram(iris, 'Sepal.Width', 'Species')
The extra parameter in plot_multi_histogram is the name of the column containing the category labels.
We can see this more dramatically by creating a dataframe with many different distribution means:
a <-data.frame(n=rnorm(1000, mean = 1), category=rep('A', 1000))
b <-data.frame(n=rnorm(1000, mean = 2), category=rep('B', 1000))
c <-data.frame(n=rnorm(1000, mean = 3), category=rep('C', 1000))
d <-data.frame(n=rnorm(1000, mean = 4), category=rep('D', 1000))
e <-data.frame(n=rnorm(1000, mean = 5), category=rep('E', 1000))
f <-data.frame(n=rnorm(1000, mean = 6), category=rep('F', 1000))
many_distros <- do.call('rbind', list(a,b,c,d,e,f))
Passing data frame in as before (and widening chart using options):
options(repr.plot.width = 20, repr.plot.height = 8)
plot_multi_histogram(many_distros, 'n', 'category')
robocopy seems to be the most versatile. See it's other options in the help
robocopy /?
robocopy SRC DST /E /MOV
Partial solution: for a single string column
tmp = df['A1'].fillna(''); isEmpty = tmp==''
gives boolean Series of True where there are empty strings or NaN values.
@Kendall
I tested your code and made some improvements, now it is even faster. I also tested with @???? ???????? code, this is also faster than his code.
long long int FindDivisors(long long int n) {
long long int count = 0;
long long int i, m = (long long int)sqrt(n);
for(i = 1;i <= m;i++) {
if(n % i == 0)
count += 2;
}
if(n / m == m && n % m == 0)
count--;
return count;
}
I am assuming that you are using a C99 compiler (with support for dynamically sized arrays). The problem in your code is that at the time when the compilers sees your variable declaration it cannot know how many elements there are in the array (I am also assuming here, from the compiler error that length
is not a compile time constant).
You must manually initialize that array:
int boardAux[length][length];
memset( boardAux, 0, length*length*sizeof(int) );
IMHO what the best solution is depends to some extent on how you store time in the rest of the database (and the rest of your application)
Personally I have worked with SQLite and try to always use unix timestamps for storing absolute time, so when dealing with the time of day (like you ask for) I do what Glen Solsberry writes in his answer and store the number of seconds since midnight
When taking this general approach people (including me!) reading the code are less confused if I use the same standard everywhere
you can simply use react-native-rename npm package.
Install using
npm install react-native-rename -g
Then from the root of your React Native project execute the following
react-native-rename "MyApp" -b com.mycompany.myapp
react-native-rename on npm
but notice that, this lib remove your MainActivity.java
and MainApplication.java
.
before changing your package name, give a backup from this two file and, after changing package name just put it back to their place. this solution work for me
more info: react-native-rename
Try to surround the path with quotes, and remove the spaces
export PYTHONPATH="/home/user/my_project":$PYTHONPATH
And don't forget to preserve previous content suffixing by :$PYTHONPATH (which is the value of the variable)
Execute the following command to check everything is configured correctly:
echo $PYTHONPATH
How about:
return (returnValue == "1");
or as suggested below:
return (returnValue != "0");
The correct one will depend on what you are looking for as a success result.
Add a log4j.properties(log4j.xml) file with at least one appender in root of your classpath.
The contents of the file(log4j.properties) can be as simple as
log4j.rootLogger=WARN,A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{ISO8601} [%t] %-5p %c %x - %m%n
This will enable log4j logging with default log level as WARN
and use the java console to log the messages.
Another way to do it in Java 7 or earlier would be to use Guava:
public static String[] names() {
return FluentIterable.from(values()).transform(Enum::name).toArray(String.class);
}
I experienced this issue when trying to restore a database on MS SQL Server 2012.
Here's what worked for me:
I had to first run the RESTORE FILELISTONLY
command below on the backup file to list the logical file names:
RESTORE FILELISTONLY
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
This displayed the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively:
LogicalName PhysicalName
com.my_db C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf
com.my_db_log C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf
All I had to do was to simply replace the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively in my database restore script:
USE master;
GO
ALTER DATABASE my_db SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
RESTORE DATABASE my_db
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
WITH REPLACE,
MOVE 'com.my_db' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf',
MOVE 'com.my_db_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf'
GO
ALTER DATABASE my_db SET MULTI_USER;
GO
And the Database Restore task ran successfully:
That's all.
I hope this helps
select 1 from table
is used by some databases as a query to test a connection to see if it's alive, often used when retrieving or returning a connection to / from a connection pool.
From your code it becomes apparent that you use POCO. Having another key is unnecessary: you can add an index as suggested by juFo.
If you use Fluent API instead of attributing UserName property your column annotation should look like this:
this.Property(p => p.UserName)
.HasColumnAnnotation("Index", new IndexAnnotation(new[] {
new IndexAttribute("Index") { IsUnique = true }
}
));
This will create the following SQL script:
CREATE UNIQUE NONCLUSTERED INDEX [Index] ON [dbo].[Users]
(
[UserName] ASC
)
WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF,
IGNORE_DUP_KEY = OFF,
DROP_EXISTING = OFF,
ONLINE = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
If you attempt to insert multiple Users having the same UserName you'll get a DbUpdateException with the following message:
Cannot insert duplicate key row in object 'dbo.Users' with unique index 'Index'.
The duplicate key value is (...).
The statement has been terminated.
Again, column annotations are not available in Entity Framework prior to version 6.1.
Maybe something like this?
UPDATE [MyTable]
SET [SomeField] = NULL
WHERE [SomeField] is not NULL
AND LEN(LTRIM(RTRIM([SomeField]))) = 0
If you are using Rubygems version 2.1.0 or later, you can try: gem uninstall --all
.
$('.block').scrollTop($('.block')[0].scrollHeight);
I use this code to scroll the chat when new messages arrive.
Let me recommend mem_top tool I created
It helped me to solve a similar issue
It just instantly shows top suspects for memory leaks in a Python program
try this:-
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = new Date();
System.out.println(dateFormat.format(date));
or
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
pi Radians = 180 degrees
So 1 degree = pi/180 radians
or 1 radian = 180/pi degrees
I tried the above, (svn merge
) and you're right, it does jack. However
svn update -r <revision> <target> [-R]
seems to work, but isn't permanent (my svn is simply showing an old revision). So I had to
mv <target> <target backup>
svn update <target>
mv <target backup> <target>
svn commit -m "Reverted commit on <target>" <target>
In my particular case my target is interfaces/AngelInterface.php
. I made changes to the file, committed them, updated the build computer ran the phpdoc compiler and found my changes were a waste of time. svn log interfaces/AngelInterface.php
shows my change as r22060 and the previous commit on that file was r22059. So I can svn update -r 22059 interfaces/AngelInterface.php
and I end up with code as it was in -r22059 again. Then :-
mv interfaces/AngelInterface.php interfaces/AngelInterface.php~
svn update interfaces/AngelInterface.php
mv interfaces/AngelInterface.php~ interfaces/AngelInterface.php
svn commit -m "reverted -r22060" interfaces/AngelInterface.php
Alternatively I could do the same thing on a directory, by specifying . -R
in place of interfaces/AngelInterface.php
in all the above.
model =list.stream().max(Comparator.comparing(Model::yourSortList)).get();
Another way to look at it is to consider git rebase master
as:
Rebase the current branch on top of
master
Here , 'master
' is the upstream branch, and that explain why, during a rebase, ours
and theirs
are reversed.
In a scenario where you intend to push a single email to different recipients at one instance (i.e CC multiple email addresses), the solution below works fine with Laravel 5.4 and above.
Mail::to('[email protected]')
->cc(['[email protected]','[email protected]','[email protected]','[email protected]'])
->send(new document());
where document is any class that further customizes your email.
ENV['RAILS_ENV']
is now deprecated.
You should use Rails.env
which is clearly much nicer.
use g++
instead of gcc
.
Make sure that you run the SQL Server Configuration Manager snap-in as Administrator if UAC is enabled. Then right click the service and then click properties, change the start mode to enabled, then start it.
Need to set "on" server parameter "log_bin_trust_function_creators" on server side. This one you can easily find on left side blade if it is azure maria db.
This should work for you to get the contents of list.txt
file
$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));
$context=stream_context_create($headers);
$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);
$str=utf8_encode($str);
$str=json_decode($str,true);
print_r($str);
edit the project's settings.gradle file: delete the module name (, ':xxxxx') where xxxxx is the module name to be deleted
using the file explorer delete the module folder
by the way, the current version of the Android Studio (v3.1.2) throws an exception and exits the removing with an error while I'm removing the module through Module Settings => selected module => - (minus)
Best Regards, thanks)
select * from yourtable where created < now() and created > '2011-04-25 04:00:00'
I believe SET
is ANSI standard whereas the SELECT
is not. Also note the different behavior of SET
vs. SELECT
in the example below when a value is not found.
declare @var varchar(20)
set @var = 'Joe'
set @var = (select name from master.sys.tables where name = 'qwerty')
select @var /* @var is now NULL */
set @var = 'Joe'
select @var = name from master.sys.tables where name = 'qwerty'
select @var /* @var is still equal to 'Joe' */
Expires
and Cache-Control
are "strong caching headers"
Last-Modified
and ETag
are "weak caching headers"
First the browser check Expires/Cache-Control
to determine whether or not to make a request to the server
If have to make a request, it will send Last-Modified/ETag
in the HTTP request. If the Etag
value of the document matches that, the server will send a 304 code instead of 200, and no content. The browser will load the contents from its cache.
$('.toggle img').data('block', 'something');
$('.toggle img').attr('src', 'something.jpg');
Use jQuery.data and jQuery.attr.
I'm showing them to you separately for the sake of understanding.
In the STL, std::max_element
provides the iterator (which can be used to get index with std::distance
, if you really want it).
int main(int argc, char** argv) {
int A[4] = {0, 2, 3, 1};
const int N = sizeof(A) / sizeof(int);
cout << "Index of max element: "
<< distance(A, max_element(A, A + N))
<< endl;
return 0;
}
Solution : 1.Project -> Build Path -> Configure Build Path
2.Select Java Build path on the left menu, and select "Source"
3.Under Project select Include(All) and click OK
Cause : The issue might because u might have deleted the CLASS files or dependencies on the project
Answer above is missing an example which might not be obvious (it wasn't to me).
Url could be broken down into parts
https://github.com/liufa/Tuplinator/commit/f36e3c5b3aba23a6c9cf7c01e7485028a23c3811
\_____/\________/ \_______________________________________/
| | |
Account name | Hash of revision
Project name
Hash can be found here (you can click it and will get the url from browser).
Hope this saves you some time.
No, thankfully, there isn't goto
in Java.
The goto
keyword is only reserved, but not used (the same goes for const
).
For me the error was:
Error: unexpected input in "?"
and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.
EDIT: OP requested an example. Here it goes.
? ~ cat a.R
cat('hello world\n')
? ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f ...cat('hello wo
00000010: 726c 645c 6e27 290a rld\n').
? ~ R -f a.R
R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> cat('hello world\n')
Error: unexpected input in "?"
Execution halted
I like TcpCatcher because it is very simple to use and has a modern interface. It is provided as a jar file, you just download it and run it (no installation process). Also, it comes with a very useful "on the fly" packets modification features (debug mode).
My answer is based on getting a 403 error although I had all of the Apache settings mentioned in the other answers correct.
It was a fresh Centos 7 server and it turned out that the issue was not the Apache settings but the fact that the PhpMyAdmin did not serve at all. The solution was to install php and add the php directive to apache.conf:
Don't forget to restart Apache server to take effect - systemctl restart httpd.service
I hope this helps. I first thought my issue was Apache directives, so I post my solution here.
Unfortunately, you can only have one app.config file per executable, so if you have DLL’s linked into your application, they cannot have their own app.config files.
Solution is:
You don't need to put the App.config file in the Class Library's project.
You put the App.config file in the application that is referencing your class
library's dll.
For example, let's say we have a class library named MyClasses.dll which uses the app.config file like so:
string connect =
ConfigurationSettings.AppSettings["MyClasses.ConnectionString"];
Now, let's say we have an Windows Application named MyApp.exe which references MyClasses.dll. It would contain an App.config with an entry such as:
<appSettings>
<add key="MyClasses.ConnectionString"
value="Connection string body goes here" />
</appSettings>
OR
An xml file is best equivalent for app.config. Use xml serialize/deserialize as needed. You can call it what every you want. If your config is "static" and does not need to change, your could also add it to the project as an embedded resource.
Hope it gives some Idea
Using double
to store large integers is dubious; the largest integer that can be stored reliably in double
is much smaller than DBL_MAX
. You should use long long
, and if that's not enough, you need your own arbitrary-precision code or an existing library.
I wanted to add a comment but I have less than 50 pts so I can only "Answer". Be aware that if you use the "VisualTreeHelper" method to retrieve XAML "TextBlock" objects then it will also grab XAML "Button" objects. If you re-initialize the "TextBlock" object by writing to the Textblock.Text parameter then you will no longer be able to change the Button text using the Button.Content parameter. The Button will permanently show the text written to it from the Textblock.Text write action (from when it was retrieved --
foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
// do something with tb here
tb.Text = ""; //this will overwrite Button.Content and render the
//Button.Content{set} permanently disabled.
}
To work around this, you can try using a XAML "TextBox" and add methods (or Events) to mimic a XAMAL Button. XAML "TextBox" is not gathered by a search for "TextBlock".
Create a HttpRequestMessage
, set the Method to GET
, set your headers and then use SendAsync
instead of GetAsync
.
var client = new HttpClient();
var request = new HttpRequestMessage() {
RequestUri = new Uri("http://www.someURI.com"),
Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
.ContinueWith((taskwithmsg) =>
{
var response = taskwithmsg.Result;
var jsonTask = response.Content.ReadAsAsync<JsonObject>();
jsonTask.Wait();
var jsonObject = jsonTask.Result;
});
task.Wait();
I faced this issue, I was not able to copy zeppelin [1GB] directory into docker container and was getting issue
COPY failed: stat /var/lib/docker/tmp/docker-builder977188321/zeppelin-0.7.2-bin-all: no such file or directory
I am using docker Version: 17.09.0-ce and resolved the issue with the following steps.
Step 1: copy zeppelin directory [which i want to copy into docker package]into directory contain "Dockfile"
Step 2: edit Dockfile and add command [location where we want to copy] ADD ./zeppelin-0.7.2-bin-all /usr/local/
Step 3: go to directory which contain DockFile and run command [alternatives also available] docker build
Step 4: docker image created Successfully with logs
Step 5/9 : ADD ./zeppelin-0.7.2-bin-all /usr/local/ ---> 3691c902d9fe
Step 6/9 : WORKDIR $ZEPPELIN_HOME ---> 3adacfb024d8 .... Successfully built b67b9ea09f02
You can't, Print Preview is a feature of a browser, and therefore should be protected from being called by JavaScript as it would be a security risk.
That's why your example uses Active X, which bypasses the JavaScript security issues.
So instead use the print stylesheet that you already should have and show it for media=screen,print instead of media=print.
Read Alist Apart: Going to Print for a good article on the subject of print stylesheets.
For those who use Bootstrap 3, it has a great CSS class to do the job:
<img src="..." class="img-circle">
Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.
Bootstrap 4 includes flexbox, so the method of vertical centering is much easier and doesn't require extra CSS.
Just use the d-flex
and align-items-center
utility classes..
<div class="jumbotron d-flex align-items-center">
<div class="container">
content
</div>
</div>
http://www.codeply.com/go/ui6ABmMTLv
Important: Vertical centering is relative to height. The parent container of the items you're attempting to center must have a defined height. If you want the height of the page use vh-100
or min-vh-100
on the parent! For example:
<div class="jumbotron d-flex align-items-center min-vh-100">
<div class="container text-center">
I am centered vertically
</div>
</div>
Check your servers error log, typically /var/log/apache2/error.log
.
You test k = M
instead of k == M
.
Maybe it is what you want to do, in this case, write if (match == 0 && (k = M))
The output file needs to be opened in binary mode:
f = open('varstor.txt','w')
needs to be:
f = open('varstor.txt','wb')
You could use a Polygon Clipping algorithm to find the intersection between two polygons. However these tend to be complicated algorithms when all of the edge cases are taken into account.
One implementation of polygon clipping that you can use your favorite search engine to look for is Weiler-Atherton. wikipedia article on Weiler-Atherton
Alan Murta has a complete implementation of a polygon clipper GPC.
Edit:
Another approach is to first divide each polygon into a set of triangles, which are easier to deal with. The Two-Ears Theorem by Gary H. Meisters does the trick. This page at McGill does a good job of explaining triangle subdivision.
use this
from collections import Counter
list1=['apple','egg','apple','banana','egg','apple']
counts = Counter(list1)
print(counts)
# Counter({'apple': 3, 'egg': 2, 'banana': 1})
I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:
action="javascript:checkout()"
You try this?
Don't forget include the script reference in the html head.
I don't know cause of that works in firefox. Regards.
Use options(scipen=5)
or some other high enough number. The scipen option determines how likely R is to switch to scientific notation, the higher the value the less likely it is to switch. Set the option before making your plot, if it still has scientific notation, set it to a higher number.
My problem was similar but with the inconvenience that sometimes the string contains letters (sometimes empty).
string sNumbers = "1,2,hh,3,4,x,5";
Trying to follow Pcode Xonos Extension Method:
public static List<int> SplitToIntList(this string list, char separator = ',')
{
int result = 0;
return (from s in list.Split(',')
let isint = int.TryParse(s, out result)
let val = result
where isint
select val).ToList();
}
check this out https://forum.jquery.com/topic/get-index-of-same-class-element-on-click then http://jsfiddle.net/me2loveit2/d6rFM/2/
var index = $('selector').index(this);
console.log(index)
In Kotlin or in ConstraintLayout you just add :
android:windowSoftInputMode="stateHidden|adjustResize"
OR
android:windowSoftInputMode="stateVisible|adjustResize"
Which state you need after activity launch, you can set from manifest.
in your AndroidManifest.xml
like this:
<activity
android:name=".ActivityName"
android:windowSoftInputMode="stateHidden|adjustResize"
/>
jQuery(function ($) {
$('li#linkss').find('a').on('click', function (e) {
var
link_href = $(this).attr('href')
, $linkElem = $(link_href)
, $linkElem_scroll = $linkElem.get(0) && $linkElem.position().top - 115;
$('html, body')
.animate({
scrollTop: $linkElem_scroll
}, 'slow');
e.preventDefault();
});
});
You can perform it, this way:
$('input[id=ans]').is(':checked');
you can run raw query like this way too.
DB::table('setting_colleges')->first();
Try to use this:
position: relative;
clear: both;
I use it when I can't use absolute position, for example in printing when you use page-break-after: always;
works fine only with position:relative
.
table.setDefaultEditor(Object.class, null);
The answer by Kleist certainly works, but there is an important caveat:
When you write a Makefile
manually, you might generate a SRCS
variable using a function to select all .cpp
and .h
files. If a source file is later added, re-running make
will include it.
However, CMake (with a command like file(GLOB ...)
) will explicitly generate a file list and place it in the auto-generated Makefile
. If you have a new source file, you will need to re-generate the Makefile
by re-running cmake
.
edit: No need to remove the Makefile.
Swift 2
Using Trailing Closures this becomes:
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
Trailing Closures is Swift syntactic sugar that enables defining the closure outside of the function parameter scope. For more information see Trailing Closures in Swift 2.2 Programming Language Guide.
In dispatch_async case the API is func dispatch_async(queue: dispatch_queue_t, _ block: dispatch_block_t)
since dispatch_block_t
is type alias for () -> Void
- A closure that receives 0 parameters and does not have a return value, and block being the last parameter of the function we can define the closure in the outer scope of dispatch_async
.
Use something like header( 'Location: /my-other-page.html' );
to redirect. You can't have sent any other data on the page before you do this though.
Access 2007 can lose the CurrentDb: see http://support.microsoft.com/kb/167173, so in the event of getting "Object Invalid or no longer set" with the examples, use:
Dim db as Database
Dim rs As DAO.Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset("SELECT * FROM myTable")
It is pretty easy to add a collaborator to a free plan.
The added user should now be able to push to your repository on GitHub.
Before you extract values from $_POST
, you should check if they exist. You could use the isset
function for this (http://php.net/manual/en/function.isset.php)
t
indicates for text mode
https://docs.python.org/release/3.1.5/library/functions.html#open
on linux, there's no difference between text mode and binary mode,
however, in windows, they converts \n
to \r\n
when text mode.
its not .val() if you want to get file /home/user/default.png it will get with .val() just default.png
MonoDevelop from: http://monodevelop.com/
There is no equivalent to Visual Studio. However, for writing C# on Mac or Linux, you can't get better than MonoDevelop.
The Mac build is pre beta. From the MonoDevelop site on Mac:
The Mac OS X port of MonoDevelop is under active development and has not seen a stable release yet. Recent work described by Michael Hutchinson has focussed on improving the usability and stability of Monodevelop on the Mac. This work will be released in MonoDevelop 2.2. Right now it's not finished, and is very much an alpha.
I had a very similar issue. I got the same error because the csv contained spaces in the header. My csv contained a header "Gender " and I had it listed as:
[['Gender']]
If it's easy enough for you to access your csv, you can use the excel formula trim()
to clip any spaces of the cells.
or remove it like this
df.columns = df.columns.to_series().apply(lambda x: x.strip())
I present a fully worked example on how building a shared library
and using it under Python
by means of ctypes
. I consider the Windows
case and deal with DLLs
. Two steps are needed:
The shared library
I consider is the following and is contained in the testDLL.cpp
file. The only function testDLL
just receives an int
and prints it.
#include <stdio.h>
?
extern "C" {
?
__declspec(dllexport)
?
void testDLL(const int i) {
printf("%d\n", i);
}
?
} // extern "C"
To build a DLL
with Visual Studio
from the command line run
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\vsdevcmd"
to set the include path and then run
cl.exe /D_USRDLL /D_WINDLL testDLL.cpp /MT /link /DLL /OUT:testDLL.dll
to build the DLL.
DLL
from the IDEAlternatively, the DLL
can be build using Visual Studio
as follows:
Under Python, do the following
import os
import sys
from ctypes import *
lib = cdll.LoadLibrary('testDLL.dll')
lib.testDLL(3)
What is the package name of your class? If there is no package name, then most likely the solution is:
java -cp FileManagement Main
In AndroidManifest.xml, don't forget to set:
android:windowSoftInputMode="adjustResize"
and for RelativeLayout inside ScrollView ,set :
android:layout_gravity="center" or android:layout_gravity="bottom"
it will be okay
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
Note:
Its not necessary to specify table name in Person.hbm.xml (........) when you are creating table with same as class name. Also applicable to fields.
While creating "person" table in your respective database,make sure that whatever FILEDS names you specified in Person.hbm.xml must match with table COLUMNS names ELSE you wil get above error.
Most likely the remote repository doesn't exist or you have added the wrong one.
You have to first remove the origin and re-add it:
git remote remove origin
git remote add origin https://github.com/username/repository
I ended up with the following:
set input=AAA BBB CCC DDD EEE FFF
set nth=4
for /F "tokens=%nth% delims= " %%a in ("%input%") do set nthstring=%%a
echo %nthstring%
With this you can parameterize the input and index. Make sure to put this code in a bat file.
The SQL you need is:
Update table set table_column = "test";
The SQL you posted creates a new row rather than updating existing rows.
It's quite unclear how you are computing the size ("the size in debug mode"?").
Use printf()
:
printf("the size of c is %u\n", (unsigned int) sizeof c);
Normally you'd print a size_t
value (which is the type sizeof
returns) with %zu
, but if you're using a pre-C99 compiler like Visual Studio that won't work.
You need to find the typedef
statements in your code that define the custom names like uint8
and so on; those are not standard so nobody here can know how they're defined in your code.
New C code should use <stdint.h>
which gives you uint8_t
and so on.
To get the equivalent of a static constructor, you need to write a separate ordinary class to hold the static data and then make a static instance of that ordinary class.
class StaticStuff
{
std::vector<char> letters_;
public:
StaticStuff()
{
for (char c = 'a'; c <= 'z'; c++)
letters_.push_back(c);
}
// provide some way to get at letters_
};
class Elsewhere
{
static StaticStuff staticStuff; // constructor runs once, single instance
};
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
The solution suggested
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
<remove name="UrlRoutingModule"/>
</modules>
</system.webServer>
works, but can degrade performance and can even cause errors, because now all registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.
A more sensible solution is to include this in your web.config:
<system.webServer>
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
</system.webServer>
Credit for his goes to Colin Farr. Check-out his post about this topic at http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html.
First of all, you can't pass to alert
second argument, use concatenation instead
alert("Input is " + inputValue);
However in order to get values from input better to use states like this
var MyComponent = React.createClass({_x000D_
getInitialState: function () {_x000D_
return { input: '' };_x000D_
},_x000D_
_x000D_
handleChange: function(e) {_x000D_
this.setState({ input: e.target.value });_x000D_
},_x000D_
_x000D_
handleClick: function() {_x000D_
console.log(this.state.input);_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<input type="text" onChange={ this.handleChange } />_x000D_
<input_x000D_
type="button"_x000D_
value="Alert the text input"_x000D_
onClick={this.handleClick}_x000D_
/>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
<MyComponent />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
after i tried the given answers, i found out another reason for the same Exception, that i had to add the library i'm using manually to my main library through
Right click on my main library >
Properties >
Android >
Go to the very bottom of the screen and click (Add) >
Select my other library that caused the crash >
Apply
before this solution, i used the "Fix Project setup" from within the .java file in eclipse, but this did not work, so i had to add it manually here and it worked
$ du -h -d=1 ~/Library/Developer/Xcode/*
shows at least two folders are huge:
1.5G /Users/horace/Library/Developer/Xcode/DerivedData
9.4G /Users/horace/Library/Developer/Xcode/iOS DeviceSupport
Feel free to remove stuff in the folders:
rm -rf ~/Library/Developer/Xcode/DerivedData/*
and some in:
open ~/Library/Developer/Xcode/iOS\ DeviceSupport/
I had this exact same problem with Xampp portable on Windows 10 Home. I went through all the suggestions and none worked. I did get it working with Windows Firewall Settings and an error on my part.
My pen drive was labelled Drive E on my laptop and Drive F on my Desktop. Once I corrected that using disk partition and changed the drive letter to E for my desktop to windows asked for access for the firewall and everything clicked.
The steps to correct the drive letter were: 1. Hit the windows key and type Partition, "create and format harddisks partitions" should be at the top, hit enter 2. Find the drive you are looking for at the top panel and click on it. 3. Right click on it and select change drive letter and path, click okay 4. Now try to start xampp control panel and start Apache and Mysql 5. if you get the windows firewall click allow.
I can't say this will work but it did for me and is what I added to this discussion. I also think it might have been just the firewall did not allow the oither drive letter.
The working directory is a common concept across virtually all operating systems and program languages etc. It's the directory in which your program is running. This is usually (but not always, there are ways to change it) the directory the application is in.
Relative paths are ones that start without a drive specifier. So in linux they don't start with a /
, in windows they don't start with a C:\
, etc. These always start from your working directory.
Absolute paths are the ones that start with a drive (or machine for network paths) specifier. They always go from the start of that drive.
No, AFAIK, it's not possible to do it portably.
There's no defined "first" record anyway - on different SQL engines it's perfectly possible that "SELECT * FROM table
" might return the results in a different order each time.
I tend not to use the .on() syntax, if not necessary. For example you can migrate easier like this:
old:
$('.myButton').live('click', function);
new:
$('.myButton').click(function)
Here is a list of valid event handlers: https://api.jquery.com/category/forms/
I don't like hiding the placeholder when you focus the textarea. So I made a constructor function Placeholder
that looks exactly like the built-in placeholder and works also in other browsers than Google Chrome. It's very convenient because you can use the Placeholder
function as often as you want and it doesn't even need jQuery.
EDIT:
It now also handles special cases, like inserting the placeholder, correctly.
var textarea = document.getElementById("textarea");_x000D_
new Placeholder(textarea, "Line 1\nLine 2\nLine 3");_x000D_
_x000D_
function Placeholder(el, placeholder) {_x000D_
if (el.value == "" || el.value == placeholder) {_x000D_
el.style.color = "gray";_x000D_
el.value = placeholder;_x000D_
el._plc = true;_x000D_
el.className += " unselectable";_x000D_
}_x000D_
function keyPress(e) {_x000D_
window.setTimeout(function() {_x000D_
var replaced = reverseStr(el.value).replace(reverseStr(placeholder), "");_x000D_
_x000D_
if (el.value == "") {_x000D_
el.value = placeholder;_x000D_
el.style.color = "gray";_x000D_
cursorToStart(el);_x000D_
el._plc = true;_x000D_
el.className += " unselectable";_x000D_
} else if (el._plc && el.value.endsWith(placeholder) && replaced !== "") {_x000D_
el.value = reverseStr(replaced);_x000D_
el.style.color = "black";_x000D_
el._plc = false;_x000D_
el.readOnly = false;_x000D_
el.className = el.className.replace("unselectable", "");_x000D_
} else if (el._plc && el.readOnly) {_x000D_
var ch = String.fromCharCode(e.charCode);_x000D_
if (e.keyCode == 13) ch = "\n"; // ENTER_x000D_
else if (e.charCode == 0) return; // non-character keys_x000D_
_x000D_
el.value = ch;_x000D_
el.style.color = "black";_x000D_
el._plc = false;_x000D_
el.readOnly = false;_x000D_
el.className = el.className.replace("unselectable", "");_x000D_
}_x000D_
}, 10);_x000D_
}_x000D_
el.addEventListener("keypress", keyPress, false);_x000D_
el.addEventListener("paste", keyPress, false);_x000D_
el.addEventListener("cut", keyPress, false);_x000D_
el.addEventListener("mousedown", function() {_x000D_
if (el._plc) el.readOnly = true;_x000D_
}, false);_x000D_
el.addEventListener("mouseup", function() {_x000D_
el.readOnly = false;_x000D_
if (el._plc) cursorToStart(el);_x000D_
}, false);_x000D_
_x000D_
function cursorToStart(input) {_x000D_
if (input.createTextRange) {_x000D_
var part = input.createTextRange();_x000D_
part.move("character", 0);_x000D_
part.select();_x000D_
} else if (input.setSelectionRange){_x000D_
input.setSelectionRange(0, 0);_x000D_
} input.focus();_x000D_
}_x000D_
function reverseStr(str) {_x000D_
if (!str) return "";_x000D_
return str.split("").reverse().join("");_x000D_
}_x000D_
}
_x000D_
textarea {_x000D_
border: 1px solid gray;_x000D_
padding: 3px 6px;_x000D_
font-family: Arial;_x000D_
font-size: 13px;_x000D_
transition: .2s;_x000D_
}_x000D_
textarea:hover, textarea:focus {_x000D_
border-color: #2277cc;_x000D_
}_x000D_
textarea:focus {_x000D_
box-shadow: inset 0 0 5px #85B7E9;_x000D_
}_x000D_
*.unselectable {_x000D_
-webkit-user-select: none;_x000D_
-webkit-touch-callout: none;_x000D_
-khtml-user-select: none;_x000D_
-moz-user-select: none;_x000D_
-ms-user-select: none;_x000D_
-o-user-select: none;_x000D_
}
_x000D_
<textarea id="textarea"></textarea>
_x000D_
Quite similar approve as already posted above. However it's easier to read.
/**
* Remove all empty spaces from array a string array
* @param arr array
* @return array without ""
*/
public static String[] removeAllEmpty(String[] arr) {
if (arr == null)
return arr;
String[] result = new String[arr.length];
int amountOfValidStrings = 0;
for (int i = 0; i < arr.length; i++) {
if (!arr[i].equals(""))
result[amountOfValidStrings++] = arr[i];
}
result = Arrays.copyOf(result, amountOfValidStrings);
return result;
}
Going one step further, uploading to iTunesConnect via commandline with Xcode 7!
(Assuming you are starting with an .ipa
that has been signed with the correct release profile and signing identity.)
Enter altool
, the CLI interface for the Application Loader (docs
, page 38).
Hidden deep within Xcode.app's structure, is a handy function to let us upload directly to ItunesConnect.
/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Versions/A/Support/altool
Simply run $ altool --upload-app -f file -u username [-p password]
to upload your newly minted .ipa
straight to Apple.
The password is optional, and will prompt you for it if you leave it off the command.
If there are any issues with the app during the verification step, the console will print them out.
You will likely have to export the path to altool
if you don't want to save its location.
export PATH=$PATH:/Applications/Xcode.app/Contents/Applications/Application\ Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Versions/A/Support/
Thats it! Simply login to iTunesConnect.com and select your new build for testing with testflight.
Final Note: If you get an error saying Exception while launching iTunesTransporter: Transporter not found at path: /usr/local/itms/bin/iTMSTransporter. You should reinstall the application
, you can follow the suggestion on this SO answer, to run a symlink to the correct location:
ln -s /Applications/Xcode.app/Contents/Applications/Application\ Loader.app/Contents/itms /usr/local/itms
Sometimes you face these problems if you specify UTF-8 encoding also. I recommend you to specify encoding while reading file and same encoding while writing to file. This might solve your problem.
In Java 8 :
int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());
You need to provide your own implementation of equals()
in MyClass
.
@Override
public boolean equals(Object other) {
if (!(other instanceof MyClass)) {
return false;
}
MyClass that = (MyClass) other;
// Custom equality check here.
return this.field1.equals(that.field1)
&& this.field2.equals(that.field2);
}
You should also override hashCode()
if there's any chance of your objects being used in a hash table. A reasonable implementation would be to combine the hash codes of the object's fields with something like:
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 37 + this.field1.hashCode();
hashCode = hashCode * 37 + this.field2.hashCode();
return hashCode;
}
See this question for more details on implementing a hash function.
If you modify the grant tables manually (using INSERT, UPDATE, etc.), you should execute
a FLUSH PRIVILEGES
statement to tell the server to reload the grant tables.
PS: I wouldn't recommend to allow any host to connect for any user (especially not the root
use). If you are using mysql for a client/server application, prefer a subnet address. If you are using mysql with a web server or application server, use specific IPs.
If you assign its output to a variable, bash
automatically strips whitespace:
linecount=`wc -l < log.txt`
Just use pandas
list(pd.DataFrame(listofstuff).melt().values)
this only works for a list of lists
if you have a list of list of lists you might want to try something along the lines of
lists(pd.DataFrame(listofstuff).melt().apply(pd.Series).melt().values)
Thanks to great Mark Amery's answer I devised function to account for all possible ISO formats of datetime:
class FixedOffset(tzinfo):
"""Fixed offset in minutes: `time = utc_time + utc_offset`."""
def __init__(self, offset):
self.__offset = timedelta(minutes=offset)
hours, minutes = divmod(offset, 60)
#NOTE: the last part is to remind about deprecated POSIX GMT+h timezones
# that have the opposite sign in the name;
# the corresponding numeric value is not used e.g., no minutes
self.__name = '<%+03d%02d>%+d' % (hours, minutes, -hours)
def utcoffset(self, dt=None):
return self.__offset
def tzname(self, dt=None):
return self.__name
def dst(self, dt=None):
return timedelta(0)
def __repr__(self):
return 'FixedOffset(%d)' % (self.utcoffset().total_seconds() / 60)
def __getinitargs__(self):
return (self.__offset.total_seconds()/60,)
def parse_isoformat_datetime(isodatetime):
try:
return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S.%f')
except ValueError:
pass
try:
return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S')
except ValueError:
pass
pat = r'(.*?[+-]\d{2}):(\d{2})'
temp = re.sub(pat, r'\1\2', isodatetime)
naive_date_str = temp[:-5]
offset_str = temp[-5:]
naive_dt = datetime.strptime(naive_date_str, '%Y-%m-%dT%H:%M:%S.%f')
offset = int(offset_str[-4:-2])*60 + int(offset_str[-2:])
if offset_str[0] == "-":
offset = -offset
return naive_dt.replace(tzinfo=FixedOffset(offset))
On Mac, head -n -1 wont work. And, I was trying to find a simple solution [ without worrying about processing time ] to solve this problem only using "head" and/or "tail" commands.
I tried the following sequence of commands and was happy that I could solve it just using "tail" command [ with the options available on Mac ]. So, if you are on Mac, and want to use only "tail" to solve this problem, you can use this command :
cat file.txt | tail -r | tail -n +2 | tail -r
1> tail -r : simply reverses the order of lines in its input
2> tail -n +2 : this prints all the lines starting from the second line in its input
Just ran into this issue - if you updated a bunch of files and don't want to do git mv
all of them this also works:
/dir/RenamedFile.js
to /whatever/RenamedFile.js
.git add -A
to stage that change/dir/RenamedFile.js
.git add -A
again, will re-stage vs that change, forcing git to pick up the filename change.You can't instantiate interfaces or abstract classes.
That's because it wouldn't have any logic to it.
Interfaces provide a contract of the methods that should be in a class, without implementation. (So there's no actual logic in the interface).
Abstract classes provide basic logic of a class, but are not fully functional (not everything is implemented). So again, you won't be able to do anything with it.
Based on the statements:
SELECT DATEADD(MONTH, 1, @x) -- Add a month to the supplied date @x
and
SELECT DATEADD(DAY, 0 - DAY(@x), @x) -- Get last day of month previous to the supplied date @x
how about adding a month to date @x and then retrieving the last day of the month previous to that (i.e. The last day of the month of the supplied date)
DECLARE @x DATE = '20-Feb-2012'
SELECT DAY(DATEADD(DAY, 0 - DAY(DATEADD(MONTH, 1, @x)), DATEADD(MONTH, 1, @x)))
Note: This was test using SQL Server 2008 R2
Multiply the value you want to insert (ex. 2.99) by 100
Then insert the division by 100 of the result adding .01 to the end:
299.01/100
If you have a List
of objects, you can serialize them to JSON as follow:
List<MyObjectClass> listOfObjects = new List<MyObjectClass>();
And then use addParameter
:
requestREST.AddParameter("myAssocKey", JsonConvert.SerializeObject(listOfObjects));
And you wil need to set the request format to JSON
:
requestREST.RequestFormat = DataFormat.Json;
Right, I've been trying to fix this issue for sometime. I've used all the solutions in the various Stack Overflow topics regarding this and none seemed to be working.
I have just fixed the issue this morning. After you gave fixed the web.config for both the project and the views, making sure all the .dll versions are matching with what you have in the references folder. You will need to unload the project, edit the .csproj, and then update all the .dll versions in that file.
System.Web.Helpers
System.Web.Mvc
System.Web.WebPages
Hope this helps, as I have finally fixed this issue! No more red squiggly lines.
This has also fixed the context menu issue I was having where, I wasn't getting the option to add a controller, view etc.
This worked for me . In my case 2 tables foo and boo have to be joined based on 3 different columns.Please note in my case ,in boo the 3 common columns are not primary key
i.e., one to one mapping based on 3 different columns
@Entity
@Table(name = "foo")
public class foo implements Serializable
{
@Column(name="foocol1")
private String foocol1;
//add getter setter
@Column(name="foocol2")
private String foocol2;
//add getter setter
@Column(name="foocol3")
private String foocol3;
//add getter setter
private Boo boo;
private int id;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "brsitem_id", updatable = false)
public int getId()
{
return this.id;
}
public void setId(int id)
{
this.id = id;
}
@OneToOne
@JoinColumns(
{
@JoinColumn(updatable=false,insertable=false, name="foocol1", referencedColumnName="boocol1"),
@JoinColumn(updatable=false,insertable=false, name="foocol2", referencedColumnName="boocol2"),
@JoinColumn(updatable=false,insertable=false, name="foocol3", referencedColumnName="boocol3")
}
)
public Boo getBoo()
{
return boo;
}
public void setBoo(Boo boo)
{
this.boo = boo;
}
}
@Entity
@Table(name = "boo")
public class Boo implements Serializable
{
private int id;
@Column(name="boocol1")
private String boocol1;
//add getter setter
@Column(name="boocol2")
private String boocol2;
//add getter setter
@Column(name="boocol3")
private String boocol3;
//add getter setter
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "item_id", updatable = false)
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
}
Someone should mark Johannes Weiß's comment as the answer to this question. That is exactly why xml documents can't just be loaded in a DOM Document class.
No, you don't "inherit" non-default constructors, you need to define the one taking a String in your class. Typically you use super(message)
in your constructor to invoke your parent constructor. For example, like this:
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
Help is your best saviour, there is a logs action that you can call to check logs for all running processes.
forever --help
Shows the commands
logs Lists log files for all forever processes
logs <script|index> Tails the logs for <script|index>
Sample output of the above command, for three processes running. console.log output's are stored in these logs.
info: Logs for running Forever processes
data: script logfile
data: [0] server.js /root/.forever/79ao.log
data: [1] server.js /root/.forever/ZcOk.log
data: [2] server.js /root/.forever/L30K.log
ag
(the silver searcher) has pretty simple syntax for this
-G --file-search-regex PATTERN
Only search files whose names match PATTERN.
so
ag -G *.h -G *.cpp CP_Image <path>
i have faced the same problem. the following solution have worked for me.
FrameLayout glFrame=(FrameLayout) findViewById(R.id.animatedView);
glFrame.addView(yourView);
glFrame.bringToFront();
glFrame.invalidate();
2nd solution is by using xml adding this attribute to the view xml
android:translationZ=""
Here is the OOP way of adding a colorbar:
fig, ax = plt.subplots()
im = ax.scatter(x, y, c=c)
fig.colorbar(im, ax=ax)
img {_x000D_
width: 200px;_x000D_
}
_x000D_
<img src="https://image.ibb.co/gmmneK/children_593313_340.jpg"/>_x000D_
_x000D_
<img src="https://image.ibb.co/e0RLzK/entrepreneur_1340649_340.jpg"/>_x000D_
_x000D_
<img src="https://image.ibb.co/cks4Rz/typing_849806_340.jpg"/>
_x000D_
please see the above code.
I had the same problem, and I fixed it like this:
Voila...
Neither JPA nor Hibernate annotations support the notion of a default column value. As a workaround to this limitation, set all default values just before you invoke a Hibernate save()
or update()
on the session. This closely as possible (short of Hibernate setting the default values) mimics the behaviour of the database which sets default values when it saves a row in a table.
Unlike setting the default values in the model class as this alternative answer suggests, this approach also ensures that criteria queries that use an Example
object as a prototype for the search will continue to work as before. When you set the default value of a nullable attribute (one that has a non-primitive type) in a model class, a Hibernate query-by-example will no longer ignore the associated column where previously it would ignore it because it was null.
SELECT *
FROM table_name
WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) , '-', SUBSTRING( json_date, 7, 2 ) , '-', SUBSTRING( json_date, 3, 2 ) ) >= NOW();
This only works in situations where you have a numeric field, but you can put a minus sign in front of the field name like so:
reportingNameGroups = reportingNameGroups.OrderBy(x=> - x.GroupNodeId);
However this works a little bit different than OrderByDescending
when you have are running it on an int?
or double?
or decimal?
fields.
What will happen is on OrderByDescending
the nulls will be at the end, vs with this method the nulls will be at the beginning. Which is useful if you want to shuffle nulls around without splitting data into pieces and splicing it later.
If it's WPF, there is a collection of colors in the static class Brushes
.
TextBox.Background = Brushes.Red;
Of course, you can create your own brush if you want.
LinearGradientBrush myBrush = new LinearGradientBrush();
myBrush.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
myBrush.GradientStops.Add(new GradientStop(Colors.Orange, 0.5));
myBrush.GradientStops.Add(new GradientStop(Colors.Red, 1.0));
TextBox.Background = myBrush;
The following approach worked for me
Navigate to your android SDK/tools folder in the terminal window (in case you didn't added the path for it)
Make sure the virtual device you're planning to clean is powered off.
Run the command "./emulator -wipe-data -avd YourAvdName" where YourAvdName is the name of your virtual android device
current working directory variable ie full path /home/dev/other
dir=$PWD
print the full path
echo $dir
public static class DateTimeExtensions
{
public static DateTime LastDayOfMonth(this DateTime date)
{
return date.AddDays(1-(date.Day)).AddMonths(1).AddDays(-1);
}
}
Try to put this in your CSS file.
td {
text-align: center;
vertical-align: middle;
}