A packet is a general term for a formatted unit of data carried by a network. It is not necessarily connected to a specific OSI model layer.
For example, in the Ethernet protocol on the physical layer (layer 1), the unit of data is called an "Ethernet packet", which has an Ethernet frame (layer 2) as its payload. But the unit of data of the Network layer (layer 3) is also called a "packet".
A frame is also a unit of data transmission. In computer networking the term is only used in the context of the Data link layer (layer 2).
Another semantical difference between packet and frame is that a frame envelops your payload with a header and a trailer, just like a painting in a frame, while a packet usually only has a header.
But in the end they mean roughly the same thing and the distinction is used to avoid confusion and repetition when talking about the different layers.
It is not an import problem. You simply call .dropDuplicates()
on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...)
is pyspark.sql.dataframe.DataFrame
, after you apply .collect()
it is a plain Python list
, and lists don't provide dropDuplicates
method. What you want is something like this:
(df1 = sqlContext
.createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
.dropDuplicates())
df1.collect()
With the directory
parameter:
impdp system/password@$ORACLE_SID schemas=USER_SCHEMA directory=MY_DIR \
dumpfile=mydumpfile.dmp logfile=impdpmydumpfile.log
The default directory is DATA_PUMP_DIR
, which is presumably set to /u01/app/oracle/admin/mydatabase/dpdump
on your system.
To use a different directory you (or your DBA) will have to create a new directory object in the database, which points to the Oracle-visible operating system directory you put the file into, and assign privileges to the user doing the import.
When use CMS GC in jdk1.8 will appeare this error, i change the G1 Gc solve this problem.
-Xss512k -Xms6g -Xmx6g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=70 -XX:NewRatio=1 -XX:SurvivorRatio=6 -XX:G1ReservePercent=10 -XX:G1HeapRegionSize=32m -XX:ConcGCThreads=6 -Xloggc:gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps
Correcting gradle settings is quite difficult. If you don't know much about Gradle it requires you to learn alot. Instead you can do the following:
1) Start a new project in a new folder. Choose the same settings with your project with gradle problem but keep it simple: Choose an empty main activity. 2) Delete all the files in ...\NewProjectName\app\src\main folder 3) Copy all the files in ...\ProjectWithGradleProblem\app\src\main folder to ...\NewProjectName\app\src\main folder. 4) If you are using the Test project (\ProjectWithGradleProblem\app\src\AndroidTest) you can do the same for that too.
this method works fine if your Gradle installation is healthy. If you just installed Android studio and did not modify it, the Gradle installation should be fine.
Not sure this will fix the problem for everyone , But uninstalling java, java SDK and installing the latest version (Version 8) fixed the issue for me ..
In my case, I created a new project and when I ran it the first time, it gave me the following error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package
Problem solved!!
The solution is by using DecimalFormat class. This class provides a lot of functionality to format a number.
To get a double value as string with no decimals use the code below.
DecimalFormat decimalFormat = new DecimalFormat(".");
decimalFormat.setGroupingUsed(false);
decimalFormat.setDecimalSeparatorAlwaysShown(false);
String year = decimalFormat.format(32024.2345D);
You can use mplayer.
mencoder -nocache -rtsp-stream-over-tcp rtsp://192.168.XXX.XXX/test.sdp -oac copy -ovc copy -o test.avi
The "copy" codec is just a dumb copy of the stream. Mencoder adds a header and stuff you probably want.
In the mplayer source file "stream/stream_rtsp.c" is a prebuffer_size setting of 640k and no option to change the size other then recompile. The result is that writing the stream is always delayed, which can be annoying for things like cameras, but besides this, you get an output file, and can play it back most places without a problem.
To send an mms for Android 4.0 api 14 or higher without permission to write apn settings, you can use this library: Retrieve mnc and mcc codes from android, then call
Carrier c = Carrier.getCarrier(mcc, mnc);
if (c != null) {
APN a = c.getAPN();
if (a != null) {
String mmsc = a.mmsc;
String mmsproxy = a.proxy; //"" if none
int mmsport = a.port; //0 if none
}
}
To use this, add Jsoup and droid prism jar to the build path, and import com.droidprism.*;
Helpful trick I thought I'd share on this old thread.
You can see how much memory is being used and adjust things accordingly using the Show memory indicator
setting.
It shows up in the lower right of the window.
This coffeescript works for me with Node - the trick is that the _id get's stripped of its ObjectID wrapper when sent and returned from the client and so this needs to be replaced for updates (when no _id is provided, save will revert to insert and add one).
app.post '/new', (req, res) ->
# post data becomes .query
data = req.query
coll = db.collection 'restos'
data._id = ObjectID(data._id) if data._id
coll.save data, {safe:true}, (err, result) ->
console.log("error: "+err) if err
return res.send 500, err if err
console.log(result)
return res.send 200, JSON.stringify result
How was the database exported?
If it was exported using exp
and a full schema was exported, then
Create the user:
create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
Grant the rights:
grant connect, create session, imp_full_database to <username>;
Start the import with imp
:
imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
If it was exported using expdp
, then start the import with impdp
:
impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp
file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\
).
Either move the export file to the above path or create a directory object to pointing to the path where the dmp
file is present and pass the object name to the impdp
command above.
Make sure they're really tabs! In bash, you can insert a tab using C-v TAB
$ echo "LOAD_SETTLED LOAD_INIT 2011-01-13 03:50:01" | awk -F$'\t' '{print $1}'
LOAD_SETTLED
They serve the actual image inside CSS so there will be less HTTP requests per page.
You would need to root the phone and cross compile tcpdump or use someone else's already compiled version.
You might find it easier to do these experiments with the emulator, in which case you could do the monitoring from the hosting pc. If you must use a real device, another option would be to put it on a wifi network hanging off of a secondary interface on a linux box running tcpdump.
I don't know off the top of my head how you would go about filtering by a specific process. One suggestion I found in some quick googling is to use strace on the subject process instead of tcpdump on the system.
Here is another choice: Chaosreader
So I need to debug an application which posts xml to a 3rd party application. I found a brilliant little perl script which does all the hard work – you just chuck it a tcpdump output file, and it does all the manipulation and outputs everything you need...
The script is called chaosreader0.94. See http://www.darknet.org.uk/2007/11/chaosreader-trace-tcpudp-sessions-from-tcpdump/
It worked like a treat, I did the following:
tcpdump host www.blah.com -s 9000 -w outputfile; perl chaosreader0.94 outputfile
android.provider.telephony.SMS_RECEIVED
is not correct because Telephony is a class and it should be capital as in android.provider.Telephony.SMS_RECEIVED
Note Slipstream's response, that base64.b64encode
and base64.b64decode
need bytes-like object, not string.
>>> import base64
>>> a = '{"name": "John", "age": 42}'
>>> base64.b64encode(a)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python3.6/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
If you are not using "-XX:HeapDumpPath" option then in case of JBoss EAP/As by default the heap dump file will be generated in "JBOSS_HOME/bin" directory.
YourKit Java Profiler seems to handle them too.
I know this does not answer this question, but I came here because I had the same error with nodeJS server. I am stuck a long time until I found the solution. My solution just adds slash or /
in end of proxyreserve apache.
my old code is:
ProxyPass / http://192.168.1.1:3001
ProxyPassReverse / http://192.168.1.1:3001
the correct code is:
ProxyPass / http://192.168.1.1:3001/
ProxyPassReverse / http://192.168.1.1:3001/
You can actually do this within the query.
$results = Project::orderBy('name')->get();
This will return all results with the proper order.
Both time
and datetime
have a date component.
Normally if you are just dealing with the time part you'd supply a default date. If you are just interested in the difference and know that both times are on the same day then construct a datetime
for each with the day set to today and subtract the start from the stop time to get the interval (timedelta
).
Full answer to the original question that was talking about a possible different path on local and remote is below
git fetch origin
git diff master -- [local-path] origin/master -- [remote-path]
Assuming the local path is docs/file1.txt and remote path is docs2/file1.txt, use git diff master -- docs/file1.txt origin/master -- docs2/file1.txt
This is adapted from GitHub help page here and Code-Apprentice answer above
HTML
<a name="gettop"></a>
<button id="btn"><a href="#gettop">Back to Top</a></button>
CSS
#btn {
position: fixed;
bottom: 10px;
float: right;
right: 20.5%;
left: 77.25%;
max-width: 90px;
width: 100%;
font-size: 12px;
border-color: rgba(5, 82, 248);
background-color: rgb(5, 82, 248);
padding: .5px;
border-radius: 4px;
font-family: Georgia, 'Times New Roman', Times, serif;
}
On Hover Color Change
#btn:hover {
background-color: #fafafa;
}
sentence="one;two;three"
a="${sentence};"
while [ -n "${a}" ]
do
echo ${a%%;*}
a=${a#*;}
done
SELECT TIMESTAMPDIFF(HOUR,NOW(),'2013-05-15 10:23:23')
calculates difference in hour.(for days--> you have to define day replacing hour
SELECT DATEDIFF('2012-2-2','2012-2-1')
SELECT TO_DAYS ('2012-2-2')-TO_DAYS('2012-2-1')
You're almost there, you just have to append:
-Dhttp.proxyUser=someUserName
-Dhttp.proxyPassword=somePassword
MySQL has started deprecating SQL_CALC_FOUND_ROWS
functionality with version 8.0.17 onwards.
So, it is always preferred to consider executing your query with LIMIT
, and then a second query with COUNT(*)
and without LIMIT
to determine whether there are additional rows.
From docs:
The SQL_CALC_FOUND_ROWS query modifier and accompanying FOUND_ROWS() function are deprecated as of MySQL 8.0.17 and will be removed in a future MySQL version.
COUNT(*) is subject to certain optimizations. SQL_CALC_FOUND_ROWS causes some optimizations to be disabled.
Use these queries instead:
SELECT * FROM tbl_name WHERE id > 100 LIMIT 10; SELECT COUNT(*) WHERE id > 100;
Also, SQL_CALC_FOUND_ROWS
has been observed to having more issues generally, as explained in the MySQL WL# 12615 :
SQL_CALC_FOUND_ROWS has a number of problems. First of all, it's slow. Frequently, it would be cheaper to run the query with LIMIT and then a separate SELECT COUNT() for the same query, since COUNT() can make use of optimizations that can't be done when searching for the entire result set (e.g. filesort can be skipped for COUNT(*), whereas with CALC_FOUND_ROWS, we must disable some filesort optimizations to guarantee the right result)
More importantly, it has very unclear semantics in a number of situations. In particular, when a query has multiple query blocks (e.g. with UNION), there's simply no way to calculate the number of “would-have-been” rows at the same time as producing a valid query. As the iterator executor is progressing towards these kinds of queries, it is genuinely difficult to try to retain the same semantics. Furthermore, if there are multiple LIMITs in the query (e.g. for derived tables), it's not necessarily clear to which of them SQL_CALC_FOUND_ROWS should refer to. Thus, such nontrivial queries will necessarily get different semantics in the iterator executor compared to what they had before.
Finally, most of the use cases where SQL_CALC_FOUND_ROWS would seem useful should simply be solved by other mechanisms than LIMIT/OFFSET. E.g., a phone book should be paginated by letter (both in terms of UX and in terms of index use), not by record number. Discussions are increasingly infinite-scroll ordered by date (again allowing index use), not by paginated by post number. And so on.
You probably specify the .php
extension and It don't found your class.
What I was doing :
php artisan db:seed --class=RolesPermissionsTableSeeder.php
What solved my problem : What I was doing :
php artisan db:seed --class=RolesPermissionsTableSeeder
mysqldump -u root -p --all-databases > alldb.sql
Look up the documentation for mysqldump. You may want to use some of the options mentioned in comments:
mysqldump -u root -p --opt --all-databases > alldb.sql
mysqldump -u root -p --all-databases --skip-lock-tables > alldb.sql
mysql -u root -p < alldb.sql
Here's one I made. It doesn't use a second variable, which I like.
Points = Len(Cells(1, i)) * 1.2
If Round(Points) >= Points Then
Points = Round(Points)
Else: Points = Round(Points) + 1
End If
Well, you could use the 3-argument version: File.createTempFile(String prefix, String suffix, File directory)
which will let you put it where you'd like. Unless you tell it to, Java won't treat it differently than any other file. The only drawback is that the filename is guaranteed to be at least 8 characters long (minimum of 3 characters for the prefix, plus 5 or more characters generated by the function).
If that's too long for you, I suppose you could always just start with the filename "a", and loop through "b", "c", etc until you find one that doesn't already exist.
If the same has to be done in the JSP , use:
<fmt:formatNumber pattern="#,##0" value="${yourlist.yourintvalue}" var="formattedVariable" />
<c:out value="${formattedVariable}"></c:out>
ofcourse for multiple values use :
<c:forEach items="${yourlist}" var="yourlist">
<fmt:formatNumber pattern="#,##0" value="${yourlist.yourintvalue}" var="formattedVariable" />
<c:out value="${formattedVariable}"></c:out>
</c:forEach>
getClass()
method is defined in Object class with the following signature:
public final Class getClass()
Since it is not defined as static
, you can not call it within a static code block. See these answers for more information: Q1, Q2, Q3.
If you're in a static context, then you have to use the class literal expression to get the Class, so you basically have to do like:
Foo.class
This type of expression is called Class Literals and they are explained in Java Language Specification Book as follows:
A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a `.' and the token class. The type of a class literal is Class. It evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.
You can also find information about this subject on API documentation for Class.
Make sure your packaging strategy defined in your pom.xml is not "pom". It should be "jar" or anything else. Once you do that, update your project right clicking on it and go to Maven -> Update Project...
Why not just add "min-width" to your css-class?
The JAX-WS way for basic authentication is
Service s = new Service();
Port port = s.getPort();
BindingProvider prov = (BindingProvider)port;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
port.call();
Thanks for the information here. I am finding this embedding useful and particularly for mobile especially with the embedded images' css file being cached.
To help make life easier, as my file editor(s) do not natively handle this, I made a couple of simple scripts for laptop/desktop editing work, share here in case they are any use to any one else. I have stuck with php as it is handling these things directly and very well.
Under Windows 8.1 say---
C:\Users\`your user name`\AppData\Roaming\Microsoft\Windows\SendTo
... there as an Administrator you can establish a shortcut to a batch file in your path. That batch file will call a php (cli) script.
You can then right click an image in file explorer, and SendTo the batchfile.
Ok Admiinstartor request, and wait for the black command shell windows to close.
Then just simply paste the result from clipboard in your into your text editor...
<img src="|">
or
`background-image : url("|")`
Following should be adaptable for other OS.
Batch file...
rem @echo 0ff
rem Puts 64 encoded version of a file on clipboard
php c:\utils\php\make64Encode.php %1
And with php.exe in your path, that calls a php (cli) script...
<?php
function putClipboard($text){
// Windows 8.1 workaround ...
file_put_contents("output.txt", $text);
exec(" clip < output.txt");
}
// somewhat based on http://perishablepress.com/php-encode-decode-data-urls/
// convert image to dataURL
$img_source = $argv[1]; // image path/name
$img_binary = fread(fopen($img_source, "r"), filesize($img_source));
$img_string = base64_encode($img_binary);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$dataType = finfo_file($finfo, $img_source);
$build = "data:" . $dataType . ";base64," . $img_string;
putClipboard(trim($build));
?>
If you absolutely only want to store the combined field on the model and not the two seperate fields, you could do something like this:
form
attribute on your ModelAdmin
(https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form)save_formset
method on your ModelAdmin
(https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model)I never done something like this so I'm not completely sure how it will work out.
Since aa
is the set/object that might be null, can you check aa == null
?
(aa
/ xx
might be interchangeable (a typo in the question); the original question talks about xx
but only defines aa
)
i.e.
select new {
AssetID = x.AssetID,
Status = aa == null ? (bool?)null : aa.Online; // a Nullable<bool>
}
or if you want the default to be false
(not null
):
select new {
AssetID = x.AssetID,
Status = aa == null ? false : aa.Online;
}
Update; in response to the downvote, I've investigated more... the fact is, this is the right approach! Here's an example on Northwind:
using(var ctx = new DataClasses1DataContext())
{
ctx.Log = Console.Out;
var qry = from boss in ctx.Employees
join grunt in ctx.Employees
on boss.EmployeeID equals grunt.ReportsTo into tree
from tmp in tree.DefaultIfEmpty()
select new
{
ID = boss.EmployeeID,
Name = tmp == null ? "" : tmp.FirstName
};
foreach(var row in qry)
{
Console.WriteLine("{0}: {1}", row.ID, row.Name);
}
}
And here's the TSQL - pretty much what we want (it isn't ISNULL
, but it is close enough):
SELECT [t0].[EmployeeID] AS [ID],
(CASE
WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(10),@p0)
ELSE [t2].[FirstName]
END) AS [Name]
FROM [dbo].[Employees] AS [t0]
LEFT OUTER JOIN (
SELECT 1 AS [test], [t1].[FirstName], [t1].[ReportsTo]
FROM [dbo].[Employees] AS [t1]
) AS [t2] ON ([t0].[EmployeeID]) = [t2].[ReportsTo]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1
QED?
If you are running a linux server:
This system is quite secure/handy for homeservers -usually with all ports blocked by default-. You only have to forward the SSH port (don't use number 22).
If you like Microsoft Terminal Server you can even set a SSH Tunneling to your computer and connect securely to your web server throught it.
With ssh tunneling you even can forward the 3306 port of your remote server to a local port and connect using local phpMyAdmin or MySQL Workbench.
I understand that this option is an overkill, but is as secure as the access of your private key.
package com.sekurtrack.myapplication;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
ListView listView;
private BluetoothAdapter BA;
private ArrayList<String> mDeviceList = new ArrayList<String>();
private Set<BluetoothDevice> pairedDevices;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.devicesList);
BA = BluetoothAdapter.getDefaultAdapter();
BA.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
/* BA = BluetoothAdapter.getDefaultAdapter();
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);*/
}
@Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
Log.i("BT1", device.getName() + "\n" + device.getAddress());
listView.setAdapter(new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, mDeviceList));
}
}
};
}
you can use this add string to list on a button click
final String a[]={"hello","world"};
final ArrayAdapter<String> at=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a);
final ListView sp=(ListView)findViewById(R.id.listView1);
sp.setAdapter(at);
final EditText et=(EditText)findViewById(R.id.editText1);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
int k=sp.getCount();
String a1[]=new String[k+1];
for(int i=0;i<k;i++)
a1[i]=sp.getItemAtPosition(i).toString();
a1[k]=et.getText().toString();
ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);
sp.setAdapter(ats);
}
});
So on a button click it will get string from edittext and store in listitem. you can change this to your needs.
You can also use any()
, map()
like so:
if any(map(l.startswith, x)):
pass # Do something
Or alternatively, using a generator expression:
if any(l.startswith(s) for s in x)
pass # Do something
calloc
allocates the requested memory and returns a pointer to it. It also sets allocated memory to zero.
In case you are planning to use your string
as empty string all the time:
char *string = NULL;
string = (char*)calloc(1, sizeof(char));
In case you are planning to store some value in your string
later:
char *string = NULL;
int numberOfChars = 50; // you can use as many as you need
string = (char*)calloc(numberOfChars + 1, sizeof(char));
If you want to customize the message that being shown on empty table use this:
$('#example').dataTable( {
"oLanguage": {
"sEmptyTable": "My Custom Message On Empty Table"
}
} );
Since Datatable 1.10 you can do the following:
$('#example').DataTable( {
"language": {
"emptyTable": "My Custom Message On Empty Table"
}
} );
For the complete availble datatables custom messages for the table take a look at the following link reference/option/language
Easiest way to export Excel to Html table
$file_name ="file_name.xls";
$excel_file="Your Html Table Code";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file_name");
echo $excel_file;
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
No, don't do it that way.
From your Eclipse workspace, right click your project on the left pane -> Properties -> Java Build Path -> Add Jars -> add your jars here.
Tadaa!! :)
var seconds = 0;
setInterval(function () {
seconds++;
}, 1000);
There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.
Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.
You could also solve this by saving and comparing times.
EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.
you did not use S anywhere in your algorithm (besides modifying it). the idea of dijkstra is once a vertex is on S, it will not be modified ever again. in this case, once B is inside S, you will not reach it again via C.
this fact ensures the complexity of O(E+VlogV) [otherwise, you will repeat edges more then once, and vertices more then once]
in other words, the algorithm you posted, might not be in O(E+VlogV), as promised by dijkstra's algorithm.
I know that the problem was answered, but this could happen again and my solution was a little different from the ones that I found. In my case the solution wasn't related to include two different libraries in my project. See code below:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
This code was giving that error "Unexpected Top-Level Exception". I fix the code making the following changes:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects
.
See their examples:
string myJsonString = @"{
"Name": "Apple",
"Expiry": "\/Date(1230375600000+1300)\/",
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}";
// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);
Here is the solution I found on Hibernate 4.1.9. I had to pass a parameter to my query that can have value NULL sometimes. So I passed the using:
setParameter("orderItemId", orderItemId, new LongType())
After that, I use the following where clause in my query:
where ((:orderItemId is null) OR (orderItem.id != :orderItemId))
As you can see, I am using the Query.setParameter(String, Object, Type) method, where I couldn't use the Hibernate.LONG that I found in the documentation (probably that was on older versions). For a full set of options of type parameter, check the list of implementation class of org.hibernate.type.Type interface.
Hope this helps!
1) Put https://api-server.com/API/index.php/member/signin
in the url input box and choose POST
from the dropdown
2) In Headers tab, enter:
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
3) In Body tab, select the raw
radio button and write:
{"description":"","phone":"","lastname":"","app_version":"2.6.2","firstname":"","password":"my_pass","city":"","apikey":"213","lang":"fr","platform":"1","email":"[email protected]","pseudo":"example"}
select form-data
radio button and write:
key = name Value = userfile Select Text
key = filename Select File
and upload your profil.jpg
You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.
Also, remove the onclick="alert()"
from your submit. This is the cause for your first undefined
message.
<?php
$posted = false;
if( $_POST ) {
$posted = true;
// Database stuff here...
// $result = mysql_query( ... )
$result = $_POST['name'] == "danny"; // Dummy result
}
?>
<html>
<head></head>
<body>
<?php
if( $posted ) {
if( $result )
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
else
echo "<script type='text/javascript'>alert('failed!')</script>";
}
?>
<form action="" method="post">
Name:<input type="text" id="name" name="name"/>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
<v-btn color="info" @click="eliminarTarea(item.id)">Eliminar</v-btn>
And for your JS:
this.listaTareas = this.listaTareas.filter(i=>i.id != id)
To answer your question: It takes any error output (normally sent to stderr) and writes it to standard output (stdout).
This is helpful with, for example 'more' when you need paging for all output. Some programs like printing usage information into stderr.
To help you remember
"2>&1" simply points everything sent to stderr, to stdout instead.
I also recommend reading this post on error redirecting where this subject is covered in full detail.
I use sbt assembly to package my project. I also meet this problem. My solution is here. Step1: add META-INF mergestrategy in your build.sbt
case PathList("META-INF", "MANIFEST.MF") => MergeStrategy.discard
case PathList("META-INF", ps @ _*) => MergeStrategy.first
Step2: add hadoop-hdfs lib to build.sbt
"org.apache.hadoop" % "hadoop-hdfs" % "2.4.0"
Step3: sbt clean; sbt assembly
Hope the above information can help you.
We recently released a library that helps a lot to access private fields, methods and inner classes through reflection : BoundBox
For a class like
public class Outer {
private static class Inner {
private int foo() {return 2;}
}
}
It provides a syntax like :
Outer outer = new Outer();
Object inner = BoundBoxOfOuter.boundBox_new_Inner();
new BoundBoxOfOuter.BoundBoxOfInner(inner).foo();
The only thing you have to do to create the BoundBox class is to write @BoundBox(boundClass=Outer.class)
and the BoundBoxOfOuter
class will be instantly generated.
The best way to do this is here i found after searching for one issue after other in the LogCat
MediaPlayer mp;
mp = MediaPlayer.create(context, R.raw.sound_one);
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.reset();
mp.release();
mp=null;
}
});
mp.start();
Not releasing the Media player gives you this error in LogCat:
Android: MediaPlayer finalized without being released
Not resetting the Media player gives you this error in LogCat:
Android: mediaplayer went away with unhandled events
So play safe and simple code to use media player.
To play more than one sounds in same Activity/Fragment simply change the resID while creating new Media player like
mp = MediaPlayer.create(context, R.raw.sound_two);
and play it !
Have fun!
I needed to do many very simple XML requests and after reading @Ivan Krechetov's comment about the speed hit of SOAP, I tried his code and discovered http_post_data() is not built into PHP 5.2. Not really wanting to install it, I tried cURL which is on all my servers. Although I do not know how fast cURL is compared to SOAP, it sure was easy to do what I needed. Below is a sample with cURL for anyone needing it.
$xml_data = '<?xml version="1.0" encoding="UTF-8" ?>
<priceRequest><customerNo>123</customerNo><password>abc</password><skuList><SKU>99999</SKU><lineNumber>1</lineNumber></skuList></priceRequest>';
$URL = "https://test.testserver.com/PriceAvailability";
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
While you already have very good answers, I really like the explanation on this website: https://https.cio.gov/faq/#what-information-does-https-protect
in short: using HTTPS hides:
for mac
I removed all the old failed downloads of maven there were several versions of maven also on my mac
find ~/.m2 -name "*.lastUpdated" -exec grep -q "Could not transfer" {} ; -print -exec rm {} ;
after that, I simply updated my eclipse by
help -> check for updates
and the problem resolved for me
the main reason for this problem is the failed old updates does not allow you to download archetype so if you try to build project in any archetype of maven it gets failed
The native Python way for asynchronous calls in 2021 with Python 3.9 suitable also for Jupyter / Ipython Kernel
Camabeh's answer is the way to go since Python 3.3.
async def display_date(loop): end_time = loop.time() + 5.0 while True: print(datetime.datetime.now()) if (loop.time() + 1.0) >= end_time: break await asyncio.sleep(1) loop = asyncio.get_event_loop() # Blocking call which returns when the display_date() coroutine is done loop.run_until_complete(display_date(loop)) loop.close()
This will work in Jupyter Notebook / Jupyter Lab but throw an error:
RuntimeError: This event loop is already running
Due to Ipython's usage of event loops we need something called nested asynchronous loops which is not yet implemented in Python. Luckily there is nest_asyncio to deal with the issue. All you need to do is:
!pip install nest_asyncio # use ! within Jupyter Notebook, else pip install in shell
import nest_asyncio
nest_asyncio.apply()
(Based on this thread)
Only when you call loop.close()
it throws another error as it probably refers to Ipython's main loop.
RuntimeError: Cannot close a running event loop
I'll update this answer as soon as someone answered to this github issue.
Initializing the contents of a list like that isn't really what lists are for. Lists are designed to hold objects. If you want to map particular numbers to particular objects, consider using a key-value pair structure like a hash table or dictionary instead of a list.
Just want to share another option:
# mark two objects to be deleted
session.delete(obj1)
session.delete(obj2)
# commit (or flush)
session.commit()
http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#deleting
In this example, the following codes shall works fine:
obj = User.query.filter_by(id=123).one()
session.delete(obj)
session.commit()
I was using localhost during unit testing when my recaptcha key was registered to 127.0.0.1. So I changed my browser to point to 127.0.0.1 and it started working. Although I was able to add "localhost" to the list of domains in my ReCaptcha Key Settings, I am still unable to unit test using localhost. I have to use the loopback IP address 127.0.0.1.
I have an example about this.
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid body-content" ng-controller="formView">
<div class="row">
<div class="col-md-12">
<h4>Register Form</h4>
<form class="form-horizontal" ng-submit="" name="f" novalidate>
<div ng-repeat="item in elements" class="form-group">
<label>{{item.Label}}</label>
<element type="{{item.Type}}" model="item"></element>
</div>
<input ng-show="f.$valid" type="submit" id="submit" value="Submit" class="" />
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script src="app.js"></script>
</body>
</html>
angular.module('app', [])
.controller('formView', function ($scope) {
$scope.elements = [{
"Id":1,
"Type":"textbox",
"FormId":24,
"Label":"Name",
"PlaceHolder":"Place Holder Text",
"Max":20,
"Required":false,
"Options":null,
"SelectedOption":null
},
{
"Id":2,
"Type":"textarea",
"FormId":24,
"Label":"AD2",
"PlaceHolder":"Place Holder Text",
"Max":20,
"Required":true,
"Options":null,
"SelectedOption":null
}];
})
.directive('element', function () {
return {
restrict: 'E',
link: function (scope, element, attrs) {
scope.contentUrl = attrs.type + '.html';
attrs.$observe("ver", function (v) {
scope.contentUrl = v + '.html';
});
},
template: '<div ng-include="contentUrl"></div>'
}
})
Suppose for example your date is coming like this & you need to install momentjs for advance date features.
let cmpDate = Thu Aug 27 2020 00:00:00 GMT+0530 (India Standard Time)
let format = "MM/DD/YYYY";
let startDate: any = moment().format(format);
let endDate: any = moment().add(30, "days").format(format);
let compareDate: any = moment(cmpDate).format(format);
var startDate1 = startDate.split("/");
var startDate2 = endDate.split("/");
var compareDate1 = compareDate.split("/");
var fromDate = new Date(startDate1[2], parseInt(startDate1[1]) - 1, startDate1[0]);
var toDate = new Date(startDate2[2], parseInt(startDate2[1]) - 1, startDate2[0]);
var checkDate = new Date(compareDate1[2], parseInt(compareDate1[1]) - 1, compareDate1[0]);
if (checkDate > fromDate && checkDate < toDate) {
... condition works between current date to next 30 days
}
This is from the book Hackers: Heroes of the Computer Revolution by Steven Levy.
.. the memory had been reduced to 4096 "words" of eighteen bits each. (A "bit" is a binary digit, either a 1 or 0. A series of binary numbers is called a "word").
As the other answers suggest, a "word" does not seem to have a fixed length.
Known Windows Services That Listen on Port 80
From Services Manager (run: services.msc), stop and disable these Windows Services which are known to bind to port 80.
Double click Service, and change ‘Startup Type’ to ‘Disabled’…
skype also using port 80 as default setting and you can uncheck it.
You might, or might not, have some of these Services installed and running.
In my case "SQL Server Reporting Services" was opening port 80.
You can simply download the library which you want to include and copy it to libs folder of your project. Then select that file (in my case it was android-support-v4 library) right click on it and select "Add as Library"
I found that the accepted answer's solution unfortunately does not compile on Swift 3 for Linux. Here's a modified version, then, that does:
import Foundation
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try RegularExpression(pattern: regex, options: [])
let nsString = NSString(string: text)
let results = regex.matches(in: text, options: [], range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range) }
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
The main differences are:
Swift on Linux seems to require dropping the NS
prefix on Foundation objects for which there is no Swift-native equivalent. (See Swift evolution proposal #86.)
Swift on Linux also requires specifying the options
arguments for both the RegularExpression
initialization and the matches
method.
For some reason, coercing a String
into an NSString
doesn't work in Swift on Linux but initializing a new NSString
with a String
as the source does work.
This version also works with Swift 3 on macOS / Xcode with the sole exception that you must use the name NSRegularExpression
instead of RegularExpression
.
You should look at MoSync too, MoSync gives you standard C/C++, easy-to-use well-documented APIs, and a full-featured Eclipse-based IDE. Its now a open sourced IDE still pretty cool but not maintained anymore.
"You could also use find and sed, but I find that this little line of perl works nicely.
perl -pi -w -e 's/search/replace/g;' *.php
" (Extracted from http://www.liamdelahunty.com/tips/linux_search_and_replace_multiple_files.php)
My best results come from using perl and grep (to ensure that file have the search expression )
perl -pi -w -e 's/search/replace/g;' $( grep -rl 'search' )
I just solved this problem for myself writing a global dotnet tool (that also takes into account git+history).
Install via
dotnet tool install -g ModernRonin.ProjectRenamer
, use with renameproject <oldName> <newName>
.
Documentation/Tinkering/PRs at
In some cases your image can be Alpine-based. In this case it will throw:
OCI runtime exec failed: exec failed: container_linux.go:348: starting container process caused "exec: \"bash\": executable file not found in $PATH": unknown
Because /bin/bash
doesn't exist. Instead of this you should use:
docker exec -it 9f7d99aa6625 ash
or
docker exec -it 9f7d99aa6625 sh
Try this:
$('element').attr('id', 'value');
So it becomes;
$(function() {
$('span .breadcrumb').each(function(){
$('#nav').attr('id', $(this).text());
$('#container').attr('id', $(this).text());
$('.stretch_footer').attr('id', $(this).text())
$('#footer').attr('id', $(this).text());
});
});
So you are changing/overwriting the id of three elements and adding an id to one element. You can modify as per you needs...
Setup:
My OS windows 8 64bit
Eclipse version Standard/SDK Kepler Service Release 2
My JDK is jdk-8u5-windows-i586
My JRE is jre-8u5-windows-i586
This how I overcome my error.
At the very first my Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
also didn't work.
Then I login to this website and downloaded the UCanAccess 2.0.8 zip (as Mr.Gord Thompson said) file and unzip it.
Then you will also able to find these *.jar files in that unzip folder:
ucanaccess-2.0.8.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.0.4.jar
Then what I did was I copied all these 5 files and paste them in these 2 locations:
C:\Program Files (x86)\eclipse\lib
C:\Program Files (x86)\eclipse\lib\ext
(I did that funny thing becoz I was unable to import these libraries to my project)
Then I reopen the eclipse with my project.then I see all that *.jar files in my project's JRE System Library folder.
Finally my code works.
public static void main(String[] args)
{
try
{
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\Hasith\\Documents\\JavaDatabase1.mdb");
Statement stment = conn.createStatement();
String qry = "SELECT * FROM Table1";
ResultSet rs = stment.executeQuery(qry);
while(rs.next())
{
String id = rs.getString("ID") ;
String fname = rs.getString("Nama");
System.out.println(id + fname);
}
}
catch(Exception err)
{
System.out.println(err);
}
//System.out.println("Hasith Sithila");
}
This error is because of deleting R.java
file from project /gen
folder. If you have backup of your project, please go to the project directory and paste R.java
file which you copy from your backup section.
Corrupt R.java file can also be caused by an error in XML. Often these kinds of errors don't show up in eclipse, so I'd suggest taking a look at your XML files. After that you can also try to Clean
your project by going to Project -> Clean...
in the menu bar.
You won't be able to do this easily with plain javascript. When you post a form, the form inputs are sent to the server and your page is refreshed - the data is handled on the server side. That is, the submit()
function doesn't actually return anything, it just sends the form data to the server.
If you really wanted to get the response in Javascript (without the page refreshing), then you'll need to use AJAX, and when you start talking about using AJAX, you'll need to use a library. jQuery is by far the most popular, and my personal favourite. There's a great plugin for jQuery called Form which will do exactly what it sounds like you want.
Here's how you'd use jQuery and that plugin:
$('#myForm')
.ajaxForm({
url : 'myscript.php', // or whatever
dataType : 'json',
success : function (response) {
alert("The server says: " + response);
}
})
;
Using PyCharm IDE.
You can
comment
anduncomment
lines of code using Ctrl+/. Ctrl+/ comments or uncomments the current line or several selected lines with single line comments({# in Django templates, or # in Python scripts)
.Pressing Ctrl+Shift+/
for a selected block of source code in a Django template surrounds the block with{% comment %} and {% endcomment %}
tags.
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print("Loop ended.")
Select all lines then press Ctrl + /
# n = 5
# while n > 0:
# n -= 1
# if n == 2:
# break
# print(n)
# print("Loop ended.")
There is also multipanelfigure package that is worth to mention. See also this answer.
library(ggplot2)
theme_set(theme_bw())
q1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
q2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
q3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec))
q4 <- ggplot(mtcars) + geom_bar(aes(carb))
library(magrittr)
library(multipanelfigure)
figure1 <- multi_panel_figure(columns = 2, rows = 2, panel_label_type = "none")
# show the layout
figure1
figure1 %<>%
fill_panel(q1, column = 1, row = 1) %<>%
fill_panel(q2, column = 2, row = 1) %<>%
fill_panel(q3, column = 1, row = 2) %<>%
fill_panel(q4, column = 2, row = 2)
figure1
# complex layout
figure2 <- multi_panel_figure(columns = 3, rows = 3, panel_label_type = "upper-roman")
figure2
figure2 %<>%
fill_panel(q1, column = 1:2, row = 1) %<>%
fill_panel(q2, column = 3, row = 1) %<>%
fill_panel(q3, column = 1, row = 2) %<>%
fill_panel(q4, column = 2:3, row = 2:3)
figure2
Created on 2018-07-06 by the reprex package (v0.2.0.9000).
This defines what shell (command interpreter) you are using for interpreting/running your script. Each shell is slightly different in the way it interacts with the user and executes scripts (programs).
When you type in a command at the Unix prompt, you are interacting with the shell.
E.g., #!/bin/csh
refers to the C-shell, /bin/tcsh
the t-shell, /bin/bash
the bash shell, etc.
You can tell which interactive shell you are using the
echo $SHELL
command, or alternatively
env | grep -i shell
You can change your command shell with the chsh
command.
Each has a slightly different command set and way of assigning variables and its own set of programming constructs. For instance the if-else statement with bash looks different that the one in the C-shell.
This page might be of interest as it "translates" between bash and tcsh commands/syntax.
Using the directive in the shell script allows you to run programs using a different shell. For instance I use the tcsh
shell interactively, but often run bash scripts using /bin/bash in the script file.
Aside:
This concept extends to other scripts too. For instance if you program in Python you'd put
#!/usr/bin/python
at the top of your Python program
No, you cannot do this. The values in the IN clause must be exact matches. You could modify the select thusly:
SELECT *
FROM tbl
WHERE my_col LIKE %val1%
OR my_col LIKE %val2%
OR my_col LIKE %val3%
...
If the val1, val2, val3... are similar enough, you might be able to use regular expressions in the REGEXP_LIKE operator.
I'm using Eclipse and I copied your code and got the same error. I then opened up the project properties->Java Build Path -> Libraries->Add External JARs... c:\jrun4\lib\sqlitejdbc-v056.jar Worked like a charm. You may need to restart your web server if you've just copied the .jar file.
You can also do this if you want to play around with pandas. However, I like punchagan's way.
# replicating your dataframe
lake = pd.DataFrame({'co tp': ['DE Lake', 'Forest', 'FR Lake', 'Forest'],
'area': [10, 20, 30, 40],
'count': [7, 5, 2, 3]})
lake.set_index('co tp', inplace=True)
# to get key value using pandas
area_dict = lake.set_index('area').T.to_dict('records')[0]
print(area_dict)
output: {10: 7, 20: 5, 30: 2, 40: 3}
By using transform: works like a charm!
<div class="parent">
<span>center content using transform</span>
</div>
//CSS
.parent {
position: relative;
height: 200px;
border: 1px solid;
}
.parent span {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
I tried this tool and it gave me good results.
public final Map<String, List<String>> stringMap = new ConcurrentHashMap<String, List<String>>() {
@Nullable
@Override
public List<String> get(@NonNull Object key) {
return computeIfAbsent((String) key, s -> new ArrayList<String>());
}
};
HashMap cause dead loop, so use ConcurrentHashMap instead of HashMap,
There exist breakpoint()
method nowadays, which replaces import pdb; pdb.set_trace()
.
It also has several new features, such as possible environment variables.
The difference is the amount of memory allocated to each integer, and how large a number they each can store.
In Access 2013. Drop a "Text Box" control onto your form. On the Property Sheet for the control under the Format tab find the Format property. Set this to one of the date format options. Job's done.
Another reason this can happen is if you send the wrong appId. This can happen in early development if you have a development app and a production app. If you hard-code the appId for dev and push to prod, this will show up.
Here are a lot of answers already but non of them worked for me. Fyi I have a Lenovo laptop with win10 and what works for me is the following:
Paste = Shift+fn+prt sc
Copy = Shift+fn+c
cp -r /home/server/folder/test /home/server/
can try this
select (CONVERT(VARCHAR(10),GETDATE()+360,110)) as Date_Result
\d*\.\d*
Explanation:
\d* - any number of digits
\. - a dot
\d* - more digits.
This will match 123.456
, .123
, 123.
, but not 123
If you want the dot to be optional, in most languages (don't know about jquery) you can use
\d*\.?\d*
With eval("my script here")
function.
Hi every one this code is workin for me please try with this for sending mail to multiple recepients
private String recipient = "[email protected] ,[email protected] ";
String[] recipientList = recipient.split(",");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String recipient : recipientList) {
recipientAddress[counter] = new InternetAddress(recipient.trim());
counter++;
}
message.setRecipients(Message.RecipientType.TO, recipientAddress);
You can use 100vw / 100vh
. CSS3 gives us viewport-relative units. 100vw means 100% of the viewport width. 100vh; 100% of the height.
<div style="display:flex; justify-content: space-between;background-color: lightyellow; width:100%; height:85vh">
<div style="width:70%; height: 100%; border: 2px dashed red"></div>
<div style="width:30%; height: 100%; border: 2px dashed red"></div>
</div>
well, I actually just saved and closed the project and restarted VS Express 2013 in windows 8 and that sorted my problem.
You cannot open a connection directly to a path on a remote host using fsockopen
. The url www.mydomain.net/1/file.php
contains a path, when the only valid value for that first parameter is the host, www.mydomain.net
.
If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.
If you only want to send an HTTP request and ignore the response, you could use fsockopen()
and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen()
, it might look something like this:
$fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
fputs($fp, "GET /1/file.php HTTP/1.1\n");
fputs($fp, "Host: www.mydomain.net\n");
fputs($fp, "Connection: close\n\n");
That leaves any error handling up to you of course, but it would mean that you wouldn't waste time reading the response.
The following works for me in Firefox and Internet Explorer:
<object id="mediaplayer" classid="clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701" standby="loading microsoft windows media player components..." type="application/x-oleobject" width="320" height="310">
<param name="filename" value="./test.wmv">
<param name="animationatstart" value="true">
<param name="transparentatstart" value="true">
<param name="autostart" value="true">
<param name="showcontrols" value="true">
<param name="ShowStatusBar" value="true">
<param name="windowlessvideo" value="true">
<embed src="./test.wmv" autostart="true" showcontrols="true" showstatusbar="1" bgcolor="white" width="320" height="310">
</object>
For this type error: UnexpectedTypeException ERROR: We are trying to use incorrect Hibernate validator annotation on any bean property. For this same issue for my Springboot project( validating type 'java.lang.Integer')
The solution that worked for me is using @NotNull
for Integer.
LinkedHashMap
is precisely what you're looking for.
It is exactly like HashMap
, except that when you iterate over it, it presents the items in the insertion order.
Yes:
df -k .
for the current directory.
df -k /some/dir
if you want to check a specific directory.
You might also want to check out the stat(1)
command if your system has it. You can specify output formats to make it easier for your script to parse. Here's a little example:
$ echo $(($(stat -f --format="%a*%S" .)))
The server certificate is invalid, either because it is signed by an invalid CA (internal CA, self signed,...), doesn't match the server's name or because it is expired.
Either way, you need to find how to tell to the Python library that you are using that it must not stop at an invalid certificate if you really want to download files from this server.
All objects in Java are references and you can use them like pointers.
abstract class Animal
{...
}
class Lion extends Animal
{...
}
class Tiger extends Animal
{
public Tiger() {...}
public void growl(){...}
}
Tiger first = null;
Tiger second = new Tiger();
Tiger third;
Dereferencing a null:
first.growl(); // ERROR, first is null.
third.growl(); // ERROR, third has not been initialized.
Aliasing Problem:
third = new Tiger();
first = third;
Losing Cells:
second = third; // Possible ERROR. The old value of second is lost.
You can make this safe by first assuring that there is no further need of the old value of second or assigning another pointer the value of second.
first = second;
second = third; //OK
Note that giving second a value in other ways (NULL, new...) is just as much a potential error and may result in losing the object that it points to.
The Java system will throw an exception (OutOfMemoryError
) when you call new and the allocator cannot allocate the requested cell. This is very rare and usually results from run-away recursion.
Note that, from a language point of view, abandoning objects to the garbage collector are not errors at all. It is just something that the programmer needs to be aware of. The same variable can point to different objects at different times and old values will be reclaimed when no pointer references them. But if the logic of the program requires maintaining at least one reference to the object, It will cause an error.
Novices often make the following error.
Tiger tony = new Tiger();
tony = third; // Error, the new object allocated above is reclaimed.
What you probably meant to say was:
Tiger tony = null;
tony = third; // OK.
Improper Casting:
Lion leo = new Lion();
Tiger tony = (Tiger)leo; // Always illegal and caught by compiler.
Animal whatever = new Lion(); // Legal.
Tiger tony = (Tiger)whatever; // Illegal, just as in previous example.
Lion leo = (Lion)whatever; // Legal, object whatever really is a Lion.
Pointers in C:
void main() {
int* x; // Allocate the pointers x and y
int* y; // (but not the pointees)
x = malloc(sizeof(int)); // Allocate an int pointee,
// and set x to point to it
*x = 42; // Dereference x to store 42 in its pointee
*y = 13; // CRASH -- y does not have a pointee yet
y = x; // Pointer assignment sets y to point to x's pointee
*y = 13; // Dereference y to store 13 in its (shared) pointee
}
Pointers in Java:
class IntObj {
public int value;
}
public class Binky() {
public static void main(String[] args) {
IntObj x; // Allocate the pointers x and y
IntObj y; // (but not the IntObj pointees)
x = new IntObj(); // Allocate an IntObj pointee
// and set x to point to it
x.value = 42; // Dereference x to store 42 in its pointee
y.value = 13; // CRASH -- y does not have a pointee yet
y = x; // Pointer assignment sets y to point to x's pointee
y.value = 13; // Deference y to store 13 in its (shared) pointee
}
}
UPDATE: as suggested in the comments one must note that C has pointer arithmetic. However, we do not have that in Java.
I have a jQuery plugin called waitForImages
that can detect when background images have downloaded.
$('body')
.css('background-image','url(http://picture.de/image.png)')
.waitForImages(function() {
alert('Background image done loading');
// This *does* work
}, $.noop, true);
You can do this by setting the date of expiry to yesterday.
Setting it to "-1" doesn't work. That marks a cookie as a Sessioncookie.
Bash supports a concept called "Positional Parameters". These positional parameters represent arguments that are specified on the command line when a Bash script is invoked.
Positional parameters are referred to by the names $0
, $1
, $2
... and so on. $0
is the name of the script itself, $1
is the first argument to the script, $2
the second, etc. $*
represents all of the positional parameters, except for $0
(i.e. starting with $1
).
An example:
#!/bin/bash
FILE="$1"
externalprogram "$FILE" <other-parameters>
If the functions are re-written with completely different variables and we call id on them, it then illustrates the point well. I didn't get this at first and read jfs' post with the great explanation, so I tried to understand/convince myself:
def f(y, z):
y = 2
z.append(4)
print ('In f(): ', id(y), id(z))
def main():
n = 1
x = [0,1,2,3]
print ('Before in main:', n, x,id(n),id(x))
f(n, x)
print ('After in main:', n, x,id(n),id(x))
main()
Before in main: 1 [0, 1, 2, 3] 94635800628352 139808499830024
In f(): 94635800628384 139808499830024
After in main: 1 [0, 1, 2, 3, 4] 94635800628352 139808499830024
z and x have the same id. Just different tags for the same underlying structure as the article says.
Have you tried this in your application.properties?
spring.jackson.time-zone= # Time zone used when formatting dates. For instance `America/Los_Angeles`
The most simple way I found was to create a stored procedure. Enter the 'JobName' and hit go.
/*-----------------------------------------------------------------------------------------------------------
Document Title: usp_getJobStatus
Purpose: Finds a Current Jobs Run Status
Input Example: EXECUTE usp_getJobStatus 'MyJobName'
-------------------------------------------------------------------------------------------------------------*/
IF OBJECT_ID ( 'usp_getJobStatus','P' ) IS NOT NULL
DROP PROCEDURE usp_getJobStatus;
GO
CREATE PROCEDURE usp_getJobStatus
@JobName NVARCHAR (1000)
AS
IF OBJECT_ID('TempDB..#JobResults','U') IS NOT NULL DROP TABLE #JobResults
CREATE TABLE #JobResults ( Job_ID UNIQUEIDENTIFIER NOT NULL,
Last_Run_Date INT NOT NULL,
Last_Run_Time INT NOT NULL,
Next_Run_date INT NOT NULL,
Next_Run_Time INT NOT NULL,
Next_Run_Schedule_ID INT NOT NULL,
Requested_to_Run INT NOT NULL,
Request_Source INT NOT NULL,
Request_Source_id SYSNAME
COLLATE Database_Default NULL,
Running INT NOT NULL,
Current_Step INT NOT NULL,
Current_Retry_Attempt INT NOT NULL,
Job_State INT NOT NULL )
INSERT #JobResults
EXECUTE master.dbo.xp_sqlagent_enum_jobs 1, '';
SELECT job.name AS [Job_Name],
( SELECT MAX(CAST( STUFF(STUFF(CAST(jh.run_date AS VARCHAR),7,0,'-'),5,0,'-') + ' ' +
STUFF(STUFF(REPLACE(STR(jh.run_time,6,0),' ','0'),5,0,':'),3,0,':') AS DATETIME))
FROM msdb.dbo.sysjobs AS j
INNER JOIN msdb.dbo.sysjobhistory AS jh
ON jh.job_id = j.job_id AND jh.step_id = 0
WHERE j.[name] LIKE '%' + @JobName + '%'
GROUP BY j.[name] ) AS [Last_Completed_DateTime],
( SELECT TOP 1 start_execution_date
FROM msdb.dbo.sysjobactivity
WHERE job_id = r.job_id
ORDER BY start_execution_date DESC ) AS [Job_Start_DateTime],
CASE
WHEN r.running = 0 THEN
CASE
WHEN jobInfo.lASt_run_outcome = 0 THEN 'Failed'
WHEN jobInfo.lASt_run_outcome = 1 THEN 'Success'
WHEN jobInfo.lASt_run_outcome = 3 THEN 'Canceled'
ELSE 'Unknown'
END
WHEN r.job_state = 0 THEN 'Success'
WHEN r.job_state = 4 THEN 'Success'
WHEN r.job_state = 5 THEN 'Success'
WHEN r.job_state = 1 THEN 'In Progress'
WHEN r.job_state = 2 THEN 'In Progress'
WHEN r.job_state = 3 THEN 'In Progress'
WHEN r.job_state = 7 THEN 'In Progress'
ELSE 'Unknown' END AS [Run_Status_Description]
FROM #JobResults AS r
LEFT OUTER JOIN msdb.dbo.sysjobservers AS jobInfo
ON r.job_id = jobInfo.job_id
INNER JOIN msdb.dbo.sysjobs AS job
ON r.job_id = job.job_id
WHERE job.[enabled] = 1
AND job.name LIKE '%' + @JobName + '%'
Similar to another answer here, but change the http in the rewrite to to $scheme like so:
server {
listen 80;
server_name test.com;
rewrite ^ $scheme://www.test.com$request_uri? permanent;
}
And edit your main server block server_name variable as following:
server_name www.test.com;
I had to do this to redirect www.test.com to test.com.
For those who understand the bias problem but can't stand the unpredictable run-time of rejection-based methods, this series produces a progressively less biased random integer in the [0, n-1]
interval:
r = n / 2;
r = (rand() * n + r) / (RAND_MAX + 1);
r = (rand() * n + r) / (RAND_MAX + 1);
r = (rand() * n + r) / (RAND_MAX + 1);
...
It does so by synthesising a high-precision fixed-point random number of i * log_2(RAND_MAX + 1)
bits (where i
is the number of iterations) and performing a long multiplication by n
.
When the number of bits is sufficiently large compared to n
, the bias becomes immeasurably small.
It does not matter if RAND_MAX + 1
is less than n
(as in this question), or if it is not a power of two, but care must be taken to avoid integer overflow if RAND_MAX * n
is large.
The Array.newInstance(Class<?> componentType, int length)
method is to be used to create an array with dynamically length.
Multi-dimensional arrays can be created similarly with the Array.newInstance(Class<?> componentType, int... dimensions)
method.
Create this function prototype:
Array.prototype.contains = function ( needle ) {
for (i in this) {
if (this[i] == needle) return true;
}
return false;
}
and then you can use following code to search in array x
if (x.contains('searchedString')) {
// do a
}
else
{
// do b
}
You can even pass parameters to the sed command:
test.sh
#!/bin/bash
echo "-> start"
for i in $(seq 5); do
# passing parameters to sed
j=$(($i+3))
sed -i "${j}s/.*/replaced by '$i'!/" output.dat
done
echo "-> finished"
exit
orignial output.dat:
a
b
c
d
e
f
g
h
i
j
Executing ./test.sh gives the new output.dat
a
b
c
replaced by '1'!
replaced by '2'!
replaced by '3'!
replaced by '4'!
replaced by '5'!
i
j
This question has already been marked answered, but I'd like to share some information that might help others with using FileList.
It would be convenient to treat a FileList as an array, but methods like sort, shift, pop, and slice don't work. As others have suggested, you can copy the FileList to an array. However, rather than using a loop, there's a simple one line solution to handle this conversion.
// fileDialog.files is a FileList
var fileBuffer=[];
// append the file list to an array
Array.prototype.push.apply( fileBuffer, fileDialog.files ); // <-- here
// And now you may manipulated the result as required
// shift an item off the array
var file = fileBuffer.shift(0,1); // <-- works as expected
console.info( file.name + ", " + file.size + ", " + file.type );
// sort files by size
fileBuffer.sort(function(a,b) {
return a.size > b.size ? 1 : a.size < b.size ? -1 : 0;
});
Tested OK in FF, Chrome, and IE10+
I have created main.css file and included all css files in it.
We can include only one main.css file
@import url('style.css');
@import url('platforms.css');
For the asynchronous dispatch case you describe above, you shouldn't need to check if you're on the main thread. As Bavarious indicates, this will simply be queued up to be run on the main thread.
However, if you attempt to do the above using a dispatch_sync()
and your callback is on the main thread, your application will deadlock at that point. I describe this in my answer here, because this behavior surprised me when moving some code from -performSelectorOnMainThread:
. As I mention there, I created a helper function:
void runOnMainQueueWithoutDeadlocking(void (^block)(void))
{
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}
}
which will run a block synchronously on the main thread if the method you're in isn't currently on the main thread, and just executes the block inline if it is. You can employ syntax like the following to use this:
runOnMainQueueWithoutDeadlocking(^{
//Do stuff
});
What's wrong with actually using ng-animate
for ng-show
as you mentioned?
<script src="lib/angulr.js"></script>
<script src="lib/angulr_animate.js"></script>
<script>
var app=angular.module('ang_app', ['ngAnimate']);
app.controller('ang_control01_main', function($scope) {
});
</script>
<style>
#myDiv {
transition: .5s;
background-color: lightblue;
height: 100px;
}
#myDiv.ng-hide {
height: 0;
}
</style>
<body ng-app="ang_app" ng-controller="ang_control01_main">
<input type="checkbox" ng-model="myCheck">
<div id="myDiv" ng-show="myCheck"></div>
</body>
You'll have to create a Console window manually before you actually call any Console.Write methods. That will init the Console to work properly without changing the project type (which for WPF application won't work).
Here's a complete source code example, of how a ConsoleManager class might look like, and how it can be used to enable/disable the Console, independently of the project type.
With the following class, you just need to write ConsoleManager.Show()
somewhere before any call to Console.Write
...
[SuppressUnmanagedCodeSecurity]
public static class ConsoleManager
{
private const string Kernel32_DllName = "kernel32.dll";
[DllImport(Kernel32_DllName)]
private static extern bool AllocConsole();
[DllImport(Kernel32_DllName)]
private static extern bool FreeConsole();
[DllImport(Kernel32_DllName)]
private static extern IntPtr GetConsoleWindow();
[DllImport(Kernel32_DllName)]
private static extern int GetConsoleOutputCP();
public static bool HasConsole
{
get { return GetConsoleWindow() != IntPtr.Zero; }
}
/// <summary>
/// Creates a new console instance if the process is not attached to a console already.
/// </summary>
public static void Show()
{
//#if DEBUG
if (!HasConsole)
{
AllocConsole();
InvalidateOutAndError();
}
//#endif
}
/// <summary>
/// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown.
/// </summary>
public static void Hide()
{
//#if DEBUG
if (HasConsole)
{
SetOutAndErrorNull();
FreeConsole();
}
//#endif
}
public static void Toggle()
{
if (HasConsole)
{
Hide();
}
else
{
Show();
}
}
static void InvalidateOutAndError()
{
Type type = typeof(System.Console);
System.Reflection.FieldInfo _out = type.GetField("_out",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
System.Reflection.FieldInfo _error = type.GetField("_error",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod("InitializeStdOutError",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
Debug.Assert(_out != null);
Debug.Assert(_error != null);
Debug.Assert(_InitializeStdOutError != null);
_out.SetValue(null, null);
_error.SetValue(null, null);
_InitializeStdOutError.Invoke(null, new object[] { true });
}
static void SetOutAndErrorNull()
{
Console.SetOut(TextWriter.Null);
Console.SetError(TextWriter.Null);
}
}
We have to dynamically set the attribute target="_blank" and it will open it in new tab.
document.getElementsByTagName("a")[0].setAttribute('target', '_blank')
document.getElementsByTagName("a")[0].click()
If you want to open in new window, get the href link and use window.open
var link = document.getElementsByTagName("a")[0].getAttribute("href");
window.open(url, "","height=500,width=500");
Don't provide the second parameter as _blank in the above.
Sorry for tacking on to an old thread, but I think something that was said above may be incorrect/misleading.
From what I can tell .Timeout is NOT the connection time, it is the TOTAL time allowed for the entire life of the HttpWebRequest and response. Proof:
I Set:
.Timeout=5000
.ReadWriteTimeout=32000
The connect and post time for the HttpWebRequest took 26ms
but the subsequent call HttpWebRequest.GetResponse() timed out in 4974ms thus proving that the 5000ms was the time limit for the whole send request/get response set of calls.
I didn't verify if the DNS name resolution was measured as part of the time as this is irrelevant to me since none of this works the way I really need it to work--my intention was to time out quicker when connecting to systems that weren't accepting connections as shown by them failing during the connect phase of the request.
For example: I'm willing to wait 30 seconds on a connection request that has a chance of returning a result, but I only want to burn 10 seconds waiting to send a request to a host that is misbehaving.
Depending on which OS you're using, if you are flexible, then CHOICE
can be used to wait on almost any key EXCEPT
enter
If you are really referring to what Microsoft insists on calling "Command Prompt" which is simply an MS-DOS emulator, then perhaps TIMEOUT
may suit your purpose (timeout /t -1
waits on any key, not just ENTER
) and of course CHOICE
is available again in recent WIN editions.
And a warning on SET /P
- whereas set /p DUMMY=Hit ENTER to continue...
will work,
set "dummy="
set /p DUMMY=Hit ENTER to continue...
if defined dummy (echo not just ENTER was pressed) else (echo just ENTER was pressed)
will detect whether just ENTER or something else, ending in ENTER was keyed in.
The SELECT ... INTO
needs to be in the select from the CTE.
;WITH Calendar
AS (SELECT /*... Rest of CTE definition removed for clarity*/)
SELECT EventID,
EventStartDate,
EventEndDate,
PlannedDate AS [EventDates],
Cast(PlannedDate AS DATETIME) AS DT,
Cast(EventStartTime AS TIME) AS ST,
Cast(EventEndTime AS TIME) AS ET,
EventTitle,
EventType
INTO TEMPBLOCKEDDATES /* <---- INTO goes here*/
FROM Calendar
WHERE ( PlannedDate >= Getdate() )
AND ',' + EventEnumDays + ',' LIKE '%,' + Cast(Datepart(dw, PlannedDate) AS CHAR(1)) + ',%'
OR EventEnumDays IS NULL
ORDER BY EventID,
PlannedDate
OPTION (maxrecursion 0)
Without opening Xcode:
open /Applications/Xcode.app/Contents/Developer/Applications/iOS\ Simulator.app/
Those settings (core.whitespace
and apply.whitespace
) are not there to remove trailing whitespace but to:
core.whitespace
: detect them, and raise errors apply.whitespace
: and strip them, but only during patch, not "always automatically"I believe the git hook pre-commit
would do a better job for that (includes removing trailing whitespace)
Note that at any given time you can choose to not run the pre-commit
hook:
git commit --no-verify .
cd .git/hooks/ ; chmod -x pre-commit
Warning: by default, a pre-commit
script (like this one), has not a "remove trailing" feature", but a "warning" feature like:
if (/\s$/) {
bad_line("trailing whitespace", $_);
}
You could however build a better pre-commit
hook, especially when you consider that:
Committing in Git with only some changes added to the staging area still results in an “atomic” revision that may never have existed as a working copy and may not work.
For instance, oldman proposes in another answer a pre-commit
hook which detects and remove whitespace.
Since that hook get the file name of each file, I would recommend to be careful for certain type of files: you don't want to remove trailing whitespace in .md
(markdown) files!
The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.
You need to move WC-BlackonWhite.jpg
into your src
directory. The public
directory is for static files that's going to be linked directly in the HTML (such as the favicon), not stuff that you're going to import directly into your bundle.
Try setting tableFooterView tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNonzeroMagnitude))
I'm sure there are other ways to accomplish this, but one solution would be to use join
through the Query Builder.
If you have tables set up something like this:
users
id
...
friends
id
user_id
friend_id
...
votes, comments and status_updates (3 tables)
id
user_id
....
In your User model:
class User extends Eloquent {
public function friends()
{
return $this->hasMany('Friend');
}
}
In your Friend model:
class Friend extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
Then, to gather all the votes for the friends of the user with the id of 1, you could run this query:
$user = User::find(1);
$friends_votes = $user->friends()
->with('user') // bring along details of the friend
->join('votes', 'votes.user_id', '=', 'friends.friend_id')
->get(['votes.*']); // exclude extra details from friends table
Run the same join
for the comments
and status_updates
tables. If you would like votes, comments, and status_updates to be in one chronological list, you can merge the resulting three collections into one and then sort the merged collection.
Edit
To get votes, comments, and status updates in one query, you could build up each query and then union the results. Unfortunately, this doesn't seem to work if we use the Eloquent hasMany
relationship (see comments for this question for a discussion of that problem) so we have to modify to queries to use where
instead:
$friends_votes =
DB::table('friends')->where('friends.user_id','1')
->join('votes', 'votes.user_id', '=', 'friends.friend_id');
$friends_comments =
DB::table('friends')->where('friends.user_id','1')
->join('comments', 'comments.user_id', '=', 'friends.friend_id');
$friends_status_updates =
DB::table('status_updates')->where('status_updates.user_id','1')
->join('friends', 'status_updates.user_id', '=', 'friends.friend_id');
$friends_events =
$friends_votes
->union($friends_comments)
->union($friends_status_updates)
->get();
At this point, though, our query is getting a bit hairy, so a polymorphic relationship with and an extra table (like DefiniteIntegral suggests below) might be a better idea.
just parse as an array:
Review[] reviews = new Gson().fromJson(jsonString, Review[].class);
then if you need you can also create a list in this way:
List<Review> asList = Arrays.asList(reviews);
P.S. your json string should be look like this:
[
{
"reviewerID": "A2SUAM1J3GNN3B1",
"asin": "0000013714",
"reviewerName": "J. McDonald",
"helpful": [2, 3],
"reviewText": "I bought this for my husband who plays the piano.",
"overall": 5.0,
"summary": "Heavenly Highway Hymns",
"unixReviewTime": 1252800000,
"reviewTime": "09 13, 2009"
},
{
"reviewerID": "A2SUAM1J3GNN3B2",
"asin": "0000013714",
"reviewerName": "J. McDonald",
"helpful": [2, 3],
"reviewText": "I bought this for my husband who plays the piano.",
"overall": 5.0,
"summary": "Heavenly Highway Hymns",
"unixReviewTime": 1252800000,
"reviewTime": "09 13, 2009"
},
[...]
]
I ran into this issue over the past couple days. Like Omri Aharon said in their answer above, it is important to add definitions for your prop types similar to:
SomeClass.propTypes = {
someProp: PropTypes.number,
onTap: PropTypes.func,
};
Don't forget to add the prop definitions outside of your class. I would place it right below/above my class. If you are not sure what your variable type or suffix is for your PropType (ex: PropTypes.number), refer to this npm reference. To Use PropTypes, you must import the package:
import PropTypes from 'prop-types';
If you get the linting error:someProp is not required, but has no corresponding defaultProps declaration
all you have to do is either add .isRequired
to the end of your prop definition like so:
SomeClass.propTypes = {
someProp: PropTypes.number.isRequired,
onTap: PropTypes.func.isRequired,
};
OR add default prop values like so:
SomeClass.defaultProps = {
someProp: 1
};
If you are anything like me, unexperienced or unfamiliar with reactjs, you may also get this error: Must use destructuring props assignment
. To fix this error, define your props before they are used. For example:
const { someProp } = this.props;
Highlight the cell(s)/column which you want as Duration, right click on the mouse to "Format Cells". Go to "Custom" and look for "h:mm" if you want to input duration in hour and minutes format. If you want to include seconds as well, click on "h:mm:ss". You can even add up the total duration after that.
Hope this helps.
You simply need to start mysql
and feed it with the content of db.sql
:
mysql -u user -p < db.sql
The communication link between the driver and the data source to which the driver was attempting to connect failed before the function completed processing. So usually its a network error. This could be caused by packet drops or badly configured Firewall/Switch.
You can also pass in '0' as the value for the column to auto-increment, the correct value will be used when the record is created. This is so much easier than temporary tables.
Source: Copying rows in MySQL (see the second comment, by TRiG, to the first solution, by Lore)
muPdf library looks very promising: http://mupdf.com/
There is also an open source viewer: http://blog.kowalczyk.info/software/sumatrapdf/free-pdf-reader.html
You also can use this:
// GET api/user/firstname/lastname/address
[HttpGet("{firstName}/{lastName}/{address}")]
public string GetQuery(string id, string firstName, string lastName, string address)
{
return $"{firstName}:{lastName}:{address}";
}
Note: Please refer to metalheart's and metalheart
and Mark Hughes
for a possibly better approach.
http://t1m0n.name/air-datepicker/docs/? I've have tried several method of multi datepicker but only this works
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$(document).bind(mousewheelevt,
function(e)
{
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0)
{
scrollup();
}
else
{
scrolldown();
}
}
);
byte in Java is signed, so it has a range -2^7 to 2^7-1 - ie, -128 to 127. Since 132 is above 127, you end up wrapping around to 132-256=-124. That is, essentially 256 (2^8) is added or subtracted until it falls into range.
For more information, you may want to read up on two's complement.
If you are using moment.js then it is pretty simple to find date difference.
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.
Come to think of it, there is probably some similar magic in the normal static linker so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.
After searching for a while I found out that it is not sufficient to export the developer accounts from Xcode and import these on the new machine, again via Xcode.
Additionally I needed to copy the Certficate named "Apple World Wide Developer Relations Certificate Authority" from the keychain of the former development machine to the keychain of the new one.
This solved the problem for me.
See any reference manual, such as the man page:
f,F
The double argument is rounded and converted to decimal notation in the style [-]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point appears, at least one digit appears before it. (The SUSv2 does not know about F and says that character string representations for infinity and NaN may be made available. The C99 standard specifies '[-]inf' or '[-]infinity' for infinity, and a string starting with 'nan' for NaN, in the case of f conversion, and '[-]INF' or '[-]INFINITY' or 'NAN*' in the case of F conversion.)
g,G
The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.
<object CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="320" height="256" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab">
<param name="src" value="sample.mov">
<param name="qtsrc" value="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov">
<param name="autoplay" value="true">
<param name="loop" value="false">
<param name="controller" value="true">
<embed src="sample.mov" qtsrc="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov" width="320" height="256" autoplay="true" loop="false" controller="true" pluginspage="http://www.apple.com/quicktime/"></embed>
</object>
source is the first search result of the Google
Since I did not find any approach, which also handles rotation without checking time stamps, I thought I also share how we now do it in our app. The only addition to this answer https://stackoverflow.com/a/42679191/5119746 is, that we also take the orientation into consideration.
class MyApplication : Application(), Application.ActivityLifecycleCallbacks {
// Members
private var mAppIsInBackground = false
private var mCurrentOrientation: Int? = null
private var mOrientationWasChanged = false
private var mResumed = 0
private var mPaused = 0
Then, for the callbacks we have the resume first:
// ActivityLifecycleCallbacks
override fun onActivityResumed(activity: Activity?) {
mResumed++
if (mAppIsInBackground) {
// !!! App came from background !!! Insert code
mAppIsInBackground = false
}
mOrientationWasChanged = false
}
And onActivityStopped:
override fun onActivityStopped(activity: Activity?) {
if (mResumed == mPaused && !mOrientationWasChanged) {
// !!! App moved to background !!! Insert code
mAppIsInBackground = true
}
And then, here comes the addition: Checking for orientation changes:
override fun onConfigurationChanged(newConfig: Configuration) {
if (newConfig.orientation != mCurrentOrientation) {
mCurrentOrientation = newConfig.orientation
mOrientationWasChanged = true
}
super.onConfigurationChanged(newConfig)
}
That's it. Hope this helps someone :)
for interger digit we can also implement continuously dividing by 10 :
var getNumberOfDigits = function(num){
var count = 1;
while(Math.floor(num/10) >= 1){
num = Math.floor(num/10);
++count;
}
return count;
}
console.log(getNumberOfDigits(1))
console.log(getNumberOfDigits(12))
console.log(getNumberOfDigits(123))
_x000D_
Try to set the property when starting JVM, for example, add -Djava.net.preferIPv4Stack=true
.
You can't set it when code running, as the java.net just read it when jvm starting.
And about the root cause, this article give some hint: Why do I need java.net.preferIPv4Stack=true only on some windows 7 systems?.
setState(updater[, callback])
is an async function:
https://facebook.github.io/react/docs/react-component.html#setstate
You can execute a function after setState is finishing using the second param callback
like:
this.setState({
someState: obj
}, () => {
this.afterSetStateFinished();
});
The same can be done with hooks in React functional component:
https://github.com/the-road-to-learn-react/use-state-with-callback#usage
Look at useStateWithCallbackLazy:
import { useStateWithCallbackLazy } from 'use-state-with-callback';
const [count, setCount] = useStateWithCallbackLazy(0);
setCount(count + 1, () => {
afterSetCountFinished();
});
To complete André's answer, an ant solution could be like the one described in Emacs, JDEE, Ant, and the Eclipse Java Compiler, as in:
<javac
srcdir="${src}"
destdir="${build.dir}/classes">
<compilerarg
compiler="org.eclipse.jdt.core.JDTCompilerAdapter"
line="-warn:+unused -Xemacs"/>
<classpath refid="compile.classpath" />
</javac>
The compilerarg element also allows you to pass in additional command line args to the eclipse compiler.
You can find a full ant script example here which would be invoked in a command line with:
java -cp C:/eclipse-SDK-3.4-win32/eclipse/plugins/org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar org.eclipse.core.launcher.Main -data "C:\Documents and Settings\Administrator\workspace" -application org.eclipse.ant.core.antRunner -buildfile build.xml -verbose
BUT all that involves ant, which is not what Keith is after.
For a batch compilation, please refer to Compiling Java code, especially the section "Using the batch compiler"
The batch compiler class is located in the JDT Core plug-in. The name of the class is org.eclipse.jdt.compiler.batch.BatchCompiler. It is packaged into plugins/org.eclipse.jdt.core_3.4.0..jar. Since 3.2, it is also available as a separate download. The name of the file is ecj.jar.
Since 3.3, this jar also contains the support for jsr199 (Compiler API) and the support for jsr269 (Annotation processing). In order to use the annotations processing support, a 1.6 VM is required.
Running the batch compiler From the command line would give
java -jar org.eclipse.jdt.core_3.4.0<qualifier>.jar -classpath rt.jar A.java
or:
java -jar ecj.jar -classpath rt.jar A.java
All java compilation options are detailed in that section as well.
The difference with the Visual Studio command line compilation feature is that Eclipse does not seem to directly read its .project and .classpath in a command-line argument. You have to report all information contained in the .project and .classpath in various command-line options in order to achieve the very same compilation result.
So, then short answer is: "yes, Eclipse kind of does." ;)
this.myService.getConfig().subscribe(
(res) => console.log(res),
(err) => console.log(err),
() => console.log('done!')
);
You should make a habit of looking at the documentation for stuff like this. It's very useful and will improve your skills very quickly. Here's the relevant bit when you do git help diff
git diff [options] [--no-index] [--] <path> <path>
The two <path>
s are what you need to change to the directories in question.
You can also use git diff HEAD file
to show the diff for a specific file.
See the EXAMPLE
section under git-diff(1)
enter code here if (createSuccses){
val userDataChange=Intent(BRODCAST_USER_DATA_CHANGE)
LocalBroadcastManager.getInstance(this).sendBroadcast(
userDataChange
)
enableSpinner(false)
finish()
Example
$( document ).ready(function() {_x000D_
$('.msg').html('hello world');_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> _x000D_
</head>_x000D_
<body>_x000D_
<div class="msg"></div>_x000D_
</body>_x000D_
</html>
_x000D_
$ find proj
proj
proj/src
proj/src/index.js
$ cat proj/src/index.js
console.log("process.cwd() = " + process.cwd());
console.log("__dirname = " + __dirname);
$ cd proj; node src/index.js
process.cwd() = /tmp/proj
__dirname = /tmp/proj/src
Worked liked a charm for me:
matplotlib.rcParams['figure.figsize'] = (20, 10)
1. You can't spell
The first thing to test is have you spelled the name of the package correctly? Package names are case sensitive in R.
2. You didn't look in the right repository
Next, you should check to see if the package is available. Type
setRepositories()
See also ?setRepositories.
To see which repositories R will look in for your package, and optionally select some additional ones. At the very least, you will usually want CRAN
to be selected, and CRAN (extras)
if you use Windows, and the Bioc*
repositories if you do any [gen/prote/metabol/transcript]omics biological analyses.
To permanently change this, add a line like setRepositories(ind = c(1:6, 8))
to your Rprofile.site
file.
3. The package is not in the repositories you selected
Return all the available packages using
ap <- available.packages()
See also Names of R's available packages, ?available.packages.
Since this is a large matrix, you may wish to use the data viewer to examine it. Alternatively, you can quickly check to see if the package is available by testing against the row names.
View(ap)
"foobarbaz" %in% rownames(ap)
Alternatively, the list of available packages can be seen in a browser for CRAN, CRAN (extras), Bioconductor, R-forge, RForge, and github.
Another possible warnings message you may get when interacting with CRAN mirrors is:
Warning: unable to access index for repository
Which may indicate the selected CRAN repository is currently be unavailable. You can select a different mirror with chooseCRANmirror()
and try the installation again.
There are several reasons why a package may not be available.
4. You don't want a package
Perhaps you don't really want a package. It is common to be confused about the difference between a package and a library, or a package and a dataset.
A package is a standardized collection of material extending R, e.g. providing code, data, or documentation. A library is a place (directory) where R knows to find packages it can use
To see available datasets, type
data()
5. R or Bioconductor is out of date
It may have a dependency on a more recent version of R (or one of the packages that it imports/depends upon does). Look at
ap["foobarbaz", "Depends"]
and consider updating your R installation to the current version. On Windows, this is most easily done via the installr
package.
library(installr)
updateR()
(Of course, you may need to install.packages("installr")
first.)
Equivalently for Bioconductor packages, you may need to update your Bioconductor installation.
source("http://bioconductor.org/biocLite.R")
biocLite("BiocUpgrade")
6. The package is out of date
It may have been archived (if it is no longer maintained and no longer passes R CMD check
tests).
In this case, you can load an old version of the package using install_version()
library(remotes)
install_version("foobarbaz", "0.1.2")
An alternative is to install from the github CRAN mirror.
library(remotes)
install_github("cran/foobarbaz")
7. There is no Windows/OS X/Linux binary
It may not have a Windows binary due to requiring additional software that CRAN does not have. Additionally, some packages are available only via the sources for some or all platforms. In this case, there may be a version in the CRAN (extras)
repository (see setRepositories
above).
If the package requires compiling code (e.g. C, C++, FORTRAN) then on Windows install Rtools or on OS X install the developer tools accompanying XCode, and install the source version of the package via:
install.packages("foobarbaz", type = "source")
# Or equivalently, for Bioconductor packages:
source("http://bioconductor.org/biocLite.R")
biocLite("foobarbaz", type = "source")
On CRAN, you can tell if you'll need special tools to build the package from source by looking at the NeedsCompilation
flag in the description.
8. The package is on github/Bitbucket/Gitorious
It may have a repository on Github/Bitbucket/Gitorious. These packages require the remotes
package to install.
library(remotes)
install_github("packageauthor/foobarbaz")
install_bitbucket("packageauthor/foobarbaz")
install_gitorious("packageauthor/foobarbaz")
(As with installr
, you may need to install.packages("remotes")
first.)
9. There is no source version of the package
Although the binary version of your package is available, the source version is not. You can turn off this check by setting
options(install.packages.check.source = "no")
as described in this SO answer by imanuelc and the Details section of ?install.packages
.
10. The package is in a non-standard repository
Your package is in a non-standard repository (e.g. Rbbg
). Assuming that it is reasonably compliant with CRAN standards, you can still download it using install.packages
; you just have to specify the repository URL.
install.packages("Rbbg", repos = "http://r.findata.org")
RHIPE
on the other hand isn't in a CRAN-like repository and has its own installation instructions.
Link to the PyYAML documentation showing the difference for the default_flow_style
parameter.
To write it to a file in block mode (often more readable):
d = {'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yml', 'w') as yaml_file:
yaml.dump(d, yaml_file, default_flow_style=False)
produces:
A: a
B:
C: c
D: d
E: e
It can be understood like this:
var a= []; //creates a new empty array
var a= {}; //creates a new empty object
You can also understand that
var a = {};
is equivalent to var a= new Object();
Note:
You can use Arrays when you are bothered about the order of elements(of same type) in your collection else you can use objects. In objects the order is not guaranteed.
Using plain javascript
var isEmpty = document.getElementById('cartContent').innerHTML === "";
And if you are using jquery it can be done like
var isEmpty = $("#cartContent").html() === "";
I use inline if's
($_POST['category'] == $data['id'] ? 'selected="selected"' : false)
You can target that div from your stylesheet in a number of ways.
Simply use
.col-md-6:first-child {
background-color: blue;
}
Another way is to assign a class to one div and then apply the style to that class.
<div class="col-md-6 blue"></div>
.blue {
background-color: blue;
}
There are also inline styles.
<div class="col-md-6" style="background-color: blue"></div>
Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary
class from the section and add you custom class to the div.
.blue {_x000D_
background-color: blue;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<section id="about">_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
<div class="col-xs-6">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
<div class="col-xs-6 blue">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</section>
_x000D_
It depends on what the integer is supposed to encode. You could convert the date to a number of milliseconds from some previous time. People often do this affixed to 12:00 am January 1 1970, or 1900, etc., and measure time as an integer number of milliseconds from that point. The datetime
module (or others like it) will have functions that do this for you: for example, you can use int(datetime.datetime.utcnow().timestamp())
.
If you want to semantically encode the year, month, and day, one way to do it is to multiply those components by order-of-magnitude values large enough to juxtapose them within the integer digits:
2012-06-13 --> 20120613 = 10,000 * (2012) + 100 * (6) + 1*(13)
def to_integer(dt_time):
return 10000*dt_time.year + 100*dt_time.month + dt_time.day
E.g.
In [1]: import datetime
In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def to_integer(dt_time):
: return 10000*dt_time.year + 100*dt_time.month + dt_time.day
: # Or take the appropriate chars from a string date representation.
:--
In [3]: to_integer(datetime.date(2012, 6, 13))
Out[3]: 20120613
If you also want minutes and seconds, then just include further orders of magnitude as needed to display the digits.
I've encountered this second method very often in legacy systems, especially systems that pull date-based data out of legacy SQL databases.
It is very bad. You end up writing a lot of hacky code for aligning dates, computing month or day offsets as they would appear in the integer format (e.g. resetting the month back to 1 as you pass December, then incrementing the year value), and boiler plate for converting to and from the integer format all over.
Unless such a convention lives in a deep, low-level, and thoroughly tested section of the API you're working on, such that everyone who ever consumes the data really can count on this integer representation and all of its helper functions, then you end up with lots of people re-writing basic date-handling routines all over the place.
It's generally much better to leave the value in a date context, like datetime.date
, for as long as you possibly can, so that the operations upon it are expressed in a natural, date-based context, and not some lone developer's personal hack into an integer.
You can mix git blame
and git log
commands to retrieve the summary of each commit in the git blame command and append them. Something like the following bash + awk script. It appends the commit summary as code comment inline.
git blame FILE_NAME | awk -F" " \
'{
commit = substr($0, 0, 8);
if (!a[commit]) {
query = "git log --oneline -n 1 " commit " --";
(query | getline a[commit]);
}
print $0 " // " substr(a[commit], 9);
}'
In one line:
git blame FILE_NAME | awk -F" " '{ commit = substr($0, 0, 8); if (!a[commit]) { query = "git log --oneline -n 1 " commit " --"; (query | getline a[commit]); } print $0 " // " substr(a[commit], 9); }'
In WPF there are certain 'container' controls that automatically resize their contents and there are some that don't.
Here are some that do not resize their contents (I'm guessing that you are using one or more of these):
StackPanel
WrapPanel
Canvas
TabControl
Here are some that do resize their contents:
Grid
UniformGrid
DockPanel
Therefore, it is almost always preferable to use a Grid
instead of a StackPanel
unless you do not want automatic resizing to occur. Please note that it is still possible for a Grid
to not size its inner controls... it all depends on your Grid.RowDefinition
and Grid.ColumnDefinition
settings:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100" /> <!--<<< Exact Height... won't resize -->
<RowDefinition Height="Auto" /> <!--<<< Will resize to the size of contents -->
<RowDefinition Height="*" /> <!--<<< Will resize taking all remaining space -->
</Grid.RowDefinitions>
</Grid>
You can find out more about the Grid
control from the Grid
Class page on MSDN. You can also find out more about these container controls from the WPF Container Controls Overview page on MSDN.
Further resizing can be achieved using the FrameworkElement.HorizontalAlignment
and FrameworkElement.VerticalAlignment
properties. The default value of these properties is Stretch
which will stretch elements to fit the size of their containing controls. However, when they are set to any other value, the elements will not stretch.
UPDATE >>>
In response to the questions in your comment:
Use the Grid.RowDefinition
and Grid.ColumnDefinition
settings to organise a basic structure first... it is common to add Grid
controls into the cells of outer Grid
controls if need be. You can also use the Grid.ColumnSpan
and Grid.RowSpan
properties to enable controls to span multiple columns and/or rows of a Grid
.
It is most common to have at least one row/column with a Height
/Width
of "*"
which will fill all remaining space, but you can have two or more with this setting, in which case the remaining space will be split between the two (or more) rows/columns. 'Auto' is a good setting to use for the rows/columns that are not set to '"*"', but it really depends on how you want the layout to be.
There is no Auto
setting that you can use on the controls in the cells, but this is just as well, because we want the Grid
to size the controls for us... therefore, we don't want to set the Height
or Width
of these controls at all.
The point that I made about the FrameworkElement.HorizontalAlignment
and FrameworkElement.VerticalAlignment
properties was just to let you know of their existence... as their default value is already Stretch
, you don't generally need to set them explicitly.
The Margin
property is generally just used to space your controls out evenly... if you drag and drop controls from the Visual Studio Toolbox, VS will set the Margin
property to place your control exactly where you dropped it but generally, this is not what we want as it will mess with the auto sizing of controls. If you do this, then just delete or edit the Margin
property to suit your needs.
The problem may lie in you don't have enabled openssl extention in your php.ini file
go to your php.ini file end remove ;
in line where extension=openssl
is
Of course in question code there is a part of code responsible for checking whether extension is loaded or not but maybe some uncautious forget about it
If you do not want to install devDependencies you can use npm install --production
For swift 4.2
--
//MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1 //return number of sections in collection view
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10 //return number of rows in section
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
configureCell(cell: cell, forItemAtIndexPath: indexPath)
return cell //return your cell
}
func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
cell.backgroundColor = UIColor.black
//Customise your cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", for: indexPath as IndexPath) as UICollectionReusableView
return view
}
//MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// When user selects the cell
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
// When user deselects the cell
}
The following code works at both Chrome and Firefox
<a href="#"><img src="me-more-smile.jpg" onmouseover="this.src='me-thinking-about-a-date.jpg'" onmouseout="this.src='me-more-smile.jpg'" border="0" alt=""/></a>
if (isset($_POST['remove'])) {
$key=array_search($_GET['name'],$_SESSION['name']);
if($key!==false)
unset($_SESSION['name'][$key]);
$_SESSION["name"] = array_values($_SESSION["name"]);
}
Since $_SESSION['name']
is an array, you need to find the array key that points at the name value you're interested in. The last line rearranges the index of the array for the next use.
FocusScope.of(context).unfocus() has a downside when using with filtered listView. Apart from so many details and concisely, use keyboard_dismisser package in https://pub.dev/packages/keyboard_dismisser will solve all the problems.
I use layers to describe the architect or technology stack within a component of my solutions. I use tiers to logically group those components typically when network or interprocess communication is involved.
Try:
DataTable.Rows[RowNo].ItemArray[columnIndex].ToString()
(This is C# code. Change this to VB equivalent)
You can't upload nested structures like that through the online tool. I'd recommend using something like Bucket Explorer for more complicated uploads.
Before you call setContentView()
, call setTheme(android.R.style...)
and just replace the ... with the theme that you want(Theme, Theme_NoTitleBar, etc.).
Or if your theme is a custom theme, then replace the entire thing, so you get setTheme(yourThemesResouceId)
In short: You should be able to achieve in the order of millions of simultaneous active TCP connections and by extension HTTP request(s). This tells you the maximum performance you can expect with the right platform with the right configuration.
Today, I was worried whether IIS with ASP.NET would support in the order of 100 concurrent connections (look at my update, expect ~10k responses per second on older ASP.Net Mono versions). When I saw this question/answers, I couldn't resist answering myself, many answers to the question here are completely incorrect.
Best Case
The answer to this question must only concern itself with the simplest server configuration to decouple from the countless variables and configurations possible downstream.
So consider the following scenario for my answer:
Detailed Answer
Synchronous thread-bound designs tend to be the worst performing relative to Asynchronous IO implementations.
WhatsApp can handle a million WITH traffic on a single Unix flavoured OS machine - https://blog.whatsapp.com/index.php/2012/01/1-million-is-so-2011/.
And finally, this one, http://highscalability.com/blog/2013/5/13/the-secret-to-10-million-concurrent-connections-the-kernel-i.html, goes into a lot of detail, exploring how even 10 million could be achieved. Servers often have hardware TCP offload engines, ASICs designed for this specific role more efficiently than a general purpose CPU.
Good software design choices
Asynchronous IO design will differ across Operating Systems and Programming platforms. Node.js was designed with asynchronous in mind. You should use Promises at least, and when ECMAScript 7 comes along, async
/await
. C#/.Net already has full asynchronous support like node.js. Whatever the OS and platform, asynchronous should be expected to perform very well. And whatever language you choose, look for the keyword "asynchronous", most modern languages will have some support, even if it's an add-on of some sort.
To WebFarm?
Whatever the limit is for your particular situation, yes a web-farm is one good solution to scaling. There are many architectures for achieving this. One is using a load balancer (hosting providers can offer these, but even these have a limit, along with bandwidth ceiling), but I don't favour this option. For Single Page Applications with long-running connections, I prefer to instead have an open list of servers which the client application will choose from randomly at startup and reuse over the lifetime of the application. This removes the single point of failure (load balancer) and enables scaling through multiple data centres and therefore much more bandwidth.
Busting a myth - 64K ports
To address the question component regarding "64,000", this is a misconception. A server can connect to many more than 65535 clients. See https://networkengineering.stackexchange.com/questions/48283/is-a-tcp-server-limited-to-65535-clients/48284
By the way, Http.sys on Windows permits multiple applications to share the same server port under the HTTP URL schema. They each register a separate domain binding, but there is ultimately a single server application proxying the requests to the correct applications.
Update 2019-05-30
Here is an up to date comparison of the fastest HTTP libraries - https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=plaintext
an even better way would be to catch the input event on the input itself rather than on the whole form (performance wise) :
<input type="range" id="rangeInput" name="rangeInput" min="0" max="20" value="0"
oninput="amount.value=rangeInput.value">
<output id="amount" name="amount" for="rangeInput">0</output>
Here's a fiddle (with the id
added as per Ryan's comment).
Here is example of taking XML file from raw folder:
InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML
Then you can:
String sxml = readTextFile(XmlFileInputStream);
when:
public String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
MAMP & MAMP PRO 4.0.6 was starting MySql server correctly but stopped doing so after my machine updated the OS to macOS Sierra (10.12.2). I tried a few options mentioned here including setting folder permissions and re-install etc. Nothing seemed fixed the issue for me so I shifted to XAMPP and it is serving OK so far.
Update: I've got MAMP working with this simple solution here.
See this example also
<?php
function get_timezones()
{
$o = array();
$t_zones = timezone_identifiers_list();
foreach($t_zones as $a)
{
$t = '';
try
{
//this throws exception for 'US/Pacific-New'
$zone = new DateTimeZone($a);
$seconds = $zone->getOffset( new DateTime("now" , $zone) );
$hours = sprintf( "%+02d" , intval($seconds/3600));
$minutes = sprintf( "%02d" , ($seconds%3600)/60 );
$t = $a ." [ $hours:$minutes ]" ;
$o[$a] = $t;
}
//exceptions must be catched, else a blank page
catch(Exception $e)
{
//die("Exception : " . $e->getMessage() . '<br />');
//what to do in catch ? , nothing just relax
}
}
ksort($o);
return $o;
}
$o = get_timezones();
?>
<html>
<body>
<select name="time_zone">
<?php
foreach($o as $tz => $label)
{
echo "<option value="$tz">$label</option>";
}
?>
</select>
</body>
</html>
1. Open "Turn windows features on or off" by: WinKey+ R => "optionalfeatures" => OK
Tested on Win 10 - But probably will work on other windows versions as well.
The following tables are store WooCommerce products database :
wp_posts -
The core of the WordPress data is the posts. It is stored a post_type
like product or variable_product
.
wp_postmeta-
Each post features information called the meta data and it is stored in the wp_postmeta. Some plugins may add their own information to this table like WooCommerce plugin store product_id
of product in wp_postmeta table.
Product categories, subcategories stored in this table :
following Query Return a list of product categories
SELECT wp_terms.*
FROM wp_terms
LEFT JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
WHERE wp_term_taxonomy.taxonomy = 'product_cat';
for more reference -
If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.
var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();
Then you'll be able to access it like:
nodes.Any(n => n.Checked);
Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.
nodes.Add(new { Checked = false, /* etc */ });
Solution from Google team
Starting from Android 5.0 that's easily achievable through the new Google Play In App updates mechanism. The requirements are to have Play Core library of version 1.5.0+ and use App Bundles idstribution instead of apks.
The library provides you 2 different ways to notify the users about the update:
Flexible, when users can continue using the app while it is being updated in the background.
Immediate - blocking screen that doesn't allow a user to enter the app until they update it.
There are next steps to implement it:
All of these steps implementations are described in details on the official site: https://developer.android.com/guide/app-bundle/in-app-updates
You cannot treat ==
or ||
as chars, since they are not chars, but a sequence of chars.
You could make your switch...case work on strings instead.
Open your terminal and open folder where file is saved.
Ex /home/User1/program/test.rb
cd /home/User1/program
ruby test.rb
format or test.rb
class Test
def initialize
puts "I love India"
end
end
# initialize object
Test.new
output
I love India
There is no OOTB feature at this moment which allows this. One way to achieve that could be to write a custom InputFormat and/or SerDe that will do this for you. You might this JIRA useful : https://issues.apache.org/jira/browse/HIVE-3751. (not related directly to your problem though).
To write console output to a txt file
public static void main(String[] args) {
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 100; i++) {
String str = null;
str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A TEXT FILE";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
FileWriter writer = null;
try {
writer = new FileWriter("final.txt");
writer.write(listString);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to generate the PDF rather then the text file, you use the dependency given below:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>
To generate a PDF, use this code:
public static void main(String[] args) {
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 100; i++) {
String str = null;
str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A PDF";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
Document document = new Document();
try {
PdfWriter writer1 = PdfWriter
.getInstance(
document,
new FileOutputStream(
"final_pdf.pdf"));
document.open();
document.add(new Paragraph(listString));
document.close();
writer1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
On Version 1.9.6.1. For UnPushed commit.
In the recent implementation, java.sql.Data is an subclass of java.util.Date, so no converting needed. see here: https://docs.oracle.com/javase/1.5.0/docs/api/java/sql/Date.html
Just Change the query like this:
SELECT TOP 1 * FROM [HumanResources].[Employee]
where Employee
is your table name and HumanResources
is your Schema name if I am not wrong.
Hope your problem will be resolved. :)
my 2 cents:
$('#theDiv').prepend($('<img>',{id:'theImg',src:'theImg.png'}))
As is mentioned, Agile is a methodology, and there are various ways to define what agile is. To a large extent, if it involves constant unit testing and the ability to quickly adapt when the business needs change then it is probably agile. The opposite is the waterfall method.
There are various implementations that are codified by consultants, such as Xtremem Programming, Scrum and RUP (Rational Unified Process).
So, if you are using Scrum then you can switch between agile and scrum depending on if you are talking about the methodology or your implementation. You will want to see if the terms are being used correctly, by the context.
For example, if I am talking about the 15 min standup as part of my agile process, that is not necessarily needed to be agile, but scrum almost requires it, so when you interchange the terms, it is important to differentiate between the two concepts.
That worked for me in Swift 5 like a charm, just add it to your viewDidLoad()
self.navigationItem.setHidesBackButton(true, animated: true)
There are many ways to do it:
Way1: If you are trying in maven project without Using PropertyConfigurator
First: check for resources directory at scr/main
if available,
then: create a .properties file and add all configuration details.
else
then: create a directory named resources and a file with .properties
write your configuration code/details.
follows the screenshot:
Way2: If you are trying with Properties file for java/maven project Use PropertyConfigurator
Place properties file anywhere in project and give the correct path. say: src/javaLog4jProperties/log4j.properties
static{
PropertyConfigurator.configure("src/javaLog4jProperties/log4j.properties");
}
Way3: If you are trying with xml on java/maven project Use DOMConfigurator
Place properties file anywhere in project and give correct path. say: src/javaLog4jProperties/log4j.xml
static{
DOMConfigurator.configure("src/javaLog4jProperties/log4j.xml");
}
If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.
If you want to append contents of 3 files into one file, then the following command will be a good choice:
cat file1 file2 file3 | tee -a file4 > /dev/null
It will combine the contents of all files into file4, throwing console output to /dev/null
.
Alternative simpler solution is to use rsync
utility:
sudo rsync -vuar --delete-after --dry-run path/subfolder/ path/
Note: Above command will show what is going to be changed. To execute the actual changes, remove --dry-run
.
The advantage is that the original folder (subfolder
) would be removed as well as part of the command, and when using mv
examples here you still need to clean up your folders, not to mention additional headache to cover hidden and non-hidden files in one single pattern.
In addition rsync
provides support of copying/moving files between remotes and it would make sure that files are copied exactly as they originally were (-a
).
The used -u
parameter would skip existing newer files, -r
recurse into directories and -v
would increase verbosity.
Change CI index.php file to:
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
if (defined('ENVIRONMENT')){
switch (ENVIRONMENT){
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
IF PHP errors are off, but any MySQL errors are still going to show, turn these off in the /config/database.php file. Set the db_debug option to false:
$db['default']['db_debug'] = FALSE;
Also, you can use active_group as development and production to match the environment https://www.codeigniter.com/user_guide/database/configuration.html
$active_group = 'development';
$db['development']['hostname'] = 'localhost';
$db['development']['username'] = '---';
$db['development']['password'] = '---';
$db['development']['database'] = '---';
$db['development']['dbdriver'] = 'mysql';
$db['development']['dbprefix'] = '';
$db['development']['pconnect'] = TRUE;
$db['development']['db_debug'] = TRUE;
$db['development']['cache_on'] = FALSE;
$db['development']['cachedir'] = '';
$db['development']['char_set'] = 'utf8';
$db['development']['dbcollat'] = 'utf8_general_ci';
$db['development']['swap_pre'] = '';
$db['development']['autoinit'] = TRUE;
$db['development']['stricton'] = FALSE;
$db['production']['hostname'] = 'localhost';
$db['production']['username'] = '---';
$db['production']['password'] = '---';
$db['production']['database'] = '---';
$db['production']['dbdriver'] = 'mysql';
$db['production']['dbprefix'] = '';
$db['production']['pconnect'] = TRUE;
$db['production']['db_debug'] = FALSE;
$db['production']['cache_on'] = FALSE;
$db['production']['cachedir'] = '';
$db['production']['char_set'] = 'utf8';
$db['production']['dbcollat'] = 'utf8_general_ci';
$db['production']['swap_pre'] = '';
$db['production']['autoinit'] = TRUE;
$db['production']['stricton'] = FALSE;
Another way to use itertools.ifilter
. This checks truthiness and process
(using lambda
)
Sample-
for x in itertools.ifilter(lambda x: x[2] == 0, my_list):
print x
Since the 'include-headers' functionality doesn't seem to be build-in yet, and most "solutions" here need to type the columns names manually, and/or don't even take joins into account, I'd recommand to get around the problem.
The best alternative I found so far is using a decent tool (I use HeidiSQL).
Put your request, select the grid, just right click and export to a file. It got all necessary options for a clean export, ans should handle most needs.
In the same idea, user3037511's approach works fine, and can be automated easily.
Just launch your request with some command line to get your headers. You may get the data with a SELECT INTO OUTFILE... or by running your query without the limit, yours to choose.
Note that output redirect to a file works like a charm on both Linux AND Windows.
This makes me want to highlight that 80% of the time, when I want to use SELECT FROM INFILE or SELECT INTO OUTFILE, I end-up using something else due to some limitations (here, the absence of a 'headers options', on an AWS-RDS, the missing rights, and so on.)
Hence, I don't exactly answer to the op's question... but it should answer his needs :)
EDIT : and to actually answer his question : no
As of 2017-09-07, you just can't include headers if you stick with the SELECT INTO OUTFILE command :|
This is absolutely doable with some flexbox magic. Have a look at this pen.
You need css like this:
aside {
background-color: cyan;
position: fixed;
max-height: 100vh;
width: 25%;
display: flex;
flex-direction: column;
}
ul {
overflow-y: scroll;
}
section {
width: 75%;
float: right;
background: orange;
}
This will work in IE10+
Play Store Rating
btn_rate_us.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
}
});
Add config/secrets.yml
to version control and deploy again. You might need to remove a line from .gitignore
so that you can commit the file.
I had this exact same issue and it just turned out that the boilerplate .gitignore
Github created for my Rails application included config/secrets.yml
.
To set the height of ActionBar
you can create new Theme
like this one:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.FixedSize" parent="Theme.Sherlock.Light.DarkActionBar">
<item name="actionBarSize">48dip</item>
<item name="android:actionBarSize">48dip</item>
</style>
</resources>
and set this Theme
to your Activity
:
android:theme="@style/Theme.FixedSize"
The error log is straightforward. As it suggested,You need to add 198.211.99.20 to your ALLOWED_HOSTS
setting.
In your project settings.py file,set ALLOWED_HOSTS
like this :
ALLOWED_HOSTS = ['198.211.99.20', 'localhost', '127.0.0.1']
For further reading read from here.
It Works , try out this :
InputStream in_s1 = TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");
As some answered before, this line of code solved the problem
Class.forName("org.hsqldb.jdbcDriver");
But my app is running in some tomcats but only in one installation I had to add this code.