return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);
When migrating from one machine to another-
Check the gpg version and supported algorithms between the two systems.
gpg --version
Check the presence of keys on both systems.
gpg --list-keys
pub 4096R/62999779 2020-08-04 sub 4096R/0F799997 2020-08-04
gpg --list-secret-keys
sec 4096R/62999779 2020-08-04 ssb 4096R/0F799997 2020-08-04
Check for the presence of same pair of key ids on the other machine. For decrypting, only secret key(sec) and secret sub key(ssb) will be needed.
If the key is not present on the other machine, export the keys in a file from the machine on which keys are present, scp the file and import the keys on the machine where it is missing.
Do not recreate the keys on the new machine with the same passphrase, name, user details as the newly generated key will have new unique id and "No secret key" error will still appear if source is using previously generated public key for encryption. So, export and import, this will ensure that same key id is used for decryption and encryption.
gpg --output gpg_pub_key --export <Email address>
gpg --output gpg_sec_key --export-secret-keys <Email address>
gpg --output gpg_sec_sub_key --export-secret-subkeys <Email address>
gpg --import gpg_pub_key
gpg --import gpg_sec_key
gpg --import gpg_sec_sub_key
You could dramatically speed up your stuff if you used just one list instead of a list of lists. This is possible of course only if all your inner lists are of the same size (which is true in your example, so I just assume this).
WIDTH = 6
level1 = [ 1,1,1,1,1,1,
1,0,0,0,0,1,
1,0,0,0,0,1,
1,0,0,0,0,1,
1,0,0,0,0,1,
1,1,1,1,1,1 ]
print level1[x + y*WIDTH] # print value at (x,y)
And you could be even faster if you used a bitfield instead of a list:
WIDTH = 8 # better align your width to bytes, eases things later
level1 = 0xFC84848484FC # bit field representation of the level
print "1" if level1 & mask(x, y) else "0" # print bit at (x, y)
level1 |= mask(x, y) # set bit at (x, y)
level1 &= ~mask(x, y) # clear bit at (x, y)
with
def mask(x, y):
return 1 << (WIDTH-x + y*WIDTH)
But that's working only if your fields just contain 0 or 1 of course. If you need more values, you'd have to combine several bits which would make the issue much more complicated.
You can use self.data
in the clean_email
method to access the POST data before validation. It should contain a key called newsletter_sub
or newsletter_unsub
depending on which button was pressed.
# in the context of a django.forms form
def clean(self):
if 'newsletter_sub' in self.data:
# do subscribe
elif 'newsletter_unsub' in self.data:
# do unsubscribe
I had a simular issue and resolved it using android:adjustViewBounds="true"
on the ImageView.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/banner_alt"
android:src="@drawable/banner_portrait" />
Try to use this free way to this, https://freenetexcel.codeplex.com
Workbook workbook = new Workbook();
workbook.LoadFromFile(@"..\..\parts.xls",ExcelVersion.Version97to2003);
//Initialize worksheet
Worksheet sheet = workbook.Worksheets[0];
DataTable dataTable = sheet.ExportDataTable();
The onclick
property is all lower-case, and accepts a function, not a string.
document.getElementById("test").onclick = foo2;
See also addEventListener
.
You can use "netstat" to check whether a port is available or not.
Use the netstat -anp | find "port number"
command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.
You have to put : before port number to get the actual output
Ex
netstat -anp | find ":8080"
In my case I solved the issue by putting the name of the formControl in double and sinlge quotes so that it is interpreted as a string:
[formControlName]="'familyName'"
similar to below:
formControlName="familyName"
Try using this code:
var datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
year: 'numeric', month: 'numeric', day: 'numeric',
};
var result = date.toLocaleDateString('en', options); // 10/29/2013
I ran in the same issue when trying to update a column which name was a keyword. The solution above didn't help me. I solved it out by simply specifying the name of the table like this:
UPDATE `survey`
SET survey.values='yes,no'
WHERE (question='Did you agree?')
Visiting this thread after some period of inactivity, but given that I don't see a thorough answer, here's my two cents.
Breadth-first search will always find the shortest path in an unweighted graph. The graph may be cyclic or acyclic.
See below for pseudocode. This pseudocode assumes that you are using a queue to implement BFS. It also assumes you can mark vertices as visited, and that each vertex stores a distance parameter, which is initialized as infinity.
mark all vertices as unvisited
set the distance value of all vertices to infinity
set the distance value of the start vertex to 0
if the start vertex is the end vertex, return 0
push the start vertex on the queue
while(queue is not empty)
dequeue one vertex (we’ll call it x) off of the queue
if x is not marked as visited:
mark it as visited
for all of the unmarked children of x:
set their distance values to be the distance of x + 1
if the value of x is the value of the end vertex:
return the distance of x
otherwise enqueue it to the queue
if here: there is no path connecting the vertices
Note that this approach doesn't work for weighted graphs - for that, see Dijkstra's algorithm.
I like
Get-WmiObject Win32_computersystem | format-custom *
That seems to expand everything.
There's also a show-object command in the PowerShellCookbook module that does it in a GUI. Jeffrey Snover, the PowerShell creator, uses it in his unplugged videos (recommended).
Although most often I use
Get-WmiObject Win32_computersystem | fl *
It avoids the .format.ps1xml file that defines a table or list view for the object type, if there are any. The format file may even define column headers that don't match any property names.
You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data. -don
In the code of the button that saves the changes to the database eg the update button, add the following lines of code:
MyDataGridView.DataSource = MyTableBindingSource
MyDataGridView.Update()
MyDataGridView.RefreshEdit()
unless [nil, 0].include?(discount) # ... end
Many of the suggestions unfortunately do not work for all Markdown viewers/editors, for instance, the popular Markdown Viewer Chrome extension, but they do work with iA Writer.
What does seem to work across both of these popular programs (and might work for your particular application) is to use HTML comment blocks ('<!-- -->')
:
| <!-- --> | <!-- --> |
|-------------|-------------|
| Foo | Bar |
Like some of the earlier suggestions stated, this does add an empty header row in your Markdown viewer/editor. In iA Writer, it's aesthetically small enough that it doesn't get in my way too much.
Although side_effect
can achieve the goal, it is not so convenient to setup side_effect
function for each test case.
I write a lightweight Mock (which is called NextMock) to enhance the built-in mock to address this problem, here is a simple example:
from nextmock import Mock
m = Mock()
m.with_args(1, 2, 3).returns(123)
assert m(1, 2, 3) == 123
assert m(3, 2, 1) != 123
It also supports argument matcher:
from nextmock import Arg, Mock
m = Mock()
m.with_args(1, 2, Arg.Any).returns(123)
assert m(1, 2, 1) == 123
assert m(1, 2, "123") == 123
Hope this package could make testing more pleasant. Feel free to give any feedback.
I know this is an old question but I just found a solution which creates a user defined function using LTRIM and RTRIM. It does not handle double spaces in the middle of a string.
The solution is however straight forward:
Taking from http://blog.stefanxo.com/2014/08/update-all-docker-images-at-once/
You can update all your existing images using the following command pipeline:
docker images | awk '/^REPOSITORY|\<none\>/ {next} {print $1}' | xargs -n 1 docker pull
Typical append
usage is
a = append(a, x)
because append
may either modify its argument in-place or return a copy of its argument with an additional entry, depending on the size and capacity of its input. Using a slice that was previously appended to may give unexpected results, e.g.
a := []int{1,2,3}
a = append(a, 4)
fmt.Println(a)
append(a[:3], 5)
fmt.Println(a)
may print
[1 2 3 4]
[1 2 3 5]
I had found a particular case where swiping (ADB shell input touchscreen swipe ... ) to unlock the home screen doesn't work. More exactly for Acer Z160 and Acer S57. The phones are history but still, they need to be taken into consideration by us developers. Here is the code source that solved my problem. I had made my app to start with the device. and in the "onCreate" function I had changed temporarily the lock type.
Also, just in case google drive does something to the zip file I will post fragments of that code below.
AndroidManifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.gresanuemanuelvasi.test_wakeup">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ServiceStarter" android:enabled="true" android:exported="false" android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
android:directBootAware="true" tools:targetApi="n">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>
class ServiceStarter: BroadcastReceiver() {
@SuppressLint("CommitPrefEdits")
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("EMY_","Calling onReceive")
context?.let {
Log.i("EMY_", "Received action: ${intent!!.getAction()}, user unlocked: " + UserManagerCompat.isUserUnlocked(context))
val sp =it.getSharedPreferences("EMY_", Context.MODE_PRIVATE)
sp.edit().putString(MainActivity.MY_KEY, "M-am activat asa cum trebuie!")
if (intent!!.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
val i = Intent(it, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
it.startActivity(i)
}
}
}
}
class MainActivity : AppCompatActivity() {
companion object {
const val MY_KEY="MY_KEY"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val kgm = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
val kgl = kgm.newKeyguardLock(MainActivity::class.java.simpleName)
if (kgm.inKeyguardRestrictedInputMode()) {
kgl.disableKeyguard()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(arrayOf(Manifest.permission.RECEIVE_BOOT_COMPLETED), 1234)
}
else
{
afisareRezultat()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if(1234 == requestCode )
{
afisareRezultat()
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
private fun afisareRezultat() {
Log.d("EMY_","Calling afisareRezultat")
val sp = getSharedPreferences("EMY_", Context.MODE_PRIVATE);
val raspuns = sp.getString(MY_KEY, "Doesn't exists")
Log.d("EMY_", "AM primit: ${raspuns}")
sp.edit().remove(MY_KEY).apply()
}
}
You can try this. similar result
<c:forEach items="${loopableObject}" var="theObject" varStatus="theCount">
<div id="divIDNo${theCount.count}"></div>
</c:forEach>
Primary Key is very unfortunate notation, because of the connotation of "Primary" and the subconscious association in consequence with the Logical Model. I thus avoid using it. Instead I refer to the Surrogate Key of the Physical Model and the Natural Key(s) of the Logical Model.
It is important that the Logical Model for every Entity have at least one set of "business attributes" which comprise a Key for the entity. Boyce, Codd, Date et al refer to these in the Relational Model as Candidate Keys. When we then build tables for these Entities their Candidate Keys become Natural Keys in those tables. It is only through those Natural Keys that users are able to uniquely identify rows in the tables; as surrogate keys should always be hidden from users. This is because Surrogate Keys have no business meaning.
However the Physical Model for our tables will in many instances be inefficient without a Surrogate Key. Recall that non-covered columns for a non-clustered index can only be found (in general) through a Key Lookup into the clustered index (ignore tables implemented as heaps for a moment). When our available Natural Key(s) are wide this (1) widens the width of our non-clustered leaf nodes, increasing storage requirements and read accesses for seeks and scans of that non-clustered index; and (2) reduces fan-out from our clustered index increasing index height and index size, again increasing reads and storage requirements for our clustered indexes; and (3) increases cache requirements for our clustered indexes. chasing other indexes and data out of cache.
This is where a small Surrogate Key, designated to the RDBMS as "the Primary Key" proves beneficial. When set as the clustering key, so as to be used for key lookups into the clustered index from non-clustered indexes and foreign key lookups from related tables, all these disadvantages disappear. Our clustered index fan-outs increase again to reduce clustered index height and size, reduce cache load for our clustered indexes, decrease reads when accessing data through any mechanism (whether index scan, index seek, non-clustered key lookup or foreign key lookup) and decrease storage requirements for both clustered and nonclustered indexes of our tables.
Note that these benefits only occur when the surrogate key is both small and the clustering key. If a GUID is used as the clustering key the situation will often be worse than if the smallest available Natural Key had been used. If the table is organized as a heap then the 8-byte (heap) RowID will be used for key lookups, which is better than a 16-byte GUID but less performant than a 4-byte integer.
If a GUID must be used due to business constraints than the search for a better clustering key is worthwhile. If for example a small site identifier and 4-byte "site-sequence-number" is feasible then that design might give better performance than a GUID as Surrogate Key.
If the consequences of a heap (hash join perhaps) make that the preferred storage then the costs of a wider clustering key need to be balanced into the trade-off analysis.
Consider this example::
ALTER TABLE Persons
ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
where the tuple "(P_Id,LastName)" requires a uniqueness constraint, and may be a lengthy Unicode LastName plus a 4-byte integer, it would be desirable to (1) declaratively enforce this constraint as "ADD CONSTRAINT pk_PersonID UNIQUE NONCLUSTERED (P_Id,LastName)" and (2) separately declare a small Surrogate Key to be the "Primary Key" of a clustered index. It is worth noting that Anita possibly only wishes to add the LastName to this constraint in order to make that a covered field, which is unnecessary in a clustered index because ALL fields are covered by it.
The ability in SQL Server to designate a Primary Key as nonclustered is an unfortunate historical circumstance, due to a conflation of the meaning "preferred natural or candidate key" (from the Logical Model) with the meaning "lookup key in storage" from the Physical Model. My understanding is that originally SYBASE SQL Server always used a 4-byte RowID, whether into a heap or a clustered index, as the "lookup key in storage" from the Physical Model.
Here is my code, used to catch every output from subprocess ASAP, including partial lines. It pumps at same time and stdout and stderr in almost correct order.
Tested and correctly worked on Python 2.7 linux & windows.
#!/usr/bin/python
#
# Runner with stdout/stderr catcher
#
from sys import argv
from subprocess import Popen, PIPE
import os, io
from threading import Thread
import Queue
def __main__():
if (len(argv) > 1) and (argv[-1] == "-sub-"):
import time, sys
print "Application runned!"
time.sleep(2)
print "Slept 2 second"
time.sleep(1)
print "Slept 1 additional second",
time.sleep(2)
sys.stderr.write("Stderr output after 5 seconds")
print "Eol on stdin"
sys.stderr.write("Eol on stderr\n")
time.sleep(1)
print "Wow, we have end of work!",
else:
os.environ["PYTHONUNBUFFERED"]="1"
try:
p = Popen( argv + ["-sub-"],
bufsize=0, # line-buffered
stdin=PIPE, stdout=PIPE, stderr=PIPE )
except WindowsError, W:
if W.winerror==193:
p = Popen( argv + ["-sub-"],
shell=True, # Try to run via shell
bufsize=0, # line-buffered
stdin=PIPE, stdout=PIPE, stderr=PIPE )
else:
raise
inp = Queue.Queue()
sout = io.open(p.stdout.fileno(), 'rb', closefd=False)
serr = io.open(p.stderr.fileno(), 'rb', closefd=False)
def Pump(stream, category):
queue = Queue.Queue()
def rdr():
while True:
buf = stream.read1(8192)
if len(buf)>0:
queue.put( buf )
else:
queue.put( None )
return
def clct():
active = True
while active:
r = queue.get()
try:
while True:
r1 = queue.get(timeout=0.005)
if r1 is None:
active = False
break
else:
r += r1
except Queue.Empty:
pass
inp.put( (category, r) )
for tgt in [rdr, clct]:
th = Thread(target=tgt)
th.setDaemon(True)
th.start()
Pump(sout, 'stdout')
Pump(serr, 'stderr')
while p.poll() is None:
# App still working
try:
chan,line = inp.get(timeout = 1.0)
if chan=='stdout':
print "STDOUT>>", line, "<?<"
elif chan=='stderr':
print " ERROR==", line, "=?="
except Queue.Empty:
pass
print "Finish"
if __name__ == '__main__':
__main__()
This assumes you know the position of the element in the ListView :
View element = listView.getListAdapter().getView(position, null, null);
Then you should be able to call getLeft() and getTop() to determine the elements on screen position.
maybe map
, but since you don't want to make a list, you can write your own...
def call_for_all(f, seq):
for i in seq:
f(i)
then you can do:
call_for_all(lamda x: x.start(), all)
call_for_all(lamda x: x.stop(), all)
by the way, all is a built in function, don't overwrite it ;-)
This has been described in some of the other answers, but here's (in code) how to combine scrollViewDidEndDecelerating
and scrollViewDidEndDragging:willDecelerate
to perform some operation when scrolling has finished:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self stoppedScrolling];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView
willDecelerate:(BOOL)decelerate
{
if (!decelerate) {
[self stoppedScrolling];
}
}
- (void)stoppedScrolling
{
// done, do whatever
}
Quoted from the javadoc;
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.
Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.
Edit: ..and made the important bit bold.
package secondhighestno;
import java.util.Scanner;
/**
*
* @author Laxman
*/
public class SecondHighestno {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc=new Scanner(System.in);
int n =sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
int max1=a[0],max2=a[0];
for(int j=0;j<n;j++){
if(a[j]>max1){
max1=a[j];
}
}
for(int k=0;k<n;k++){
if(a[k]>max2 && max1>a[k]){
max2=a[k];
}
}
System.out.println(max1+" "+max2);
}
}
The same will happen if your published version is not the same as the version you're testing on your phone.
For example, uploaded version is android:versionCode="1"
, and the version you're testing on your phone is android:versionCode="2"
I couldn't get The DataRowAttribute
to work in Visual Studio 2015, and this is what I ended up with:
[TestClass]
public class Tests
{
private Foo _toTest;
[TestInitialize]
public void Setup()
{
this._toTest = new Foo();
}
[TestMethod]
public void ATest()
{
this.Perform_ATest(1, 1, 2);
this.Setup();
this.Perform_ATest(100, 200, 300);
this.Setup();
this.Perform_ATest(817001, 212, 817213);
this.Setup();
}
private void Perform_ATest(int a, int b, int expected)
{
// Obviously this would be way more complex...
Assert.IsTrue(this._toTest.Add(a,b) == expected);
}
}
public class Foo
{
public int Add(int a, int b)
{
return a + b;
}
}
The real solution here is to just use NUnit (unless you're stuck in MSTest like I am in this particular instance).
child_process.spawn returns an object with stdout and stderr streams. You can tap on the stdout stream to read data that the child process sends back to Node. stdout being a stream has the "data", "end", and other events that streams have. spawn is best used to when you want the child process to return a large amount of data to Node - image processing, reading binary data etc.
so you can solve your problem using child_process.spawn as used below.
var spawn = require('child_process').spawn,
ls = spawn('coffee -cw my_file.coffee');
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data.toString());
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data.toString());
});
ls.on('exit', function (code) {
console.log('code ' + code.toString());
});
Try the following:
int myIndex = MyDataGrid.SelectedIndex;
This will give the index of the row which is currently selected.
Hope this helps
You can use NSNotification
Add a post method in your custom class:
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
Add an observer in your ViewController:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOFReceivedNotication:", name:"NotificationIdentifier", object: nil)
Add function in you ViewController:
func methodOFReceivedNotication(notification: NSNotification){
self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)
}
Try this code:
<form id="myform">
<!-- form elements -->
<a href="#" onclick="document.getElementById('myform').submit()">Submit</a>
</form>
But users with disabled JavaScript won't be able to submit the form, so you could add the following code:
<noscript>
<input type="submit" value="Submit form!" />
</noscript>
It is possible of course, use -l:
instead of -l
. For example -l:libXYZ.a
to link with libXYZ.a
. Notice the lib
written out, as opposed to -lXYZ
which would auto expand to libXYZ
.
Much simpler solution:
pd.DataFrame(df2["teams"].to_list(), columns=['team1', 'team2'])
Yields,
team1 team2
-------------
0 SF NYG
1 SF NYG
2 SF NYG
3 SF NYG
4 SF NYG
5 SF NYG
6 SF NYG
7 SF NYG
If you wanted to split a column of delimited strings rather than lists, you could similarly do:
pd.DataFrame(df["teams"].str.split('<delim>', expand=True).values,
columns=['team1', 'team2'])
too late to answer but here is my approach since no one mentioned this here:
why note a client side solution ?
a javascript implementation to store the mac in a cookie (you can encrypt it before that)
then each request must include that cookie name, else it will be rejected.
to make this even more fun you can make a server side verification
from the mac address you get the manifacturer (there are plenty of free APIs for this)
then compare it with the user_agent value to see if there was some sort of manipulation:
a mac address of HP + a user agent of Safari = reject request.
If you want the types of convenience methods mentioned in other answers but need portability (or even if you don't), you might want to check out Flurl [disclosure: I'm the author]. It (thinly) wraps HttpClient
and Json.NET and adds some fluent sugar and other goodies, including some baked-in testing helpers.
Post as JSON:
var resp = await "http://localhost:44268/api/test".PostJsonAsync(widget);
or URL-encoded:
var resp = await "http://localhost:44268/api/test".PostUrlEncodedAsync(widget);
Both examples above return an HttpResponseMessage
, but Flurl includes extension methods for returning other things if you just want to cut to the chase:
T poco = await url.PostJsonAsync(data).ReceiveJson<T>();
dynamic d = await url.PostUrlEncodedAsync(data).ReceiveJson();
string s = await url.PostUrlEncodedAsync(data).ReceiveString();
Flurl is available on NuGet:
PM> Install-Package Flurl.Http
You simply use the apply()
function:
R> M <- matrix(1:6, nrow=3, byrow=TRUE)
R> M
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
R> apply(M, 1, function(x) 2*x[1]+x[2])
[1] 4 10 16
R>
This takes a matrix and applies a (silly) function to each row. You pass extra arguments to the function as fourth, fifth, ... arguments to apply()
.
I have a large file in excel dealing with purchase and sale of mutual fund units. Number of rows in a worksheet exceeds 4000. I have no experience with VBA and would like to work with basic excel. Taking the cue from the solutions suggested above, I tried to solve the problem ( to insert blank rows automatically) in the following manner:
This method also may be tried by the readers.
PHP uses weak typing (which it calls 'type juggling'), which is a bad idea (though that's a conversation for another time). When you try to use a variable in a context that requires a boolean, it will convert whatever your variable is into a boolean, according to some mostly arbitrary rules available here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
Consider the following scenario:
public class Car {
@Inject
private Engine engine;
public Car() {
engine.initialize();
}
...
}
Since Car has to be instantiated prior to field injection, the injection point engine is still null during the execution of the constructor, resulting in a NullPointerException.
This problem can be solved either by JSR-330 Dependency Injection for Java constructor injection or JSR 250 Common Annotations for the Java @PostConstruct method annotation.
@PostConstruct
JSR-250 defines a common set of annotations which has been included in Java SE 6.
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.
JSR-250 Chap. 2.5 javax.annotation.PostConstruct
The @PostConstruct annotation allows for the definition of methods to be executed after the instance has been instantiated and all injects have been performed.
public class Car {
@Inject
private Engine engine;
@PostConstruct
public void postConstruct() {
engine.initialize();
}
...
}
Instead of performing the initialization in the constructor, the code is moved to a method annotated with @PostConstruct.
The processing of post-construct methods is a simple matter of finding all methods annotated with @PostConstruct and invoking them in turn.
private void processPostConstruct(Class type, T targetInstance) {
Method[] declaredMethods = type.getDeclaredMethods();
Arrays.stream(declaredMethods)
.filter(method -> method.getAnnotation(PostConstruct.class) != null)
.forEach(postConstructMethod -> {
try {
postConstructMethod.setAccessible(true);
postConstructMethod.invoke(targetInstance, new Object[]{});
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
throw new RuntimeException(ex);
}
});
}
The processing of post-construct methods has to be performed after instantiation and injection have been completed.
If table_2
is empty, then try the following insert statement:
insert into table_2 (itemid,location1)
select itemid,quantity from table_1 where locationid=1
If table_2
already contains the itemid
values, then try this update statement:
update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)
The ListView control uses the Items collection to add items to listview in the control and is able to customize items.
ws2s project is aimed at bring socket to browser-side js. It is a websocket server which transform websocket to socket.
ws2s schematic diagram
code sample:
var socket = new WS2S("wss://ws2s.feling.io/").newSocket()
socket.onReady = () => {
socket.connect("feling.io", 80)
socket.send("GET / HTTP/1.1\r\nHost: feling.io\r\nConnection: close\r\n\r\n")
}
socket.onRecv = (data) => {
console.log('onRecv', data)
}
As DOC says, you can pass data to the handler as next:
// say your selector and click handler looks something like this...
$("some selector").on('click',{param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
// access element's id where click occur
alert( event.target.id );
}
SELECT DISTINCT will always be the same, or faster, than a GROUP BY. On some systems (i.e. Oracle), it might be optimized to be the same as DISTINCT for most queries. On others (such as SQL Server), it can be considerably faster.
First check the default-jdk
package, good chance it already provide you an OpenJDK >= 11
.
ref: https://packages.ubuntu.com/search?keywords=default-jdk&searchon=names&suite=all§ion=all
So starting from Ubuntu 18.04 LTS it should be ok.
sudo apt update -qq
sudo apt install -yq default-jdk
note: don't forget to set JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/default-java
mvn -version
For Ubuntu 16.04 LTS, only openjdk-8-jdk
is provided in the official repos so you need to find it in a ppa:
sudo add-apt-repository -y ppa:openjdk-r/ppa
sudo apt update -qq
sudo apt install -yq openjdk-11-jdk
note: don't forget to set JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
mvn -version
Unless you are doing a DB to track historical times more than a century ago, using
Modified datetime DEFAULT ((0))
is perfectly safe and sound and allows more elegant queries than '1753-01-01' and more efficient queries than NULL
.
However, since first Modified datetime
is the time at which the record was inserted, you can use:
Modified datetime NOT NULL DEFAULT (GETUTCDATE())
which avoids the whole issue and makes your inserts easier and safer - as in you don't insert it at all and SQL does the housework :-)
With that in place you can still have elegant and fast queries by using 0 as a practical minimum since it's guranteed to always be lower than any insert-generated GETUTCDATE()
.
This is a very round-about way of doing it but if you want to make a histogram where you already know the bin values but dont have the source data, you can use the np.random.randint
function to generate the correct number of values within the range of each bin for the hist function to graph, for example:
import numpy as np
import matplotlib.pyplot as plt
data = [np.random.randint(0, 9, *desired y value*), np.random.randint(10, 19, *desired y value*), etc..]
plt.hist(data, histtype='stepfilled', bins=[0, 10, etc..])
as for labels you can align x ticks with bins to get something like this:
#The following will align labels to the center of each bar with bin intervals of 10
plt.xticks([5, 15, etc.. ], ['Label 1', 'Label 2', etc.. ])
I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.
.labels {
color: red;
background-color: white;
font-family: "Lucida Grande", "Arial", sans-serif;
font-size: 10px;
font-weight: bold;
text-align: center;
width: 60px;
border: 2px solid black;
white-space: nowrap;
}
JavaScript:
var marker = new MarkerWithLabel({
position: homeLatLng,
draggable: true,
map: map,
labelContent: "$425K",
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75}
});
The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50)
.
In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|
I happened to be working in localhost , in windows 10, using WAMP, as it turns out, Wamp has a really accessible configuration interface to change the MySQL configuration. You just need to go to the Wamp panel, then to MySQL, then to settings and change the mode to sql-mode: none.(essentially disabling the strict mode) The following picture illustrates this.
I would use the algorithm to compute the distance between a point (circle center) and a line (line AB). This can then be used to determine the intersection points of the line with the circle.
Let say we have the points A, B, C. Ax and Ay are the x and y components of the A points. Same for B and C. The scalar R is the circle radius.
This algorithm requires that A, B and C are distinct points and that R is not 0.
Here is the algorithm
// compute the euclidean distance between A and B
LAB = sqrt( (Bx-Ax)²+(By-Ay)² )
// compute the direction vector D from A to B
Dx = (Bx-Ax)/LAB
Dy = (By-Ay)/LAB
// the equation of the line AB is x = Dx*t + Ax, y = Dy*t + Ay with 0 <= t <= LAB.
// compute the distance between the points A and E, where
// E is the point of AB closest the circle center (Cx, Cy)
t = Dx*(Cx-Ax) + Dy*(Cy-Ay)
// compute the coordinates of the point E
Ex = t*Dx+Ax
Ey = t*Dy+Ay
// compute the euclidean distance between E and C
LEC = sqrt((Ex-Cx)²+(Ey-Cy)²)
// test if the line intersects the circle
if( LEC < R )
{
// compute distance from t to circle intersection point
dt = sqrt( R² - LEC²)
// compute first intersection point
Fx = (t-dt)*Dx + Ax
Fy = (t-dt)*Dy + Ay
// compute second intersection point
Gx = (t+dt)*Dx + Ax
Gy = (t+dt)*Dy + Ay
}
// else test if the line is tangent to circle
else if( LEC == R )
// tangent point to circle is E
else
// line doesn't touch circle
You can change the passwd file directly for the particular user or use the below command
chsh -s /usr/local/bin/bash username
Then log out and log in
LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.
Not sure if this is the most elegant solution (this is what I used), but you could scale your data to the range between 0 to 1 and then modify the colorbar:
import matplotlib as mpl
...
ax, _ = mpl.colorbar.make_axes(plt.gca(), shrink=0.5)
cbar = mpl.colorbar.ColorbarBase(ax, cmap=cm,
norm=mpl.colors.Normalize(vmin=-0.5, vmax=1.5))
cbar.set_clim(-2.0, 2.0)
With the two different limits you can control the range and legend of the colorbar. In this example only the range between -0.5 to 1.5 is show in the bar, while the colormap covers -2 to 2 (so this could be your data range, which you record before the scaling).
So instead of scaling the colormap you scale your data and fit the colorbar to that.
Here is your Tag.
<asp:LinkButton ID="LinkButton1" runat="server">Open Test Page</asp:LinkButton>
Here is your code on the code behind.
LinkButton1.Attributes.Add("href","../Test.aspx")
LinkButton1.Attributes.Add("target","_blank")
Hope this will be helpful for someone.
Edit To do the same with a link button inside a template field, use the following code.
Use GridView_RowDataBound event to find Link button.
Dim LB as LinkButton = e.Row.FindControl("LinkButton1")
LB.Attributes.Add("href","../Test.aspx")
LB.Attributes.Add("target","_blank")
Solution to iOS7 prior and iOS7 above
//
// UILabel+DynamicHeight.m
// For StackOverFlow
//
// Created by Vijay on 24/02/14.
// Copyright (c) 2014 http://Vijay-Apple-Dev.blogspot.com. All rights reserved.
//
#import <UIKit/UIKit.h>
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define iOS7_0 @"7.0"
@interface UILabel (DynamicHeight)
/*====================================================================*/
/* Calculate the size,bounds,frame of the Multi line Label */
/*====================================================================*/
/**
* Returns the size of the Label
*
* @param aLabel To be used to calculte the height
*
* @return size of the Label
*/
-(CGSize)sizeOfMultiLineLabel;
@end
//
// UILabel+DynamicHeight.m
// For StackOverFlow
//
// Created by Vijay on 24/02/14.
// Copyright (c) 2014 http://Vijay-Apple-Dev.blogspot.com. All rights reserved.
//
#import "UILabel+DynamicHeight.h"
@implementation UILabel (DynamicHeight)
/*====================================================================*/
/* Calculate the size,bounds,frame of the Multi line Label */
/*====================================================================*/
/**
* Returns the size of the Label
*
* @param aLabel To be used to calculte the height
*
* @return size of the Label
*/
-(CGSize)sizeOfMultiLineLabel{
NSAssert(self, @"UILabel was nil");
//Label text
NSString *aLabelTextString = [self text];
//Label font
UIFont *aLabelFont = [self font];
//Width of the Label
CGFloat aLabelSizeWidth = self.frame.size.width;
if (SYSTEM_VERSION_LESS_THAN(iOS7_0)) {
//version < 7.0
return [aLabelTextString sizeWithFont:aLabelFont
constrainedToSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
}
else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7_0)) {
//version >= 7.0
//Return the calculated size of the Label
return [aLabelTextString boundingRectWithSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{
NSFontAttributeName : aLabelFont
}
context:nil].size;
}
return [self bounds].size;
}
@end
The problem seems to be that you expect plt.show()
to show the window and then to return. It does not do that. The program will stop at that point and only resume once you close the window. You should be able to test that: If you close the window and then another window should pop up.
To resolve that problem just call plt.show()
once after your loop. Then you get the complete plot. (But not a 'real-time plotting')
You can try setting the keyword-argument block
like this: plt.show(block=False)
once at the beginning and then use .draw()
to update.
yes, by using css styles white-space: pre-wrap; in the .dropdown class of the bootstrap by overriding it. Earlier it is white-space: nowrap; so it makes the dropdown wrapped into one line. pre-wrap makes it as according to the width.
You can only break
a block scope if you label it. For example:
myBlock: {
var a = 0;
break myBlock;
a = 1; // this is never run
};
a === 0;
You cannot break a block scope from within a function in the scope. This means you can't do stuff like:
foo: { // this doesn't work
(function() {
break foo;
}());
}
You can do something similar though with functions:
function myFunction() {myFunction:{
// you can now use break myFunction; instead of return;
}}
This started happening for me after I installed GoogleChrome/puppeteer, the solution was to re-install npm:
$ npm i npm@latest
or
$ npm install npm@latest
Per the comments to the original post, merges / joins are well-suited for this problem. In particular, an inner join will return only values that are present in both dataframes, making thesetdiff
statement unnecessary.
Using the data from Dinre's example:
In base R:
cleanedA <- merge(data_A, data_B[, "index"], by = 1, sort = FALSE)
cleanedB <- merge(data_B, data_A[, "index"], by = 1, sort = FALSE)
Using the dplyr package:
library(dplyr)
cleanedA <- inner_join(data_A, data_B %>% select(index))
cleanedB <- inner_join(data_B, data_A %>% select(index))
To keep the data as two separate tables, each containing only its own variables, this subsets the unwanted table to only its index variable before joining. Then no new variables are added to the resulting table.
Reflection can help you.
var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);
This is my current way of doing it for bash (tested on Debian). Maybe there's a better way:
Don't do it with exec bash, for example like this:
#!/bin/bash
cd $1
exec bash
because while it appears to work, after you run it and your script finishes, yes you'll be in the correct directory, but you'll be in it in a subshell, which you can confirm by pressing Ctrl+D afterwards, and you'll see it exits the subshell, putting you back in your original directory.
This is usually not a state you want a script user to be left in after the script they run returns, because it's non-obvious that they're in a subshell and now they basically have two shells open when they thought they only had one. They might continue using this subshell and not realize it, and it could have unintended consequences.
If you really want the script to exit and leave open a subshell in the new directory, it's better if you change the PS1 variable so the script user has a visual indicator that they still have a subshell open.
Here's an example I came up with. It is two files, an outer.sh which you call directly, and an inner.sh which is sourced inside the outer.sh script. The outer script sets two variables, then sources the inner script, and afterwards it echoes the two variables (the second one has just been modified by the inner script). Afterwards it makes a temp copy of the current user's ~/.bashrc file, adds an override for the PS1 variable in it, as well as a cleanup routine, and finally it runs exec bash --rcfile pointing at the .bashrc.tmp file to initialize bash with a modified environment, including the modified prompt and the cleanup routine.
After outer.sh exits, you'll be left inside a subshell in the desired directory (in this case testdir/ which was entered into by the inner.sh script) with a visual indicator making it clear to you, and if you exit out of the subshell, the .bashrc.tmp file will be deleted by the cleanup routine, and you'll be back in the directory you started in.
Maybe there's a smarter way to do it, but that's the best way I could figure out in about 40 minutes of experimenting:
#!/bin/bash
var1="hello"
var2="world"
source inner.sh
echo $var1
echo $var2
cp ~/.bashrc .bashrc.tmp
echo 'export PS1="(subshell) $PS1"' >> .bashrc.tmp
cat <<EOS >> .bashrc.tmp
cleanup() {
echo "cleaning up..."
rm .bashrc.tmp
}
trap 'cleanup' 0
EOS
exec bash --rcfile .bashrc.tmp
cd testdir
var2="bird"
then run:
$ mkdir testdir
$ chmod 755 outer.sh
$ ./outer.sh
it should output:
hello
bird
and then drop you into your subshell using exec bash, but with a modified prompt which makes that obvious, something like:
(subshell) user@computername:~/testdir$
and if you Ctrl-D out of the subshell, it should clean up by deleting a temporary .bashrc.tmp file in the testdir/ directory
I wonder if there's a better way than having to copy the .bashrc file like that though to change the PS1 var properly in the subshell...
It's unfortunate that it seems JavaScript has no simple way to validate a date string to these days. This is the simplest way I can think of to parse dates in the format "m/d/yyyy" in modern browsers (that's why it doesn't specify the radix to parseInt, since it should be 10 since ES5):
const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;_x000D_
function isValidDate(strDate) {_x000D_
if (!dateValidationRegex.test(strDate)) return false;_x000D_
const [m, d, y] = strDate.split('/').map(n => parseInt(n));_x000D_
return m === new Date(y, m - 1, d).getMonth() + 1;_x000D_
}_x000D_
_x000D_
['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {_x000D_
console.log(d, isValidDate(d));_x000D_
});
_x000D_
This answer actually has two parts, a UX warning, and an actual solution.
UX Warning
If your modal contains so much that it needs to scroll, ask yourself if you should be using a modal at all. The size of the bootstrap modal by default is a pretty good constraint on how much visual information should fit. Depending on what you're making, you may instead want to opt for a new page or a wizard.
Actual Solution
Is here: http://jsfiddle.net/ajkochanowicz/YDjsE/2/
This solution will also allow you to change the height of .modal
and have the .modal-body
take up the remaining space with a vertical scrollbar if necessary.
UPDATE
Note that in Bootstrap 3, the modal has been refactored to better handle overflowing content. You'll be able to scroll the modal itself up and down as it flows under the viewport.
VLOOKUP deosnt work for String literals
As others have said, you can use a DateTime
and ignore the date, or use a TimeSpan
. Personally I'm not keen on either of these solutions, as neither type really reflects the concept you're trying to represent - I regard the date/time types in .NET as somewhat on the sparse side which is one of the reasons I started Noda Time. In Noda Time, you can use the LocalTime
type to represent a time of day.
One thing to consider: the time of day is not necessarily the length of time since midnight on the same day...
(As another aside, if you're also wanting to represent a closing time of a shop, you may find that you want to represent 24:00, i.e. the time at the end of the day. Most date/time APIs - including Noda Time - don't allow that to be represented as a time-of-day value.)
In the spring jar package, I use new ClassPathResource(filename).getFile()
, which throws the exception:
cannot be resolved to absolute file path because it does not reside in the file system: jar
But using new ClassPathResource(filename).getInputStream()
will solve this problem. The reason is that the configuration file in the jar does not exist in the operating system's file tree,so must use getInputStream()
.
I had the same problem on my Ubuntu 14.04 when tried to install TopTracker. I got such errors:
/usr/share/toptracker/bin/TopTracker: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version 'CXXABI_1.3.8' not found (required by /usr/share/toptracker/bin/TopTracker) /usr/share/toptracker/bin/TopTracker: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version 'GLIBCXX_3.4.21' not found (required by /usr/share/toptracker/bin/TopTracker) /usr/share/toptracker/bin/TopTracker: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version 'CXXABI_1.3.9' not found (required by /usr/share/toptracker/bin/TopTracker)
But I then installed gcc 4.9 version and problem gone:
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-4.9 g++-4.9
There is Two steps
1) Create this file in your drawable folder :- rounded_corner.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="10dp" /> // set radius of corner
<stroke android:width="2dp" android:color="#ff3478" /> // set color and width of border
<solid android:color="#FFFFFF" /> // inner bgcolor
</shape>
2) Set this file into your TextView
as background property.
android:background="@drawable/rounded_corner"
You can use this drawable in Button or Edittext also
I think every process you make start executing the line you create so something like this...
pid=fork() at line 6. fork function returns 2 values
you have 2 pids, first pid=0 for child and pid>0 for parent
so you can use if to separate
.
/*
sleep(int time) to see clearly
<0 fail
=0 child
>0 parent
*/
int main(int argc, char** argv) {
pid_t childpid1, childpid2;
printf("pid = process identification\n");
printf("ppid = parent process identification\n");
childpid1 = fork();
if (childpid1 == -1) {
printf("Fork error !\n");
}
if (childpid1 == 0) {
sleep(1);
printf("child[1] --> pid = %d and ppid = %d\n",
getpid(), getppid());
} else {
childpid2 = fork();
if (childpid2 == 0) {
sleep(2);
printf("child[2] --> pid = %d and ppid = %d\n",
getpid(), getppid());
} else {
sleep(3);
printf("parent --> pid = %d\n", getpid());
}
}
return 0;
}
//pid = process identification
//ppid = parent process identification
//child[1] --> pid = 2399 and ppid = 2398
//child[2] --> pid = 2400 and ppid = 2398
//parent --> pid = 2398
How and where is
app.run()
used? After module definition or afterapp.config()
, afterapp.controller()
?
In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js
Make it look like this
var app = angular.module('mean.dashboard', ['ui.bootstrap']);
app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
function($scope, Global, Dashboard) {
$scope.global = Global;
$scope.package = {
name: 'dashboard'
};
// ...
}
]);
app.run(function(editableOptions) {
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});
string test = "<body><head>test header</head></body>";
XmlDocument xmltest = new XmlDocument();
xmltest.LoadXml(test);
XmlNodeList elemlist = xmltest.GetElementsByTagName("head");
string result = elemlist[0].InnerXml;
//result -> "test header"
The .cc extension is necessary for using implicit rules within makefiles. Look through these links to get a better understanding of makefiles, but look mainly the second one, as it clearly says the usefulness of the .cc extension:
ftp://ftp.gnu.org/old-gnu/Manuals/make-3.79.1/html_chapter/make_2.html
https://ftp.gnu.org/old-gnu/Manuals/make-3.79.1/html_chapter/make_10.html
I just learned of this now.
Also, you can use bool method(s)
Query :
DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
where isValid(Field<string>("UserName"))// && otherMethod() && otherMethod2()
select r;
DataTable newDT = query.CopyToDataTable();
Method:
bool isValid(string userName)
{
if(userName == "XXXX" || userName == "YYYY")
return false;
else return true;
}
Not just mvn
, for any util, you can find out yourself by giving yum whatprovides {command_name}
Try var
var s = new List<string> { "a", "bk", "ca", "d" };
Oracle
stores numbers in the following way: 1 byte
for power, 1 byte
for the first significand digit (that is one before the separator), the rest for the other digits.
By digits
here Oracle
means centesimal digits
(i. e. base 100
)
SQL> INSERT INTO t_numtest VALUES (LPAD('9', 125, '9'))
2 /
1 row inserted
SQL> INSERT INTO t_numtest VALUES (LPAD('7', 125, '7'))
2 /
1 row inserted
SQL> INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))
2 /
INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))
ORA-01426: numeric overflow
SQL> SELECT DUMP(num) FROM t_numtest;
DUMP(NUM)
--------------------------------------------------------------------------------
Typ=2 Len=2: 255,11
Typ=2 Len=21: 255,8,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,79
As we can see, the maximal number here is 7.(7) * 10^124
, and he have 19
centesimal digits for precision, or 38
decimal digits.
This is a String, not a json structure(key, value), try:
return new ResponseEntity("{"vale" : "This is a String"}", HttpStatus.OK);
I do not know of a standalone PHP / Apache solution, as this would require a PHP library that can read and render SVG images. I'm not sure such a library exists - I don't know any.
ImageMagick is able to rasterize SVG files, either through the command line or the PHP binding, IMagick, but seems to have a number of quirks and external dependencies as shown e.g. in this forum thread. I think it's still the most promising way to go, it's the first thing I would look into if I were you.
JSONObject baseReq
LinkedHashMap insert = (LinkedHashMap) baseReq.get("insert");
LinkedHashMap delete = (LinkedHashMap) baseReq.get("delete");
As I can't comment yet, I want to show the solution I used based on the method Umair Ahmed posted, but when you want to search for a key instead of a value:
[{"a":true}, {"f":true}, {"g":false}]
.findIndex(function(element){return Object.keys(element)[0] == "g"});
I understand that it doesn't answer the expanded question, but the title doesn't specify what was wanted from each object, so I want to humbly share this to save headaches to others in the future, while I undestart it may not be the fastest solution.
i use firebase-database in html signup but last error i cannot understand if anybody know tell me . error is "Failed to load resource: the server responded with a status of 404 ()"
For me it was using {{ }} instead of {% %}:
href="{{ static 'bootstrap.min.css' }}" # wrong
href="{% static 'bootstrap.min.css' %}" # right
win = new BrowserWindow({width: 1000, height: 1000,icon: __dirname + '/logo.png'}); //*.png or *.ico will also work
in my case it worked !
My windows firewall was blocking port 8080 so i changed it to 5000 and it worked!
One can also try below:
public class RandomInt {
public static void main(String[] args) {
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
double Random;
if (n1 != n2)
{
if (n1 > n2)
{
Random = n2 + (Math.random() * (n1 - n2));
System.out.println("Your random number is: " + Random);
}
else
{
Random = n1 + (Math.random() * (n2 - n1));
System.out.println("Your random number is: " +Random);
}
} else {
System.out.println("Please provide valid Range " +n1+ " " +n2+ " are equal numbers." );
}
}
}
More importantly, the 2013 versions of Visual Studio Express have all the languages that comes with the commercial versions. You can use the Windows desktop versions not only to program using Windows Forms, it is possible to write those windowed applications with any language that comes with the software, may it be C++ using the windows.h header if you want to actually learn how to create windows applications from scratch, or use Windows form to create windows in C# or visual Basic.
In the past, you had to download one version for each language or type of content. Or just download an all-in-one that still installed separate versions of the software for different languages. Now with 2013 you get all the languages needed in each content oriented version of the 2013 express.
You pick what matters the most to you.
Besides, it might be a good way to learn using notepad and the command line to write and compile, but I find that a bit tedious to use. While using an IDE might be overwhelming at first, you start small, learning how to create a project, write code, compile your code. They have gone way over their heads to ease up your day when you take it for the first time.
Did you mean len(list1)-1
?
If you're searching for other method, you can try list1.index(list1[-1])
, but I don't recommend this one. You will have to be sure, that the list contains NO duplicates.
It depends on your application and its use as to the level of security you need.
In terms of security, you should be validating all values you get from the querystring or post parameters, to ensure they're valid.
You may also wish to add logging for others, including analysis of weblogs so you can determine if an attempt to hack your system is occuring.
I don't believe it's possible to inject javascript into a URL and have this run, unless your application is using parameters without validating them first.
Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule
It will be $_COOKIE['CaptchaResponseValue']
, not $_COOKIE('CaptchaResponseValue')
Swift
If you are not using object then you can user this code for contains.
let elements = [ 10, 20, 30, 40, 50]
if elements.contains(50) {
print("true")
}
If you are using NSObject Class in swift. This variables is according to my requirement. you can modify for your requirement.
var cliectScreenList = [ATModelLeadInfo]()
var cliectScreenSelectedObject: ATModelLeadInfo!
This is for a same data type.
{ $0.user_id == cliectScreenSelectedObject.user_id }
If you want to AnyObject type.
{ "\($0.user_id)" == "\(cliectScreenSelectedObject.user_id)" }
Full condition
if cliectScreenSelected.contains( { $0.user_id == cliectScreenSelectedObject.user_id } ) == false {
cliectScreenSelected.append(cliectScreenSelectedObject)
print("Object Added")
} else {
print("Object already exists")
}
I've been using ClockPick.
Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:
angular.module('myApp', ['myApp.directives', 'myApp.services']);
plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview
Both certificates should exist prior to the connection. They're usually created by Certification Authorities (not necessarily the same). (There are alternative cases where verification can be done differently, but some verification will need to be made.)
The server certificate should be created by a CA that the client trusts (and following the naming conventions defined in RFC 6125).
The client certificate should be created by a CA that the server trusts.
It's up to each party to choose what it trusts.
There are online CA tools that will allow you to apply for a certificate within your browser and get it installed there once the CA has issued it. They need not be on the server that requests client-certificate authentication.
The certificate distribution and trust management is the role of the Public Key Infrastructure (PKI), implemented via the CAs. The SSL/TLS client and servers and then merely users of that PKI.
When the client connects to a server that requests client-certificate authentication, the server sends a list of CAs it's willing to accept as part of the client-certificate request. The client is then able to send its client certificate, if it wishes to and a suitable one is available.
The main advantages of client-certificate authentication are:
You may be interested in Advantages of client certificates for client authentication? (on Security.SE).
Your typedef
needs to be in the header file (or some other file that's #import
ed into your header), because otherwise the compiler won't know what size to make the PlayerState
ivar. Other than that, it looks ok to me.
The trouble with using dates as x-values, is that if you want a bar chart like in your second picture, they are going to be wrong. You should either use a stacked bar chart (colours on top of each other) or group by date (a "fake" date on the x-axis, basically just grouping the data points).
import numpy as np
import matplotlib.pyplot as plt
N = 3
ind = np.arange(N) # the x locations for the groups
width = 0.27 # the width of the bars
fig = plt.figure()
ax = fig.add_subplot(111)
yvals = [4, 9, 2]
rects1 = ax.bar(ind, yvals, width, color='r')
zvals = [1,2,3]
rects2 = ax.bar(ind+width, zvals, width, color='g')
kvals = [11,12,13]
rects3 = ax.bar(ind+width*2, kvals, width, color='b')
ax.set_ylabel('Scores')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('2011-Jan-4', '2011-Jan-5', '2011-Jan-6') )
ax.legend( (rects1[0], rects2[0], rects3[0]), ('y', 'z', 'k') )
def autolabel(rects):
for rect in rects:
h = rect.get_height()
ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
plt.show()
None of the above fixed my problem.
I added "C:/Windows/System32" to the 'Path' or 'PATH' environment variable. I could use the reg /?
command. I also ran the 'vcvarsall.bat' file with no error message.
My error is that I was running VS2012 Cross Tools Command Prompt instead of VS2013 Cross Tools Command Prompt.
The reason being the file structure in the start menu. 2010 and 2012 are under 'Microsoft Visual Studio YEAR' and 2013 is under 'Visual Studio YEAR'. I just didn't realize this. :/
I hope this helps someone.
The same problem arrised for me when I installed Kaliko CMS Nuget Package. When I removed it, it started working fine again. So, your problem could be because of a recently installed Nuget Package. Uninstall it and your solution will work just fine.
Check jquery waypoints
here
Fiddle for example JSFiddle
When is scrolled to certain div, change your background color in jquery.
To call a sub inside another sub you only need to do:
Call Subname()
So where you have CalculateA(Nc,kij, xi, a1, a)
you need to have call CalculateA(Nc,kij, xi, a1, a)
As the which runs first problem it's for you to decide, when you want to run a sub you can go to the macro list select the one you want to run and run it, you can also give it a key shortcut, therefore you will only have to press those keys to run it. Although, on secondary subs, I usually do it as Private sub CalculateA(...)
cause this way it does not appear in the macro list and it's easier to work
Hope it helps, Bruno
PS: If you have any other question just ask, but this isn't a community where you ask for code, you come here with a question or a code that isn't running and ask for help, not like you did "It would be great if you could write it in the Excel VBA format."
There's actually a way to do this without javascript.
If you set an <input>
's required
selector to true, you can check if there's text in it with the CSS :valid
tag.
References:
input {
background: red;
}
input:valid {
background: lightgreen;
}
_x000D_
<input type="text" required>
_x000D_
Include: #include<stdlib.h>
and use System("cls")
instead of clrscr()
You're actually supposed to use $("#terms").dialog({ autoOpen: false });
to initialize it.
Then you can use $('#terms').dialog('open');
to open the dialog, and $('#terms').dialog('close');
to close it.
SELECT word, COUNT(*) FROM words GROUP by word HAVING COUNT(*) > 1
You can safely delete the WSDL cache files. If you wish to prevent future caching, use:
ini_set("soap.wsdl_cache_enabled", 0);
or dynamically:
$client = new SoapClient('http://somewhere.com/?wsdl', array('cache_wsdl' => WSDL_CACHE_NONE) );
Try to use:
location.reload(true);
When this method receives a true
value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
More info:
if you are using windows or linux operating system then type in command prompt / terminal
java -version
If java is correctly installed then you will get something like this
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
Java HotSpot(TM) Client VM (build 23.25-b01, mixed mode, sharing)
Side note: After installation of Java on a windows operating system, the PATH variable is changed to add java.exe so you need to re-open cmd.exe to reload the PATH variable.
Edit:
CD to the path first...
cd C:\ProgramData\Oracle\Java\javapath
java -version
Here's a simple Kalman filter that could be used for exactly this situation. It came from some work I did on Android devices.
General Kalman filter theory is all about estimates for vectors, with the accuracy of the estimates represented by covariance matrices. However, for estimating location on Android devices the general theory reduces to a very simple case. Android location providers give the location as a latitude and longitude, together with an accuracy which is specified as a single number measured in metres. This means that instead of a covariance matrix, the accuracy in the Kalman filter can be measured by a single number, even though the location in the Kalman filter is a measured by two numbers. Also the fact that the latitude, longitude and metres are effectively all different units can be ignored, because if you put scaling factors into the Kalman filter to convert them all into the same units, then those scaling factors end up cancelling out when converting the results back into the original units.
The code could be improved, because it assumes that the best estimate of current location is the last known location, and if someone is moving it should be possible to use Android's sensors to produce a better estimate. The code has a single free parameter Q, expressed in metres per second, which describes how quickly the accuracy decays in the absence of any new location estimates. A higher Q parameter means that the accuracy decays faster. Kalman filters generally work better when the accuracy decays a bit quicker than one might expect, so for walking around with an Android phone I find that Q=3 metres per second works fine, even though I generally walk slower than that. But if travelling in a fast car a much larger number should obviously be used.
public class KalmanLatLong {
private final float MinAccuracy = 1;
private float Q_metres_per_second;
private long TimeStamp_milliseconds;
private double lat;
private double lng;
private float variance; // P matrix. Negative means object uninitialised. NB: units irrelevant, as long as same units used throughout
public KalmanLatLong(float Q_metres_per_second) { this.Q_metres_per_second = Q_metres_per_second; variance = -1; }
public long get_TimeStamp() { return TimeStamp_milliseconds; }
public double get_lat() { return lat; }
public double get_lng() { return lng; }
public float get_accuracy() { return (float)Math.sqrt(variance); }
public void SetState(double lat, double lng, float accuracy, long TimeStamp_milliseconds) {
this.lat=lat; this.lng=lng; variance = accuracy * accuracy; this.TimeStamp_milliseconds=TimeStamp_milliseconds;
}
/// <summary>
/// Kalman filter processing for lattitude and longitude
/// </summary>
/// <param name="lat_measurement_degrees">new measurement of lattidude</param>
/// <param name="lng_measurement">new measurement of longitude</param>
/// <param name="accuracy">measurement of 1 standard deviation error in metres</param>
/// <param name="TimeStamp_milliseconds">time of measurement</param>
/// <returns>new state</returns>
public void Process(double lat_measurement, double lng_measurement, float accuracy, long TimeStamp_milliseconds) {
if (accuracy < MinAccuracy) accuracy = MinAccuracy;
if (variance < 0) {
// if variance < 0, object is unitialised, so initialise with current values
this.TimeStamp_milliseconds = TimeStamp_milliseconds;
lat=lat_measurement; lng = lng_measurement; variance = accuracy*accuracy;
} else {
// else apply Kalman filter methodology
long TimeInc_milliseconds = TimeStamp_milliseconds - this.TimeStamp_milliseconds;
if (TimeInc_milliseconds > 0) {
// time has moved on, so the uncertainty in the current position increases
variance += TimeInc_milliseconds * Q_metres_per_second * Q_metres_per_second / 1000;
this.TimeStamp_milliseconds = TimeStamp_milliseconds;
// TO DO: USE VELOCITY INFORMATION HERE TO GET A BETTER ESTIMATE OF CURRENT POSITION
}
// Kalman gain matrix K = Covarariance * Inverse(Covariance + MeasurementVariance)
// NB: because K is dimensionless, it doesn't matter that variance has different units to lat and lng
float K = variance / (variance + accuracy * accuracy);
// apply K
lat += K * (lat_measurement - lat);
lng += K * (lng_measurement - lng);
// new Covarariance matrix is (IdentityMatrix - K) * Covarariance
variance = (1 - K) * variance;
}
}
}
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
When using NOT IN, you should also consider NOT EXISTS, which handles the null cases silently. See also PostgreSQL Wiki
SELECT mac, creation_date
FROM logs lo
WHERE logs_type_id=11
AND NOT EXISTS (
SELECT *
FROM consols nx
WHERE nx.mac = lo.mac
);
To drop all documents in a collection:
await mongoose.connection.db.dropDatabase();
This answer is based off the mongoose index.d.ts file:
dropDatabase(): Promise<any>;
The Java 7 Files utility type is useful for working with files:
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.*;
public class WriteReadUtf8 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList("These", "are", "lines");
Path textFile = Paths.get("foo.txt");
Files.write(textFile, lines, StandardCharsets.UTF_8);
List<String> read = Files.readAllLines(textFile, StandardCharsets.UTF_8);
System.out.println(lines.equals(read));
}
}
The Java 8 version allows you to omit the Charset argument - the methods default to UTF-8.
declare @StartDate datetime, @EndDate datetime
select @StartDate = '10/01/2012 08:40:18.000',@EndDate='10/04/2012 09:52:48.000'
select convert(varchar(5),DateDiff(s, @startDate, @EndDate)/3600)+':'+convert(varchar(5),DateDiff(s, @startDate, @EndDate)%3600/60)+':'+convert(varchar(5),(DateDiff(s, @startDate, @EndDate)%60)) as [hh:mm:ss]
This query will helpful to you.
I also faced same problem & here is how I solved :-
I want to change package name np.com.shivakrstha.userlog to np.edu.khec.userlog
I selected shivakrstha and I pressed Shift + F6 for Rename Refract and renamed to khec.
Finally, use the same package name in AndroidManifest.xml, applicationId in build.gradle and don't forget to Rebuild Your Project.
Note:- I tried to change np to jp, so I selected np and I pressed Shift + F6 for Rename Refract and renamed to jp, it's ok to change others too.
On your own system, try
install.packages("foo", dependencies=...)
with the dependencies=
argument is documented as
dependencies: logical indicating to also install uninstalled packages
which these packages depend on/link to/import/suggest (and so
on recursively). Not used if ‘repos = NULL’. Can also be a
character vector, a subset of ‘c("Depends", "Imports",
"LinkingTo", "Suggests", "Enhances")’.
Only supported if ‘lib’ is of length one (or missing), so it
is unambiguous where to install the dependent packages. If
this is not the case it is ignored, with a warning.
The default, ‘NA’, means ‘c("Depends", "Imports",
"LinkingTo")’.
‘TRUE’ means (as from R 2.15.0) to use ‘c("Depends",
"Imports", "LinkingTo", "Suggests")’ for ‘pkgs’ and
‘c("Depends", "Imports", "LinkingTo")’ for added
dependencies: this installs all the packages needed to run
‘pkgs’, their examples, tests and vignettes (if the package
author specified them correctly).
so you probably want a value TRUE
.
In your package, list what is needed in Depends:
, see the
Writing R Extensions manual which is pretty clear on this.
You need to convert all the values in the column to date in order to sort by date.
Since the question mentioned third-party libraries and not all packages then you probably want to fall back to using wildcards.
A use case being: I just want to update all my packages that are obtained from the Github VCS, then you would just say:
go get -u github.com/... // ('...' being the wildcard).
This would go ahead and only update your github packages in the current $GOPATH
Same applies for within a VCS too, say you want to only upgrade all the packages from ogranizaiton A's repo's since as they have released a hotfix you depend on:
go get -u github.com/orgA/...
Here is a good discussion on the topic. Gavin King recommends @Inject over @EJB for non remote EJBs.
http://www.seamframework.org/107780.lace
or
https://web.archive.org/web/20140812065624/http://www.seamframework.org/107780.lace
Re: Injecting with @EJB or @Inject?
- Nov 2009, 20:48 America/New_York | Link Gavin King
That error is very strange, since EJB local references should always be serializable. Bug in glassfish, perhaps?
Basically, @Inject is always better, since:
it is more typesafe, it supports @Alternatives, and it is aware of the scope of the injected object.
I recommend against the use of @EJB except for declaring references to remote EJBs.
and
Re: Injecting with @EJB or @Inject?
Nov 2009, 17:42 America/New_York | Link Gavin King
Does it mean @EJB better with remote EJBs?
For a remote EJB, we can't declare metadata like qualifiers, @Alternative, etc, on the bean class, since the client simply isn't going to have access to that metadata. Furthermore, some additional metadata must be specified that we don't need for the local case (global JNDI name of whatever). So all that stuff needs to go somewhere else: namely the @Produces declaration.
This worked for me. Create WebViewClient like this below and set the webclient to your webview. I had to use webview.loadDataWithBaseURL as my urls (in my content) did not have the baseurl but only relative urls. You will get the url correctly only when there is a baseurl set using loadDataWithBaseURL.
public WebViewClient getWebViewClientWithCustomHeader(){
return new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
OkHttpClient httpClient = new OkHttpClient();
com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
.url(url.trim())
.addHeader("<your-custom-header-name>", "<your-custom-header-value>")
.build();
com.squareup.okhttp.Response response = httpClient.newCall(request).execute();
return new WebResourceResponse(
response.header("content-type", response.body().contentType().type()), // You can set something other as default content-type
response.header("content-encoding", "utf-8"), // Again, you can set another encoding as default
response.body().byteStream()
);
} catch (ClientProtocolException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
} catch (IOException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
}
}
};
}
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post()
method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.
Here is what you can do:
#include <algorithm>
int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);
However, in C++0x, you can do this:
std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};
Of course, if you choose to use std::vector
instead of raw array.
If you're in Python 3, there's a fork of JPype called JPype1-py3
pip install JPype1-py3
This works for me on OSX / Python 3.4.3. (You may need to export JAVA_HOME=/Library/Java/JavaVirtualMachines/your-java-version
)
from jpype import *
startJVM(getDefaultJVMPath(), "-ea")
java.lang.System.out.println("hello world")
shutdownJVM()
// Used In TypeScript For Angular 4+
const viewArray = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
const arrayObj = any;
const objectData = any;
for (let index = 0; index < this.viewArray.length; index++) {
this.arrayObj = this.viewArray[index];
this.arrayObj.filter((x) => {
if (x.id === id) {
this.objectData = x;
}
});
console.log('Json Object Data by ID ==> ', this.objectData);
}
};
This one is tricky problem, i set margin to textview in a row of a table layout. see the below:
TableLayout tl = new TableLayout(this);
tl.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
TableRow tr = new TableRow(this);
tr.setBackgroundResource(R.color.rowColor);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(4, 4, 4, 4);
TextView tv = new TextView(this);
tv.setBackgroundResource(R.color.textviewColor);
tv.setText("hello");
tr.addView(tv, params);
TextView tv2 = new TextView(this);
tv2.setBackgroundResource(R.color.textviewColor);
tv2.setText("hi");
tr.addView(tv2, params);
tl.addView(tr);
setContentView(tl);
the class needed to import for LayoutParams for use in a table row is :
import android.widget.**TableRow**.LayoutParams;
important to note that i added the class for table row. similarly many other classes are available to use LayoutParams like:
import android.widget.**RelativeLayout**.LayoutParams;
import android.widget.LinearLayout.LayoutParams;
so use accordingly.
I don't think there's a native trim()
method in the JavaScript standard. Maybe Mozilla supplies one, but if you want one in IE, you'll need to write it yourself. There are a few versions on this page.
In .NET Core, I was able to reach the same resolution as described in the accepted answer, by entering the following in package manager console:
Install-Package EntityFramework.Core -Pre
use mysql_fetch_assoc
to fetch the result at an associated array instead of mysql_fetch_array
which returns a numeric indexed array.
In Mac OS -moz-appearance: window;
will remove the arrow accrding to the MDN docs here: https://developer.mozilla.org/en-US/docs/CSS/-moz-appearance. Tested on Firefox 13 on Mac OS X 10.8.2. Also see: https://bugzilla.mozilla.org/show_bug.cgi?id=649849#c21.
If you set it programmatically you can just call it like a variable (i.e. document.getElementById('image_1').style.top
). Otherwise, you can always use jQuery:
<html>
<body>
<div id="test" style="height: 100px;">Test</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
alert($("#test").css("height"));
</script>
</body>
</html>
It appears there can by time drift if you're using Docker Machine, as this response suggests: https://stackoverflow.com/a/26454059/105562 , due to VirtualBox.
Quick and easy fix is to just restart your VM:
docker-machine restart default
I had the same issue on Windows, Docker 18.06.1-ce-win73 (19507)
.
Removing and re-adding the shared drive via the Docker settings panel and everything worked again.
I generally find the conditional command concatenation operators much more convenient than ERRORLEVEL.
yourCommand && (
echo yourCommand was successful
) || (
echo yourCommand failed
)
There is one complication you should be aware of. The error branch will fire if the last command in the success branch raises an error.
yourCommand && (
someCommandThatMayFail
) || (
echo This will fire if yourCommand or someCommandThatMayFail raises an error
)
The fix is to insert a harmless command that is guaranteed to succeed at the end of the success branch. I like to use (call )
, which does nothing except set the ERRORLEVEL to 0. There is a corollary (call)
that does nothing except set the ERRORLEVEL to 1.
yourCommand && (
someCommandThatMayFail
(call )
) || (
echo This can only fire if yourCommand raises an error
)
See Foolproof way to check for nonzero (error) return code in windows batch file for examples of the intricacies needed when using ERRORLEVEL to detect errors.
It sounds like you should be clearer about your RNG requirements. The strongest cryptographic RNG requirement (as I understand it) would be that even if you know the algorithm used to generate them, and you know all previously generated random numbers, you could not get any useful information about any of the random numbers generated in the future, without spending an impractical amount of computing power.
If you don't need this full guarantee of randomness then there are probably appropriate performance tradeoffs. I would tend to agree with Dan Dyer's response about AESCounterRNG from Uncommons-Maths, or Fortuna (one of its authors is Bruce Schneier, an expert in cryptography). I've never used either but the ideas appear reputable at first glance.
I would think that if you could generate an initial random seed periodically (e.g. once per day or hour or whatever), you could use a fast stream cipher to generate random numbers from successive chunks of the stream (if the stream cipher uses XOR then just pass in a stream of nulls or grab the XOR bits directly). ECRYPT's eStream project has lots of good information including performance benchmarks. This wouldn't maintain entropy between the points in time that you replenish it, so if someone knew one of the random numbers and the algorithm you used, technically it might be possible, with a lot of computing power, to break the stream cipher and guess its internal state to be able to predict future random numbers. But you'd have to decide whether that risk and its consequences are sufficient to justify the cost of maintaining entropy.
Edit: here's some cryptographic course notes on RNG I found on the 'net that look very relevant to this topic.
I moved my project from "standard" hosting to Azure and get the same error when I try to open page with url-rewrite. I.e. rule is :
<add key="/iPod-eBook-Creator.html" value="/Product/ProductDetail?PRODUCT_UID=IPOD_EBOOK_CREATOR" />
try to open my_site/iPod-eBook-Creator.html and get this error (page my_site/Product/ProductDetail?PRODUCT_UID=IPOD_EBOOK_CREATOR can be opened without any problem).
I checked the fully site - never used .. to "level up"
<asp:Button ID="btnSubmit" runat="server" OnClientClick ="showDiv()"
OnClick="btnImport_Click" Text="Upload" ></asp:Button>
In IIS 7 (not IIS 7.5), sites access files and folders based on the account set on the application pool for the site. By default, in IIS7, this account is NETWORK SERVICE
.
Specify an Identity for an Application Pool (IIS 7)
In IIS 7.5 (Windows 2008 R2 and Windows 7), the application pools run under the ApplicationPoolIdentity which is created when the application pool starts. If you want to set ACLS for this account, you need to choose IIS AppPool\ApplicationPoolName
instead of NT Authority\Network Service
.
It could be a case-sensitivity issue. Normally tables and columns are not case sensitive, but they will be if you use quotation marks. For example:
create table bad_design("goodLuckSelectingThisColumn" number);
I got this error because I didn't create my own test suite correctly:
Here is how I did it correctly:
Put this in Foobar.java
:
public class Foobar{
public int getfifteen(){
return 15;
}
}
Put this in FoobarTest.java
:
import static org.junit.Assert.*;
import junit.framework.JUnit4TestAdapter;
import org.junit.Test;
public class FoobarTest {
@Test
public void mytest() {
Foobar f = new Foobar();
assert(15==f.getfifteen());
}
public static junit.framework.Test suite(){
return new JUnit4TestAdapter(FoobarTest.class);
}
}
Download junit4-4.8.2.jar
I used the one from here:
http://www.java2s.com/Code/Jar/j/Downloadjunit4jar.htm
Compile it:
javac -cp .:./libs/junit4-4.8.2.jar Foobar.java FoobarTest.java
Run it:
el@failbox /home/el $ java -cp .:./libs/* org.junit.runner.JUnitCore FoobarTest
JUnit version 4.8.2
.
Time: 0.009
OK (1 test)
One test passed.
I use this:
basename $(git remote get-url origin) .git
Which returns something like gitRepo
. (Remove the .git
at the end of the command to return something like gitRepo.git
.)
(Note: It requires Git version 2.7.0 or later)
This is an expansion on virgo47's answer (above).
It provides some static methods to get the current and invoking class / method names.
/* Utility class: Getting the name of the current executing method
* https://stackoverflow.com/questions/442747/getting-the-name-of-the-current-executing-method
*
* Provides:
*
* getCurrentClassName()
* getCurrentMethodName()
* getCurrentFileName()
*
* getInvokingClassName()
* getInvokingMethodName()
* getInvokingFileName()
*
* Nb. Using StackTrace's to get this info is expensive. There are more optimised ways to obtain
* method names. See other stackoverflow posts eg. https://stackoverflow.com/questions/421280/in-java-how-do-i-find-the-caller-of-a-method-using-stacktrace-or-reflection/2924426#2924426
*
* 29/09/2012 (lem) - added methods to return (1) fully qualified names and (2) invoking class/method names
*/
package com.stackoverflow.util;
public class StackTraceInfo
{
/* (Lifted from virgo47's stackoverflow answer) */
private static final int CLIENT_CODE_STACK_INDEX;
static {
// Finds out the index of "this code" in the returned stack trace - funny but it differs in JDK 1.5 and 1.6
int i = 0;
for (StackTraceElement ste: Thread.currentThread().getStackTrace())
{
i++;
if (ste.getClassName().equals(StackTraceInfo.class.getName()))
{
break;
}
}
CLIENT_CODE_STACK_INDEX = i;
}
public static String getCurrentMethodName()
{
return getCurrentMethodName(1); // making additional overloaded method call requires +1 offset
}
private static String getCurrentMethodName(int offset)
{
return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX + offset].getMethodName();
}
public static String getCurrentClassName()
{
return getCurrentClassName(1); // making additional overloaded method call requires +1 offset
}
private static String getCurrentClassName(int offset)
{
return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX + offset].getClassName();
}
public static String getCurrentFileName()
{
return getCurrentFileName(1); // making additional overloaded method call requires +1 offset
}
private static String getCurrentFileName(int offset)
{
String filename = Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX + offset].getFileName();
int lineNumber = Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX + offset].getLineNumber();
return filename + ":" + lineNumber;
}
public static String getInvokingMethodName()
{
return getInvokingMethodName(2);
}
private static String getInvokingMethodName(int offset)
{
return getCurrentMethodName(offset + 1); // re-uses getCurrentMethodName() with desired index
}
public static String getInvokingClassName()
{
return getInvokingClassName(2);
}
private static String getInvokingClassName(int offset)
{
return getCurrentClassName(offset + 1); // re-uses getCurrentClassName() with desired index
}
public static String getInvokingFileName()
{
return getInvokingFileName(2);
}
private static String getInvokingFileName(int offset)
{
return getCurrentFileName(offset + 1); // re-uses getCurrentFileName() with desired index
}
public static String getCurrentMethodNameFqn()
{
return getCurrentMethodNameFqn(1);
}
private static String getCurrentMethodNameFqn(int offset)
{
String currentClassName = getCurrentClassName(offset + 1);
String currentMethodName = getCurrentMethodName(offset + 1);
return currentClassName + "." + currentMethodName ;
}
public static String getCurrentFileNameFqn()
{
String CurrentMethodNameFqn = getCurrentMethodNameFqn(1);
String currentFileName = getCurrentFileName(1);
return CurrentMethodNameFqn + "(" + currentFileName + ")";
}
public static String getInvokingMethodNameFqn()
{
return getInvokingMethodNameFqn(2);
}
private static String getInvokingMethodNameFqn(int offset)
{
String invokingClassName = getInvokingClassName(offset + 1);
String invokingMethodName = getInvokingMethodName(offset + 1);
return invokingClassName + "." + invokingMethodName;
}
public static String getInvokingFileNameFqn()
{
String invokingMethodNameFqn = getInvokingMethodNameFqn(2);
String invokingFileName = getInvokingFileName(2);
return invokingMethodNameFqn + "(" + invokingFileName + ")";
}
}
There is another way of doing this with just JavaScript. All you have to do is toggle the visibility based on the current state of the DIV's visibility in CSS.
Example:
function toggleVideo() {
var e = document.getElementById('video-over');
if(e.style.visibility == 'visible') {
e.style.visibility = 'hidden';
} else if(e.style.visibility == 'hidden') {
e.style.visibility = 'visible';
}
}
Here is another option, slight modification to another answer in above/below:
Reflections reflections = new Reflections("com.example.project.package",
new SubTypesScanner(false));
Set<Class<? extends Object>> allClasses =
reflections.getSubTypesOf(Object.class);
document.getElementById("my").className = 'myclass';
I have tried with this below Steps and its working fine:-
Download latest version for nodejs, it should work
If you need to do that on multiple sheets, and multiple columns in each sheet, here is how you can iterate through all of them:
// Auto size columns for each worksheet
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$objPHPExcel->setActiveSheetIndex($objPHPExcel->getIndex($worksheet));
$sheet = $objPHPExcel->getActiveSheet();
$cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
/** @var PHPExcel_Cell $cell */
foreach ($cellIterator as $cell) {
$sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
}
}
A lesser perplexing way to look at it would be:
string = 'happy'
print(string)
'happy'
string_reversed = string[-1::-1]
print(string_reversed)
'yppah'
In English [-1::-1] reads as:
"Starting at -1, go all the way, taking steps of -1"
Volatile boolean vs AtomicBoolean
The Atomic* classes wrap a volatile primitive of the same type. From the source:
public class AtomicLong extends Number implements java.io.Serializable {
...
private volatile long value;
...
public final long get() {
return value;
}
...
public final void set(long newValue) {
value = newValue;
}
So if all you are doing is getting and setting a Atomic* then you might as well just have a volatile field instead.
What does AtomicBoolean do that a volatile boolean cannot achieve?
Atomic* classes give you methods that provide more advanced functionality such as incrementAndGet()
for numbers, compareAndSet()
for booleans, and other methods that implement multiple operations (get/increment/set, test/set) without locking. That's why the Atomic* classes are so powerful.
For example, if multiple threads are using the following code using ++
, there will be race conditions because ++
is actually: get, increment, and set.
private volatile value;
...
// race conditions here
value++;
However, the following code will work in a multi-threaded environment safely without locks:
private final AtomicLong value = new AtomicLong();
...
value.incrementAndGet();
It's also important to note that wrapping your volatile field using Atomic* class is a good way to encapsulate the critical shared resource from an object standpoint. This means that developers can't just deal with the field assuming it is not shared possibly injecting problems with a field++; or other code that introducing race conditions.
select max(Salary) from Employee
where Salary
not in (Select Max(Salary) from Employee)
Try to disable the engine
option in your .htaccess file:
php_flag engine off
From within a terminal, try
sudo update-alternatives --config x-terminal-emulator
Select the desired terminal from the list of alternatives.
A better and more generic solution IMO:
<!-- Insert this line above script imports -->
<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>
<!-- normal script imports etc -->
<script src="scripts/jquery.min.js"></script>
<script src="scripts/vendor.js"></script>
<!-- Insert this line after script imports -->
<script>if (window.module) module = window.module;</script>
Benefits
node-integration
to be falsesource here
(Using as an example your first link)
You want to duplicate the behavior of an old HP calculator, there are two options:
You write new program that draws the calculator's display and keys, and when the user clicks on the keys, your programs does what the old calculator did. This is a Simulator
You get a dump of the calculator's firmware, then write a program that loads the firmware and interprets it the same way the microprocessor in the calculator did. This is an Emulator
The Simulator tries to duplicate the behavior of the device.
The Emulator tries to duplicate the inner workings of the device.
you can create selector file in res/drawable
example: res/drawable/selector_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_disabled" android:state_enabled="false" />
<item android:drawable="@drawable/btn_enabled" />
</selector>
and in layout activity, fragment or etc
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/selector_bg_rectangle_black"/>
This is not actually a problem with the function being "void", but a problem with the function parameters. I think it's just g++ giving an unhelpful error message.
EDIT: As in the accepted answer, the fix is to use std::string
instead of just string
.
My OS is Ubuntu. I solved this problem by using:
sudo apt-get install php5-mysql
I have used Dropbox as my Prive or protected svn. Try the link below. http://foyzulkarim.blogspot.com/2012/12/dropbox-as-svn-repository.html
sizeWithFont:
is now deprecated, use sizeWithAttributes:
instead:
UIFont *font = [UIFont fontWithName:@"Helvetica" size:30];
NSDictionary *userAttributes = @{NSFontAttributeName: font,
NSForegroundColorAttributeName: [UIColor blackColor]};
NSString *text = @"hello";
...
const CGSize textSize = [text sizeWithAttributes: userAttributes];
I make this method and work fine. (tested in android 6.0.1)
public void notifyThis(String title, String message) {
NotificationCompat.Builder b = new NotificationCompat.Builder(this.context);
b.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.favicon32)
.setTicker("{your tiny message}")
.setContentTitle(title)
.setContentText(message)
.setContentInfo("INFO");
NotificationManager nm = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1, b.build());
}
PikePDF can do this with very little code:
from pikepdf import Pdf, PdfImage
filename = "sample-in.pdf"
example = Pdf.open(filename)
for i, page in enumerate(example.pages):
for j, (name, raw_image) in enumerate(page.images.items()):
image = PdfImage(raw_image)
out = image.extract_to(fileprefix=f"{filename}-page{i:03}-img{j:03}")
extract_to
will automatically pick the file extension based on how the image
is encoded in the PDF.
If you want, you could also print some detail about the images as they get extracted:
# Optional: print info about image
w = raw_image.stream_dict.Width
h = raw_image.stream_dict.Height
f = raw_image.stream_dict.Filter
size = raw_image.stream_dict.Length
print(f"Wrote {name} {w}x{h} {f} {size:,}B {image.colorspace} to {out}")
which can print something like
Wrote /Im1 150x150 /DCTDecode 5,952B /ICCBased to sample2.pdf-page000-img000.jpg
Wrote /Im10 32x32 /FlateDecode 36B /ICCBased to sample2.pdf-page000-img001.png
...
See the docs for more that you can do with images, including replacing them in the PDF file.
For those looking for a complete example check out http://www.exchangecore.com/blog/how-use-ldap-active-directory-authentication-php/.
I have tested this connecting to both Windows Server 2003 and Windows Server 2008 R2 domain controllers from a Windows Server 2003 Web Server (IIS6) and from a windows server 2012 enterprise running IIS 8.
There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.
One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.
Random r = new Random();
List<string> list = new List(originalArray);
List<string> randomStrings = new List();
while(list.Count > 0)
{
int i = r.Random(list.Count);
randomStrings.Add(list[i]);
list.RemoveAt(i);
}
Assuming you actually mean timestamp
because there is no datetime
in Postgres
Cast the timestamp column to a date, that will remove the time part:
select *
from the_table
where the_timestamp_column::date = date '2015-07-15';
This will return all rows from July, 15th.
Note that the above will not use an index on the_timestamp_column
. If performance is critical, you need to either create an index on that expression or use a range condition:
select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
and the_timestamp_column < timestamp '2015-07-16 00:00:00';
Just wanted to show you a way to save all your Bundle after onConfigurationChanged:
Create new Bundle just after your class:
public class MainActivity extends Activity {
Bundle newBundy = new Bundle();
Next, after "protected void onCreate" add this:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
onSaveInstanceState(newBundy);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
onSaveInstanceState(newBundy);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBundle("newBundy", newBundy);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getBundle("newBundy");
}
If you add this all your crated classes into MainActivity will be saved.
But the best way is to add this in your AndroidManifest:
<activity name= ".MainActivity" android:configChanges="orientation|screenSize"/>
import datetime
now = datetime.datetime.now()
print(now.year)
The above code works perfectly fine for me.
I got this error too but for a different reason. It turns out I had made a typo when I tried to specify the version number as a variable:
dependencies {
// ...
implementation "com.google.android.gms:play-services-location:{$playServices}"
// ...
}
I had defined the variable playServices in gradle.properties in my project's root directory:
playServices=15.0.1
The typo was {$playServices}
which should have said ${playServices}
like this:
dependencies {
// ...
implementation "com.google.android.gms:play-services-location:${playServices}"
// ...
}
That fixed the problem for me.
The portable way to do this (ensuring that you get 0x00 0x00 0x00 0xaf
everywhere) is to use shifts:
unsigned char bytes[4];
unsigned long n = 175;
bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;
The methods using unions and memcpy()
will get a different result on different machines.
The issue you are having is with the printing rather than the conversion. I presume you are using char
rather than unsigned char
, and you are using a line like this to print it:
printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);
When any types narrower than int
are passed to printf
, they are promoted to int
(or unsigned int
, if int
cannot hold all the values of the original type). If char
is signed on your platform, then 0xff
likely does not fit into the range of that type, and it is being set to -1 instead (which has the representation 0xff
on a 2s-complement machine).
-1 is promoted to an int
, and has the representation 0xffffffff
as an int
on your machine, and that is what you see.
Your solution is to either actually use unsigned char
, or else cast to unsigned char
in the printf
statement:
printf("%x %x %x %x\n", (unsigned char)bytes[0],
(unsigned char)bytes[1],
(unsigned char)bytes[2],
(unsigned char)bytes[3]);
Add this to your ajax call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Just be sure what timezone you want to use.
datetime="06/12/2012 07:21:22"
Most popular use takes machine timezone.
date -d "$datetime" +"%s" #depends on local timezone, my output = "1339456882"
But in case you intentionally want to pass UTC datetime and you want proper timezone you need to add -u
flag. Otherwise you convert it from your local timezone.
date -u -d "$datetime" +"%s" #general output = "1339485682"
Add to model:
using System.Web.Mvc;
And to your property
[AllowHtml]
[Display(Name = "Body")]
public String Body { get; set; }
This code from my point the best way avoid this error. If you are using HTML editor you will not have security issues because it already restricted.
Just as an FYI, in Rails 2 you can do
ActiveRecord::Base.silence { <code you don't want to log goes here> }
Obviously the curly braces could be replaced with a do end
block if you wanted.
Most important difference is that second expression erases type of exception. And exception type plays vital role in catching exceptions:
public void MyMethod ()
{
// both can throw IOException
try { foo(); } catch { throw; }
try { bar(); } catch(E) {throw new Exception(E.message); }
}
(...)
try {
MyMethod ();
} catch (IOException ex) {
Console.WriteLine ("Error with I/O"); // [1]
} catch (Exception ex) {
Console.WriteLine ("Other error"); // [2]
}
If foo()
throws IOException
, [1]
catch block will catch exception. But when bar()
throws IOException
, it will be converted to plain Exception
ant won't be caught by [1]
catch block.
You could also execute tree > tree.txt
in both folders and then diff both tree.txt files with any file based diff tool (git diff).
Using a more functional approach, you can implement the match with a one-liner using an array function:
ECMAScript 6:
const regexList = [/apple/, /pear/];
const text = "banana pear";
const isMatch = regexList.some(rx => rx.test(text));
ECMAScript 5:
var regexList = [/apple/, /pear/];
var text = "banana pear";
var isMatch = regexList.some(function(rx) { return rx.test(text); });
You can use python -m http.server
. By default the local server will run on port 8000. If you would like to change this, simply add the port number python -m http.server 1234
If you are using python 2 (instead of 3), the equivalent command is python -m SimpleHTTPServer
you can try chsh -s /bin/bash
to set the bash as the default,
or chsh -s /bin/zsh
to set the zsh as the default.
Terminal will need a restart to take effect.
Yes you can (this is how I understand the original question). Here is how I did it. Just tie it into outside context. For example:
//javascript
my_function = null;
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
my_function = my_fun;
})
//just js
function js_fun () {
my_function(); //== call jquery function - just Reference is globally defined not function itself
}
I encountered this same problem when trying to access methods of the object, that was instantiated on DOM object ready only. Works. My example:
MyControl.prototype = {
init: function {
// init something
}
update: function () {
// something useful, like updating the list items of control or etc.
}
}
MyCtrl = null;
// create jquery plug-in
$.fn.aControl = function () {
var control = new MyControl(this);
control.init();
MyCtrl = control; // here is the trick
return control;
}
now you can use something simple like:
function() = {
MyCtrl.update(); // yes!
}
If you're just trying to replace one property, lodash _.find
and _.set
should be enough:
var arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];
_.set(_.find(arr, {id: 1}), 'name', 'New Person');
from sklearn import metrics
import numpy as np
print(np.sqrt(metrics.mean_squared_error(y_test,y_predict)))
It ignores the cached content when refreshing...
https://support.google.com/a/answer/3001912?hl=en
F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content
Hi please find the answer
const express = require('express');
const app = express();
const port = 8080;
app.get('/', (req, res) => res.send('Hello home!'));
app.get('/about-us', (req, res) => res.send('Hello about us!'));
app.post('/user/set-profile', (req, res) => res.send('Hello profile!'));
//last 404 page
app.get('*', (req, res) => res.send('Page Not found 404'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
OSX GUYS, OVER HERE!!!
As @charlax answered (for me the best one), you can use a more dynamic command to set PATH, buuut for mac users this could not work, sometimes your USER_BASE path got from site is wrong, so you need to find out where your python installation is.
$ which python3
/usr/local/bin/python3.6
you'll get a symlink, then you need to find the source's symlink.
$ ls -la /usr/local/bin/python3.6
lrwxr-xr-x 1 root wheel 71 Mar 14 17:56 /usr/local/bin/python3.6 -> ../../../Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
(this ../../../
means root)
So you found the python path (/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
), then you just need to put in you ~/.bashrc as follows:
export PATH="$PATH:/Library/Frameworks/Python.framework/Versions/3.6/bin"
You can send an HTTP request to http://finance.yahoo.com requesting symbols, names, quotes, and all sorts of other data. Data is returned as a .CSV so you can request multiple symbols in one query.
So if you send:
http://finance.yahoo.com/d/quotes.csv?s=MSFT+F+ATT&f=sn
You'll get back something like:
"MSFT","Microsoft Corp"
"F","FORD MOTOR CO"
"ATT","AT&T"
Here is an article called Downloading Yahoo Data which includes the various tags used to request the data.
label
is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center
but since the label is only as wide as the text you don't notice.
The best thing to do is to apply a specific width to the label
that is greater than the width of the content - this will give you the results you want.
This is the most native and scalable approach I could find:
>>> myindex = pd.Series(myseries.index, index=myseries)
>>> myindex[7]
3
>>> myindex[[7, 5, 7]]
7 3
5 4
7 3
dtype: int64
The first one adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.
The second replaces the current history item so you can't go back to it.
See window.location
:
assign(url)
: Load the document at the provided URL.
replace(url)
: Replace the current document with the one at the provided URL. The difference from the assign()
method is that after using replace()
the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.
window.location.href = url;
is favoured over:
window.location = url;
In HTML:
<form id="my_form"><input id="my_field" type="date" /></form>
In JavaScript
// test and transform if needed_x000D_
if($('#my_field').attr('type') === 'text'){_x000D_
$('#my_field').attr('type', 'text').attr('placeholder','aaaa-mm-dd'); _x000D_
};_x000D_
_x000D_
// check_x000D_
if($('#my_form')[0].elements[0].value.search(/(19[0-9][0-9]|20[0-1][0-5])[- \-.](0[1-9]|1[012])[- \-.](0[1-9]|[12][0-9]|3[01])$/i) === 0){_x000D_
$('#my_field').removeClass('bad');_x000D_
} else {_x000D_
$('#my_field').addClass('bad');_x000D_
};
_x000D_
Adding the below function in bashrc lets you run the command without any arguments which displays the current directory structure and when run with any path as argument, will display the directory structure of that path. This avoids the need to switch to a particular directory before running the command.
function tree() {
find ${1:-.} | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"
}
This works in gitbash too.
Source: Comment from @javasheriff here
As I didn't want to break anything, I did this to be able to use newer versions of Python3 than Python v3.4 :
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.6 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in auto mode
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.7 2
update-alternatives: using /usr/bin/python3.7 to provide /usr/local/bin/python3 (python3) in auto mode
$ update-alternatives --list python3
/usr/bin/python3.6
/usr/bin/python3.7
$ sudo update-alternatives --config python3
There are 2 choices for the alternative python3 (providing /usr/local/bin/python3).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/python3.7 2 auto mode
1 /usr/bin/python3.6 1 manual mode
2 /usr/bin/python3.7 2 manual mode
Press enter to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in manual mode
$ ls -l /usr/local/bin/python3 /etc/alternatives/python3
lrwxrwxrwx 1 root root 18 2019-05-03 02:59:03 /etc/alternatives/python3 -> /usr/bin/python3.6*
lrwxrwxrwx 1 root root 25 2019-05-03 02:58:53 /usr/local/bin/python3 -> /etc/alternatives/python3*
The code you posted tries to save an array of custom objects to NSUserDefaults
. You can't do that. Implementing the NSCoding
methods doesn't help. You can only store things like NSArray
, NSDictionary
, NSString
, NSData
, NSNumber
, and NSDate
in NSUserDefaults
.
You need to convert the object to NSData
(like you have in some of the code) and store that NSData
in NSUserDefaults
. You can even store an NSArray
of NSData
if you need to.
When you read back the array you need to unarchive the NSData
to get back your BC_Person
objects.
Perhaps you want this:
- (void)savePersonArrayData:(BC_Person *)personObject {
[mutableDataArray addObject:personObject];
NSMutableArray *archiveArray = [NSMutableArray arrayWithCapacity:mutableDataArray.count];
for (BC_Person *personObject in mutableDataArray) {
NSData *personEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:personObject];
[archiveArray addObject:personEncodedObject];
}
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
[userData setObject:archiveArray forKey:@"personDataArray"];
}
Along with the rest of the answers, I don't think eval statements can have advanced minimization.
http://martinfowler.com/articles/microservice-testing/
Martin Fowler's blog post speaks about strategies to test code (Especially in a micro-services architecture) but most of it applies to any application.
I'll quote from his summary slide:
- Unit tests - exercise the smallest pieces of testable software in the application to determine whether they behave as expected.
- Integration tests - verify the communication paths and interactions between components to detect interface defects.
- Component tests - limit the scope of the exercised software to a portion of the system under test, manipulating the system through internal code interfaces and using test doubles to isolate the code under test from other components.
- Contract tests - verify interactions at the boundary of an external service asserting that it meets the contract expected by a consuming service.
- End-To-End tests - verify that a system meets external requirements and achieves its goals, testing the entire system, from end to end.
As Paolo said, we have 2 invocation methods:
1) python -m tests.core_test
2) python tests/core_test.py
One difference between them is sys.path[0] string. Since the interpret will search sys.path when doing import, we can do with tests/core_test.py
:
if __name__ == '__main__':
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from components import core
<other stuff>
And more after this, we can run core_test.py with other methods:
cd tests
python core_test.py
python -m core_test
...
Note, py36 tested only.