To convert any JSON to array, use the below code:
const usersJson: any[] = Array.of(res.json());
bundle install --path vendor/cache
generally fixes it as that is the more common problem. Basically, your bundler path configuration is messed up. See their documentation (first paragraph) for where to find those configurations and change them manually if needed.
If are using some auth function of firebase, you can take token using this:
//------GET USER TOKEN-------
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
mUser.getToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(@NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
String idToken = task.getResult().getToken();
// ...
}
}
});
Work well if user are logged. getCurrentUser()
In case, you want to rename _id in same collection (for instance, if you want to prefix some _ids):
db.someCollection.find().snapshot().forEach(function(doc) {
if (doc._id.indexOf("2019:") != 0) {
print("Processing: " + doc._id);
var oldDocId = doc._id;
doc._id = "2019:" + doc._id;
db.someCollection.insert(doc);
db.someCollection.remove({_id: oldDocId});
}
});
if (doc._id.indexOf("2019:") != 0) {... needed to prevent infinite loop, since forEach picks the inserted docs, even throught .snapshot() method used.
Predicate<Client> hasSameNameAsOneUser =
c -> users.stream().anyMatch(u -> u.getName().equals(c.getName()));
return clients.stream()
.filter(hasSameNameAsOneUser)
.collect(Collectors.toList());
But this is quite inefficient, because it's O(m * n). You'd better create a Set of acceptable names:
Set<String> acceptableNames =
users.stream()
.map(User::getName)
.collect(Collectors.toSet());
return clients.stream()
.filter(c -> acceptableNames.contains(c.getName()))
.collect(Collectors.toList());
Also note that it's not strictly equivalent to the code you have (if it compiled), which adds the same client twice to the list if several users have the same name as the client.
select t1.user_id,t2.user_id
from t1 left join t2 ON t1.user_id = t2.user_id
and t1.username=t2.username
and t1.first_name=t2.first_name
and t1.last_name=t2.last_name
try this. This will compare your table and find all matching pairs, if any mismatch return NULL on left.
I don't know what you mean by 'manually'. You can choose a colourmap and make a colour array easily enough:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]
colors = cm.rainbow(np.linspace(0, 1, len(ys)))
for y, c in zip(ys, colors):
plt.scatter(x, y, color=c)
Or you can make your own colour cycler using itertools.cycle
and specifying the colours you want to loop over, using next
to get the one you want. For example, with 3 colours:
import itertools
colors = itertools.cycle(["r", "b", "g"])
for y in ys:
plt.scatter(x, y, color=next(colors))
Come to think of it, maybe it's cleaner not to use zip
with the first one neither:
colors = iter(cm.rainbow(np.linspace(0, 1, len(ys))))
for y in ys:
plt.scatter(x, y, color=next(colors))
import subprocess
filepath="D:/path/to/batch/myBatch.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()
print p.returncode # is 0 if success
In ASP.NET 2.1, In StartUp.cs Add This Services:
services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
and then do 3 step:
Define a variable in your MVC controller
private IHttpContextAccessor _accessor;
DI into the controller's constructor
public SomeController(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
Retrieve the IP Address
_accessor.HttpContext.Connection.RemoteIpAddress.ToString()
This is how it is done.
The difference between Control.Invoke()
and Control.BeginInvoke()
is,
BeginInvoke()
will schedule the asynchronous action on the GUI thread. When the asynchronous action is scheduled, your code continues. Some time later (you don't know exactly when) your asynchronous action will be executedInvoke()
will execute your asynchronous action (on the GUI thread) and wait until your action has completed.A logical conclusion is that a delegate you pass to Invoke()
can have out-parameters or a return-value, while a delegate you pass to BeginInvoke()
cannot (you have to use EndInvoke to retrieve the results).
You can return multiple arrays and scalars from a function
function x()
{
$a=array("a","b","c");
$b=array("e","f");
return array('x',$a,$b);
}
list ($m,$n,$o)=x();
echo $m."\n";
print_r($n);
print_r($o);
If you're streaming a file that you're generating dynamically, and also have a realtime server-to-client messaging library implemented, you can alert your client pretty easily.
The server-to-client messaging library I like and recommend is Socket.io (via Node.js). After your server script is done generating the file that is being streamed for download your last line in that script can emit a message to Socket.io which sends a notification to the client. On the client, Socket.io listens for incoming messages emitted from the server and allows you to act on them. The benefit of using this method over others is that you are able to detect a "true" finish event after the streaming is done.
For example, you could show your busy indicator after a download link is clicked, stream your file, emit a message to Socket.io from the server in the last line of your streaming script, listen on the client for a notification, receive the notification and update your UI by hiding the busy indicator.
I realize most people reading answers to this question might not have this type of a setup, but I've used this exact solution to great effect in my own projects and it works wonderfully.
Socket.io is incredibly easy to install and use. See more: http://socket.io/
From Chromium's style guide:
Don't use else after return:
# Bad
if (foo)
return 1
else
return 2
# Good
if (foo)
return 1
return 2
return 1 if foo else 2
You only need to force cscript instead wscript. I always use this template. The function ForceConsole() will execute your vbs into cscript, also you have nice alias to print and scan text.
Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"
Call ForceConsole()
Function printf(txt)
WScript.StdOut.WriteLine txt
End Function
Function printl(txt)
WScript.StdOut.Write txt
End Function
Function scanf()
scanf = LCase(WScript.StdIn.ReadLine)
End Function
Function wait(n)
WScript.Sleep Int(n * 1000)
End Function
Function ForceConsole()
If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
WScript.Quit
End If
End Function
Function cls()
For i = 1 To 50
printf ""
Next
End Function
printf " _____ _ _ _____ _ _____ _ _ "
printf "| _ |_| |_ ___ ___| |_ _ _ _| | | __|___ ___|_|___| |_ "
printf "| | | '_| . | | --| | | | . | |__ | _| _| | . | _|"
printf "|__|__|_|_,_|___|_|_|_____|_____|___| |_____|___|_| |_| _|_| "
printf " |_| v1.0"
printl " Enter your name:"
MyVar = scanf
cls
printf "Your name is: " & MyVar
wait(5)
Python 3
from urllib.error import HTTPError
Python 2
from urllib2 import HTTPError
Just catch HTTPError
, handle it, and if it's not Error 404, simply use raise
to re-raise the exception.
See the Python tutorial.
e.g. complete example for Pyhton 2
import urllib2
from urllib2 import HTTPError
try:
urllib2.urlopen("some url")
except HTTPError as err:
if err.code == 404:
<whatever>
else:
raise
You should add the g
modifier so that sed performs a global substitution of the contents of the pattern buffer:
echo dog dog dos | sed -e 's:dog:log:g'
For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6
The official documentation for GNU sed
is available at http://www.gnu.org/software/sed/manual/
return n
from your main entry function will terminate your process and report to the parent process (the one that executed your process) the result of your process. 0 means SUCCESS. Other codes usually indicates a failure and its meaning.
If you are in the fragment itself, you need to call this. Your fragment needs to be the fragment that is being called. Enter code:
getFragmentManager().beginTransaction().remove(yourFragment).commitAllowingStateLoss();
or if you are using supportLib
, then you need to call:
getSupportFragmentManager().beginTransaction().remove(yourFragment).commitAllowingStateLoss();
If you are using a recent Cygwin (e.g. 1.7), you can also start both your .bashrc
and .bash_profile
with the following line, on the first non commented line:
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
(set -o igncr) 2>/dev/null && set -o igncr; # this comment is needed
This will force bash to ignore carriage return (\r
) characters used in Windows line separators.
See http://cygwin.com/ml/cygwin-announce/2010-08/msg00015.html.
This is useful when you want to compare data that correspond to different units. In that case, you want to remove the units. To do that in a consistent way of all the data, you transform the data in a way that the variance is unitary and that the mean of the series is 0.
You can try this
Process[] processes = Process.GetProcessesByName("processname");
foreach (Process p in processes)
{
IntPtr pFoundWindow = p.MainWindowHandle;
// Do something with the handle...
//
}
some sources prefere to use .env.development
and .env.production
but that's not obligatory.
it seems that if your environment variable does not start like that so you will have problems
to include your environment variable just put on your code process.env.REACT_APP_VARIABLE
You don't have to install any external dependency
select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
from (select id, name, author_id, count(1) as count_1
from names
group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
from names) n2
on (n2.author_id = n1.author_id)
Where true
used distinct
if more inner join, because more join group performance is slow
Using AspNetCore 2.x, you have to go a little different way:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AuthorizeRoleAttribute : AuthorizeAttribute
{
public AuthorizeRoleAttribute(params YourEnum[] roles)
{
Policy = string.Join(",", roles.Select(r => r.GetDescription()));
}
}
just use it like this:
[Authorize(YourEnum.Role1, YourEnum.Role2)]
If anyone has the same problem, one possible solution is to set the bindto
stream context configuration parameter (assuming you're connecting from 11.22.33.44 to 55.66.77.88):
$context = [
'socket' => [
'bindto' => '55.66.77.88'
]
];
$options = [
'soapVersion' => SOAP_1_1,
'stream_context' => stream_context_create($context)
];
$client = new Client('11.22.33.44', $options);
void main ()
{
int temp,integer,count=0,i,cnd=0;
char ascii[10]={0};
printf("enter a number");
scanf("%d",&integer);
if(integer>>31)
{
/*CONVERTING 2's complement value to normal value*/
integer=~integer+1;
for(temp=integer;temp!=0;temp/=10,count++);
ascii[0]=0x2D;
count++;
cnd=1;
}
else
for(temp=integer;temp!=0;temp/=10,count++);
for(i=count-1,temp=integer;i>=cnd;i--)
{
ascii[i]=(temp%10)+0x30;
temp/=10;
}
printf("\n count =%d ascii=%s ",count,ascii);
}
You can use Marvin (pure Java image processing framework) for this kind of operation: http://marvinproject.sourceforge.net
Scale plug-in: http://marvinproject.sourceforge.net/en/plugins/scale.html
Start by turning the text into a list of lists. That will take care of the parsing part:
lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))
The rest can be done with indexed lookups:
d = dict()
key = lol[6][0] # cell A7
value = lol[6][3] # cell D7
d[key] = value # add the entry to the dictionary
...
When we have to send multiple trigger parameters to jenkins job, the following commands works.
curl -X POST -i -u "auto_user":"xxxauthentication_tokenxxx" "JENKINS_URL/view/tests/job/helloworld/buildWithParameters?param1=162¶m2=store"
I was able to overcome this by using the "vh" metric with max-height on the .modal-body element. 70vh looked about right for my uses. Then set the overflow-y to auto so it only scrolls when needed.
.modal-body {
overflow-y: auto;
max-height: 70vh;
}
0 0 * * * [ $(($((
date +%-j- 1)) % 3)) == 0 ] && script
Get the day of the year from date
, offset by 1 to start at 0, check if it is modulo three.
This may seem like overkill, but if you want to avoid using the command module (which I do, because it using command is not idempotent) you can use a combination of copy and unarchive.
private Object actuallyT;
public <T> List<T> magicalListGetter(Class<T> klazz) {
List<T> list = new ArrayList<>();
list.add(klazz.cast(actuallyT));
try {
list.add(klazz.getConstructor().newInstance()); // If default constructor
} ...
return list;
}
One can give a generic type parameter to a method too. You have correctly deduced that one needs the correct class instance, to create things (klazz.getConstructor().newInstance()
).
If someone looking for calling a script with arguments
import subprocess
val = subprocess.check_call("./script.sh '%s'" % arg, shell=True)
Remember to convert the args to string before passing, using str(arg).
This can be used to pass as many arguments as desired:
subprocess.check_call("./script.ksh %s %s %s" % (arg1, str(arg2), arg3), shell=True)
This is a workaround (for me: I don't use awk very often):
Display the first row of the file containing the data, replace all pipes with newlines and then count the lines:
$ head -1 stores.dat | tr '|' '\n' | wc -l
I just found the answer from a forum referred by one of my colleague. If you declare a variable outside a function, it's always global. No matter if you use var keyword or not. But, if you declare the variable inside a function, it has a big difference. Inside a function, if you declare the variable using var keyword, it will be local, but if you declare the variable without var keyword, it will be global. It can overwrite your previously declared variables. - See more at: http://forum.webdeveloperszone.com/question/what-is-the-difference-between-using-var-keyword-or-not-using-var-during-variable-declaration/#sthash.xNnLrwc3.dpuf
This part has problems:
Card* cardArray;
void Deck() {
cardArray = new Card[NUM_TOTAL_CARDS];
int cardCount = 0;
for (int i = 0; i > NUM_SUITS; i++) { //Error
for (int j = 0; j > NUM_RANKS; j++) { //Error
cardArray[cardCount] = Card(Card::Rank(i), Card::Suit(j) );
cardCount++;
}
}
}
cardArray
is a dynamic array, but not a member of Card
class. It is strange if you would like to initialize a dynamic array which is not member of the classvoid Deck()
is not constructor of class Deck since you missed the
scope resolution operator. You may be confused with defining the constructor and the function with name Deck
and return type void
.<
not >
otherwise, loop will never
be executed.There are two methods to get the mod time, os.path.getmtime() or os.stat(), but the ctime is not reliable cross-platform (see below).
getmtime(path)
Return the time of last modification of path. The return value is a number giving the
number of seconds since the epoch (see the time module). Raise os.error if the file does
not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If
os.stat_float_times() returns True, the result is a floating point number.
stat(path)
Perform a stat() system call on the given path. The return value is an object whose
attributes correspond to the members of the stat structure, namely: st_mode (protection
bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid
(user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes),
st_atime (time of most recent access), st_mtime (time of most recent content
modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows):
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L
>>>
In the above example you would use statinfo.st_mtime or statinfo.st_ctime to get the mtime and ctime, respectively.
xrange returns an iterator and only keeps one number in memory at a time. range keeps the entire list of numbers in memory.
I don't want to have to enable a reference library as I need my scripts to be portable. The Dim foo As New VBScript_RegExp_55.RegExp
line caused User Defined Type Not Defined
errors, but I found a solution that worked for me.
Update RE comments w/ @chrisneilsen :
I was under the impression that enabling a reference library was tied to the local computers settings, but it is in fact, tied directly to the workbook. So, you can enable a reference library, share a macro enabled workbook and the end user wouldn't have to enable the library as well. Caveat: The advantage to Late Binding is that the developer does not have to worry about the wrong version of an object library being installed on the user's computer. This likely would not be an issue w/ the VBScript_RegExp_55.RegExp
library, but I'm not sold that the "performance" benifit is worth it for me at this time, as we are talking imperceptible milliseconds in my code. I felt this deserved an update to help others understand. If you enable the reference library, you can use "early bind", but if you don't, as far as I can tell, the code will work fine, but you need to "late bind" and loose on some performance/debugging features.
Source: https://peltiertech.com/Excel/EarlyLateBinding.html
What you'll want to do is put an example string in cell A1
, then test your strPattern
. Once that's working adjust then rng
as desired.
Public Sub RegExSearch()
'https://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops
'https://wellsr.com/vba/2018/excel/vba-regex-regular-expressions-guide/
'https://www.vitoshacademy.com/vba-regex-in-excel/
Dim regexp As Object
'Dim regex As New VBScript_RegExp_55.regexp 'Caused "User Defined Type Not Defined" Error
Dim rng As Range, rcell As Range
Dim strInput As String, strPattern As String
Set regexp = CreateObject("vbscript.regexp")
Set rng = ActiveSheet.Range("A1:A1")
strPattern = "([a-z]{2})([0-9]{8})"
'Search for 2 Letters then 8 Digits Eg: XY12345678 = Matched
With regexp
.Global = False
.MultiLine = False
.ignoreCase = True
.Pattern = strPattern
End With
For Each rcell In rng.Cells
If strPattern <> "" Then
strInput = rcell.Value
If regexp.test(strInput) Then
MsgBox rcell & " Matched in Cell " & rcell.Address
Else
MsgBox "No Matches!"
End If
End If
Next
End Sub
Incidentally, .ogv files are video, so "video/ogg", .ogg files are Vorbis audio, so "audio/ogg" and .oga files are general Ogg audio, so also "audio/ogg". Checked in Firefox and work. "application/ogg" is deprecated for all audio or video uses. See http://www.rfc-editor.org/rfc/rfc5334.txt
include math.h and compile with gcc test.c -lm
There are four different ways to create objects in java:
A. Using new
keyword
This is the most common way to create an object in java. Almost 99% of objects are created in this way.
MyObject object = new MyObject();
B. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
C. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();
D. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
You can read them from here.
You can use the Microsoft.VisualBasic namespace to find this helper function:
Replace(sourceString, "replacethis", "withthis", , , CompareMethod.Text)
Just changed Amber's COUNT(*) to COUNT(1) for the better performance.
SELECT name, COUNT(1) as count
FROM tablename
GROUP BY name
ORDER BY count DESC;
I was getting this error : javax.faces.application.ViewExpiredException.When I using different requests, I found those having same JsessionId, even after restarting the server. So this is due to the browser cache. Just close the browser and try, it will work.
An established connection was aborted by the software in your host machine
That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.
The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.
You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.
You can also do this with linq if you'd like
var names = new List<string>() { "John", "Anna", "Monica" };
var joinedNames = names.Aggregate((a, b) => a + ", " + b);
Although I prefer the non-linq syntax in Quartermeister's answer and I think Aggregate
might perform slower (probably more string concatenation operations).
Depending on the type of data you're dealing with, you could also just get the value counts of each column while performing your EDA by setting dropna to False.
for col in df:
print df[col].value_counts(dropna=False)
Works well for categorical variables, not so much when you have many unique values.
I think that depth first search solves it. If an unexplored edge leads to a node visited before, then the graph contains a cycle. This condition also makes it O(n), since you can explore maximum n edges without setting it to true or being left with no unexplored edges.
shape()
consists of array having two arguments rows and columns.
if you search shape[0]
then it will gave you the number of rows.
shape[1]
will gave you number of columns.
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
How about with a :before
pseudoelement:
a:before {
content: '\a';
white-space: pre;
}
Why not try adding Scope? Scope is a very good feature of Eloquent.
class User extends Eloquent {
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
public function scopeWomen($query)
{
return $query->whereGender('W');
}
}
$users = User::popular()->women()->orderBy('created_at')->get();
The correct solution to get the Prompt
value in a non-templated control context is:
@Html.TextBoxFor(model => model.Email,
new { placeholder = ModelMetadata.FromLambdaExpression(m => m.Email, ViewData).Watermark }
)
This will also not double-escape the watermark text.
I am using d3.js for parsing csv file. Very easy to use. Here is the docs.
Steps:
Using Es6;
import { csv } from 'd3-request';
import url from 'path/to/data.csv';
csv(url, function(err, data) {
console.log(data);
})
Please see docs for more.
Update - d3-request is deprecated. you can use d3-fetch
raw_input()
was renamed to input()
in Python 3.
There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.
The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.
Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.
If you need to delete the records based on some other column as well, then here is a solution:
DELETE
FROM articles
WHERE id IN
(SELECT id
FROM
(SELECT id
FROM articles
WHERE user_id = :userId
ORDER BY created_at DESC LIMIT 500, 10000000) abc)
AND user_id = :userId
ALTER TABLE Regions
ADD ( HasPhotoInReadyStorage bit,
HasPhotoInWorkStorage bit,
HasPhotoInMaterialStorage bit *(Missing ,)*
HasText bit);
import threading
# global variable x
x = 0
def increment():
"""
function to increment global variable x
"""
global x
x += 1
def thread_task():
"""
task for thread
calls increment function 100000 times.
"""
for _ in range(100000):
increment()
def main_task():
global x
# setting global variable x as 0
x = 0
# creating threads
t1 = threading.Thread(target=thread_task)
t2 = threading.Thread(target=thread_task)
# start threads
t1.start()
t2.start()
# wait until threads finish their job
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(10):
main_task()
print("Iteration {0}: x = {1}".format(i,x))
#include<stdio.h>
#define n 3
struct body
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
};
struct body bodies[n];
int main()
{
int a, b;
for(a = 0; a < n; a++)
{
for(b = 0; b < 3; b++)
{
bodies[a].p[b] = 0;
bodies[a].v[b] = 0;
bodies[a].a[b] = 0;
}
bodies[a].mass = 0;
bodies[a].radius = 1.0;
}
return 0;
}
this works fine. your question was not very clear by the way, so match the layout of your source code with the above.
SELECT username, numb from(
Select username, count(username) as numb from customers GROUP BY username ) as my_table
WHERE numb > 3
Don't provide the handler to execute
.
Get the HttpResponse
object, use the handler to get the body and get the status code from it directly
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
final HttpGet httpGet = new HttpGet(GET_URL);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
System.out.println("Response body: " + responseBody);
}
}
For quick single calls, the fluent API is useful:
Response response = Request.Get(uri)
.connectTimeout(MILLIS_ONE_SECOND)
.socketTimeout(MILLIS_ONE_SECOND)
.execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();
For older versions of java or httpcomponents, the code might look different.
I don't like it either.
So use javascript:
Public Function GetJavaScriptResult(doc as HTMLDocument, jsString As String) As String
Dim el As IHTMLElement
Dim nd As HTMLDOMTextNode
Set el = doc.createElement("INPUT")
Do
el.ID = GenerateRandomAlphaString(100)
Loop Until Document.getElementById(el.ID) Is Nothing
el.Style.display = "none"
Set nd = Document.appendChild(el)
doc.parentWindow.ExecScript "document.getElementById('" & el.ID & "').value = " & jsString
GetJavaScriptResult = Document.getElementById(el.ID).Value
Document.removeChild nd
End Function
Function GenerateRandomAlphaString(Length As Long) As String
Dim i As Long
Dim Result As String
Randomize Timer
For i = 1 To Length
Result = Result & Chr(Int(Rnd(Timer) * 26 + 65 + Round(Rnd(Timer)) * 32))
Next i
GenerateRandomAlphaString = Result
End Function
Let me know if you have any problems with this; I've changed the context from a method to a function.
By the way, what version of IE are you using? I suspect you're on < IE8. If you upgrade to IE8 I presume it'll update shdocvw.dll to ieframe.dll and you will be able to use document.querySelector/All.
Edit
Comment response which isn't really a comment: Basically the way to do this in VBA is to traverse the child nodes. The problem is you don't get the correct return types. You could fix this by making your own classes that (separately) implement IHTMLElement and IHTMLElementCollection; but that's WAY too much of a pain for me to do it without getting paid :). If you're determined, go and read up on the Implements keyword for VB6/VBA.
Public Function getSubElementsByTagName(el As IHTMLElement, tagname As String) As Collection
Dim descendants As New Collection
Dim results As New Collection
Dim i As Long
getDescendants el, descendants
For i = 1 To descendants.Count
If descendants(i).tagname = tagname Then
results.Add descendants(i)
End If
Next i
getSubElementsByTagName = results
End Function
Public Function getDescendants(nd As IHTMLElement, ByRef descendants As Collection)
Dim i As Long
descendants.Add nd
For i = 1 To nd.Children.Length
getDescendants nd.Children.Item(i), descendants
Next i
End Function
Update
getString(R.string.some_string_id)
in both Activity
or Fragment
.Context.getString(R.string.some_string_id)
where you don't have direct access to getString()
method. Like Dialog
.Problem is where you don't have Context
access, like a method in your Util
class.
Assume below method without Context.
public void someMethod(){
...
// can't use getResource() or getString() without Context.
}
Now you will pass Context
as a parameter in this method and use getString().
public void someMethod(Context context){
...
context.getString(R.string.some_id);
}
What i do is
public void someMethod(){
...
App.getRes().getString(R.string.some_id)
}
What? It is very simple to use anywhere in your app!
So here is a Bonus unique solution by which you can access resources from anywhere like Util class
.
import android.app.Application;
import android.content.res.Resources;
public class App extends Application {
private static App mInstance;
private static Resources res;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
res = getResources();
}
public static App getInstance() {
return mInstance;
}
public static Resources getResourses() {
return res;
}
}
Add name field to your manifest.xml
<application
tag.
<application
android:name=".App"
...
>
...
</application>
Now you are good to go.
You can define this during datatable initialization
"aoColumns": [{"bVisible": false},null,null,null]
public static T Clone<T>(T obj)
{
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
T newObject = (T)dcSer.ReadObject(memoryStream);
return newObject;
}
If this helps, you can also use FileSystemObject to retrieve all subfolders of a folder. You need to check the reference "Microsot Scripting Runtime" to get Intellisense and use the "new" keyword.
Sub GetSubFolders()
Dim fso As New FileSystemObject
Dim f As Folder, sf As Folder
Set f = fso.GetFolder("D:\Proj\")
For Each sf In f.SubFolders
'Code inside
Next
End Sub
This is how to show custom layout dialog with custom list item, can be customised as per your requirement.
STEP - 1 Create the layout of the DialogBox ie:-
R.layout.assignment_dialog_list_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/rectangle_round_corner_assignment_alert"
android:orientation="vertical">
<TextView
android:id="@+id/tv_popup_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:singleLine="true"
android:paddingStart="4dp"
android:text="View as:"
android:textColor="#4f4f4f" />
<ListView
android:id="@+id/lv_assignment_users"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
STEP - 2 Create custom list item layout as per your business logic
R.layout.item_assignment_dialog_list_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="4dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv_user_profile_image"
android:visibility="visible"
android:layout_width="42dp"
android:layout_height="42dp" />
<TextView
android:id="@+id/tv_user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:layout_marginStart="8dp"
android:paddingBottom="8dp"
android:textColor="#666666"
android:textSize="18sp"
tools:text="ABCD XYZ" />
</LinearLayout>
STEP - 3 Create a Data model class of your own choice
public class AssignmentUserModel {
private String userId;
private String userName;
private String userRole;
private Bitmap userProfileBitmap;
public AssignmentUserModel(String userId, String userName, String userRole, Bitmap userProfileBitmap) {
this.userId = userId;
this.userName = userName;
this.userRole = userRole;
this.userProfileBitmap = userProfileBitmap;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
public Bitmap getUserProfileBitmap() {
return userProfileBitmap;
}
public void setUserProfileBitmap(Bitmap userProfileBitmap) {
this.userProfileBitmap = userProfileBitmap;
}
}
STEP - 4 Create custom adapter
public class UserListAdapter extends ArrayAdapter<AssignmentUserModel> {
private final Context context;
private final List<AssignmentUserModel> userList;
public UserListAdapter(@NonNull Context context, int resource, @NonNull List<AssignmentUserModel> objects) {
super(context, resource, objects);
userList = objects;
this.context = context;
}
@SuppressLint("ViewHolder")
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item_assignment_dialog_list_layout, parent, false);
ImageView profilePic = rowView.findViewById(R.id.iv_user_profile_image);
TextView userName = rowView.findViewById(R.id.tv_user_name);
AssignmentUserModel user = userList.get(position);
userName.setText(user.getUserName());
Bitmap bitmap = user.getUserProfileBitmap();
profilePic.setImageDrawable(bitmap);
return rowView;
}
}
STEP - 5 Create this function and provide ArrayList of above data model in this method
// Pass list of your model as arraylist
private void showCustomAlertDialogBoxForUserList(ArrayList<AssignmentUserModel> allUsersList) {
final Dialog dialog = new Dialog(mActivity);
dialog.setContentView(R.layout.assignment_dialog_list_view);
if (dialog.getWindow() != null) {
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // this is optional
}
ListView listView = dialog.findViewById(R.id.lv_assignment_users);
TextView tv = dialog.findViewById(R.id.tv_popup_title);
ArrayAdapter arrayAdapter = new UserListAdapter(context, R.layout.item_assignment_dialog_list_layout, allUsersList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener((adapterView, view, which, l) -> {
Log.d(TAG, "showAssignmentsList: " + allUsersList.get(which).getUserId());
// TODO : Listen to click callbacks at the position
});
dialog.show();
}
Step - 6 Giving round corner background to dialog box
@drawable/rectangle_round_corner_assignment_alert
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffffff" />
<corners android:radius="16dp" />
<padding
android:bottom="16dp"
android:left="16dp"
android:right="16dp"
android:top="16dp" />
</shape>
I tried MikeTeeVee's solution, still not work, I mean the selected tab still not change and keep different color. This post solved my problem: Set CSS class 'selected' in ASP.NET menu parents and their children? Need put code in code behind.
JTable.AUTO_RESIZE_LAST_COLUMN
is defined as "During all resize operations, apply adjustments to the last column only" which means you have to set the autoresizemode at the end of your code, otherwise setPreferredWidth() won't affect anything!
So in your case this would be the correct way:
table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(400);
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
If you want the previous year and month relative to a specific date and have DateTime available then you can do this:
$d = new DateTime('2013-01-01', new DateTimeZone('UTC'));
$d->modify('first day of previous month');
$year = $d->format('Y'); //2012
$month = $d->format('m'); //12
Another way ..
<img ng-src="{{!video.playing ? 'img/icons/play-rounded-button-outline.svg' : 'img/icons/pause-thin-rounded-button.svg'}}" />
I don't thinks that possible with a vanilla collection without storing the key values in an independent array.
The easiest alternative to do this is to add a reference to the Microsoft Scripting Runtime & use a more capable Dictionary instead:
Dim dict As Dictionary
Set dict = New Dictionary
dict.Add "key1", "value1"
dict.Add "key2", "value2"
Dim key As Variant
For Each key In dict.Keys
Debug.Print "Key: " & key, "Value: " & dict.Item(key)
Next
I worked out Arraxas solution to:
expand the box to include all elements
change background & color on hover
get and alert value on click
do not keep highlighting selection after clicking
let selElem=document.getElementById('myselect').children[0];_x000D_
selElem.size=selElem.length;_x000D_
selElem.value=-1;_x000D_
_x000D_
selElem.addEventListener('change', e => {_x000D_
alert(e.target.value);_x000D_
e.target.value=-1;_x000D_
});
_x000D_
#myselect {_x000D_
display:inline-block; overflow:hidden; border:solid black 1px;_x000D_
}_x000D_
_x000D_
#myselect > select {_x000D_
padding:10px; margin:-5px -20px -5px -5px;";_x000D_
}_x000D_
_x000D_
#myselect > select > option:hover {_x000D_
box-shadow: 0 0 10px 100px #4A8CF7 inset; color: white;_x000D_
}
_x000D_
<div id="myselect">_x000D_
<select>_x000D_
<option value="2010">2010</option>_x000D_
<option value="2011">2011</option>_x000D_
<option value="2012">2012</option>_x000D_
<option value="2013">2013</option>_x000D_
<option value="2014">2014</option>_x000D_
<option value="2015">2015</option>_x000D_
<option value="2016">2016</option>_x000D_
</select>_x000D_
</div>
_x000D_
Just put a
List<Person>
into the ViewBag and in the View cast it back to List
After researching everywhere finally i have found out temporary solution. Because i have try all the solution installing access drivers but still i am facing same issues.
For excel source, Before this step you need to change the setting. Save excel file as 2010 format.xlsx
Also set Project Configuration Properties for Debugging Run64BitRuntime = False
I am using visual studio 2017, sql server 2017, office 2016, and Microsoft access database 2010 engine 32bit. Os windows 10 64 bit.
This is temporary solution. Because many peoples are searching for this type of question. Finally I figured out and this solution is not available in any of the website.
I get the same error in Chrome after pasting code copied from jsfiddle.
If you select all the code from a panel in jsfiddle and paste it into the free text editor Notepad++, you should be able to see the problem character as a question mark "?" at the very end of your code. Delete this question mark, then copy and paste the code from Notepad++ and the problem will be gone.
Use a dictionary when you have a set of unique keys that map to values.
Use a list if you have an ordered collection of items.
Use a set to store an unordered set of items.
Also works for items with spaces and ignores directories
for f in *; do [[ -f "$f" ]] && mv "$f" "unix_$f"; done
I had the same problem today and it costed me all day :-( I tried all of the suggestions above, but none of them did the work.
At the end, I uninstalled Comodo Firewall, and everything worked fine. Before uninstalling, I tried to add the all relevant files as trusted application in the comodo firewall, but it didn't work
Instead of this code, you should call GetHashCode()
, which will return a (hopefully-)unique value for each instance.
You can also use the ObjectIDGenerator
class, which is guaranteed to be unique.
To create a popup you'll need the following script:
<script language="javascript" type="text/javascript">
function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}
</script>
Then, you link to it by:
<a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>
If you want you can call the function directly from document.ready also. Or maybe from another function.
In my limited experience with this question,I try to solve the problem use follow method:
1.Stay android build tools version the same with gradle version. For example:if you use the build tools version is 3.3.0,your gradle version must be 4.10.1.You can reference by the link https://developer.android.com/studio/releases/gradle-plugin and chagne your build tools & gradle version in your AS(File->Project Structure->Project)
2.If method1 don't work,you can custom your ndk toolchains version to solve the problem :like download ndk18 or ndk16 , setting the ndk path is your AS(File->Project Structure->SDK Location->Android NDK Location)
This is not a complete new solution but a correction for afwebservant's solution:
--note comments to see the corrections
CREATE FUNCTION [dbo].[StripHTML] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @Start INT
DECLARE @End INT
DECLARE @Length INT
--DECLARE @TempStr varchar(255) (this is not used)
SET @Start = CHARINDEX('<',@HTMLText)
SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
SET @Length = (@End - @Start) + 1
WHILE @Start > 0 AND @End > 0 AND @Length > 0
BEGIN
IF (UPPER(SUBSTRING(@HTMLText, @Start, 4)) <> '<BR>') AND (UPPER(SUBSTRING(@HTMLText, @Start, 5)) <> '</BR>')
begin
SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
end
-- this ELSE and SET is important
ELSE
SET @Length = 0;
-- minus @Length here below is important
SET @Start = CHARINDEX('<',@HTMLText, @End-@Length)
SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText, @Start))
-- instead of -1 it should be +1
SET @Length = (@End - @Start) + 1
END
RETURN RTRIM(LTRIM(@HTMLText))
END
I use the following alternative to get default/optional params and "kind-of-overloaded" constructors with variable number of params:
private x?: number;
private y?: number;
constructor({x = 10, y}: {x?: number, y?: number}) {
this.x = x;
this.y = y;
}
I know it's not the prettiest code ever, but one gets used to it. No need for the additional Interface and it allows private members, which is not possible when using the Interface.
you will need to use a PHP script (or an other server side language for this)
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
and use httacces to redirect (rewrite) to the PHP file instead of the pdf
This is what I use to display images from blob:
echo '<img src="data:image/jpeg;base64,'.base64_encode($image->load()) .'" />';
The clear way to achieve this,
For example:
If you have dataFile.txt
on your current directory
import java.io.*;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class readByLine
{
public readByLine() throws FileNotFoundException
{
Scanner linReader = new Scanner(new File("dataFile.txt"));
while (linReader.hasNext())
{
String line = linReader.nextLine();
System.out.println(line);
}
linReader.close();
}
public static void main(String args[]) throws FileNotFoundException
{
new readByLine();
}
}
double a = 13.34;
int b = (int) a;
System.out.println(b); //prints 13
You could also use Except(produces the set difference of two sequences) to check whether there's a difference or not:
IEnumerable<string> inFirstOnly = a1.Except(a2);
IEnumerable<string> inSecondOnly = a2.Except(a1);
bool allInBoth = !inFirstOnly.Any() && !inSecondOnly.Any();
So this is an efficient way if the order and if the number of duplicates does not matter(as opposed to the accepted answer's SequenceEqual
). Demo: Ideone
If you want to compare in a case insentive way, just add StringComparer.OrdinalIgnoreCase
:
a1.Except(a2, StringComparer.OrdinalIgnoreCase)
Thanks for the replies.
What I did was,
1. I install meinberg ntp software application on windows 7 pc. (softros ntp server is also possible.)
2. change raspberry pi ntp.conf file (for auto update date and time)
server xxx.xxx.xxx.xxx iburst
server 1.debian.pool.ntp.org iburst
server 2.debian.pool.ntp.org iburst
server 3.debian.pool.ntp.org iburst
3. If you want to make sure that date and time update at startup run this python script in rpi,
import os
try:
client = ntplib.NTPClient()
response = client.request('xxx.xxx.xxx.xxx', version=4)
print "===================================="
print "Offset : "+str(response.offset)
print "Version : "+str(response.version)
print "Date Time : "+str(ctime(response.tx_time))
print "Leap : "+str(ntplib.leap_to_text(response.leap))
print "Root Delay : "+str(response.root_delay)
print "Ref Id : "+str(ntplib.ref_id_to_text(response.ref_id))
os.system("sudo date -s '"+str(ctime(response.tx_time))+"'")
print "===================================="
except:
os.system("sudo date")
print "NTP Server Down Date Time NOT Set At The Startup"
pass
I found more info in raspberry pi forum.
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 certificate in store.Certificates){
//TODO's
}
Indeed ADD go /usr/local/
will add content of go
folder and not the folder itself, you can use Thomasleveil solution or if that did not work for some reason you can change WORKDIR
to /usr/local/
then add your directory to it like:
WORKDIR /usr/local/
COPY go go/
or
WORKDIR /usr/local/go
COPY go ./
But if you want to add multiple folders, it will be annoying to add them like that, the only solution for now as I see it from my current issue is using COPY . .
and exclude all unwanted directories and files in .dockerignore
, let's say I got folders and files:
- src
- tmp
- dist
- assets
- go
- justforfun
- node_modules
- scripts
- .dockerignore
- Dockerfile
- headache.lock
- package.json
and I want to add src assets package.json justforfun go
so:
in Dockerfile:
FROM galaxy:latest
WORKDIR /usr/local/
COPY . .
in .dockerignore file:
node_modules
headache.lock
tmp
dist
Or for more fun (or you like to confuse more people make them suffer as well :P) can be:
*
!src
!assets
!go
!justforfun
!scripts
!package.json
In this way you ignore everything, but excluding what you want to be copied or added only from "ignore list".
It is a late answer but adding more ways to do the same covering even more cases.
Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?
partition() may be better then split() for this purpose as it has the better predicable results for situations you have no delimiter or more delimiters.
I ran into this message when UITableView in the IB was moved into another subview with Cmd-C - Cmd-V.
All identifiers, delegate methods, links in the IB etc. stay intact, but exception is raised at the runtime.
The only solution is to clear all inks, related to tableview in the IB (outlet, datasource, delegate) and make them again.
volatile:
volatile
is a keyword. volatile
forces all threads to get latest value of the variable from main memory instead of cache. No locking is required to access volatile variables. All threads can access volatile variable value at same time.
Using volatile
variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.
This means that changes to a volatile
variable are always visible to other threads. What's more, it also means that when a thread reads a volatile
variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.
When to use: One thread modifies the data and other threads have to read latest value of data. Other threads will take some action but they won't update data.
AtomicXXX:
AtomicXXX
classes support lock-free thread-safe programming on single variables. These AtomicXXX
classes (like AtomicInteger
) resolves memory inconsistency errors / side effects of modification of volatile variables, which have been accessed in multiple threads.
When to use: Multiple threads can read and modify data.
synchronized:
synchronized
is keyword used to guard a method or code block. By making method as synchronized has two effects:
First, it is not possible for two invocations of synchronized
methods on the same object to interleave. When one thread is executing a synchronized
method for an object, all other threads that invoke synchronized
methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized
method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized
method for the same object. This guarantees that changes to the state of the object are visible to all threads.
When to use: Multiple threads can read and modify data. Your business logic not only update the data but also executes atomic operations
AtomicXXX
is equivalent of volatile + synchronized
even though the implementation is different. AmtomicXXX
extends volatile
variables + compareAndSet
methods but does not use synchronization.
Related SE questions:
Difference between volatile and synchronized in Java
Volatile boolean vs AtomicBoolean
Good articles to read: ( Above content is taken from these documentation pages)
https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html
df_gdp.columns
Index([u'Country', u'Country Code', u'Indicator Name', u'Indicator Code', u'1960', u'1961', u'1962', u'1963', u'1964', u'1965', u'1966', u'1967', u'1968', u'1969', u'1970', u'1971', u'1972', u'1973', u'1974', u'1975', u'1976', u'1977', u'1978', u'1979', u'1980', u'1981', u'1982', u'1983', u'1984', u'1985', u'1986', u'1987', u'1988', u'1989', u'1990', u'1991', u'1992', u'1993', u'1994', u'1995', u'1996', u'1997', u'1998', u'1999', u'2000', u'2001', u'2002', u'2003', u'2004', u'2005', u'2006', u'2007', u'2008', u'2009', u'2010', u'2011', u'2012', u'2013', u'2014', u'2015', u'2016'], dtype='object')
df_gdp[df_gdp["Country Code"] == "USA"]["1996"].values[0]
8100000000000.0
Stripes : pretty good. a book on this has come out from pragmatic programmers : http://www.pragprog.com/titles/fdstr/stripes. No XML. Requires java 1.5 or later.
tapestry : have tried an old version 3.x. I'm told that the current version 5.x is in Beta and pretty good.
Stripes should be the better in terms of taking care of maven, no xml and wrapping your head around fast.
BR,
~A
Django has some documentation about that on their website, see: Saving changes to objects. To summarize:
.. to save changes to an object that's already in the database, use
save()
.
I landed here because the title of this question is broad and I was looking for a regex that I could use to match on a specific date format (like the OP). But I then discovered, as many of the answers and comments have comprehensively highlighted, there are many pitfalls that make constructing an effective pattern very tricky when extracting dates that are mixed-in with poor quality or non-structured source data.
In my exploration of the issues, I have come up with a system that enables you to build a regular expression by arranging together four simpler sub-expressions that match on the delimiter, and valid ranges for the year, month and day fields in the order you require.
These are :-
Delimeters
[^\w\d\r\n:]
This will match anything that is not a word character, digit character, carriage return, new line or colon. The colon has to be there to prevent matching on times that look like dates (see my test Data)
You can optimise this part of the pattern to speed up matching, but this is a good foundation that detects most valid delimiters.
Note however; It will match a string with mixed delimiters like this 2/12-73 that may not actually be a valid date.
Year Values
(\d{4}|\d{2})
This matches a group of two or 4 digits, in most cases this is acceptable, but if you're dealing with data from the years 0-999 or beyond 9999 you need to decide how to handle that because in most cases a 1, 3 or >4 digit year is garbage.
Month Values
(0?[1-9]|1[0-2])
Matches any number between 1 and 12 with or without a leading zero - note: 0 and 00 is not matched.
Date Values
(0?[1-9]|[12]\d|30|31)
Matches any number between 1 and 31 with or without a leading zero - note: 0 and 00 is not matched.
This expression matches Date, Month, Year formatted dates
(0?[1-9]|[12]\d|30|31)[^\w\d\r\n:](0?[1-9]|1[0-2])[^\w\d\r\n:](\d{4}|\d{2})
But it will also match some of the Year, Month Date ones. It should also be bookended with the boundary operators to ensure the whole date string is selected and prevent valid sub-dates being extracted from data that is not well-formed i.e. without boundary tags 20/12/194 matches as 20/12/19 and 101/12/1974 matches as 01/12/1974
Compare the results of the next expression to the one above with the test data in the nonsense section (below)
\b(0?[1-9]|[12]\d|30|31)[^\w\d\r\n:](0?[1-9]|1[0-2])[^\w\d\r\n:](\d{4}|\d{2})\b
There's no validation in this regex so a well-formed but invalid date such as 31/02/2001 would be matched. That is a data quality issue, and as others have said, your regex shouldn't need to validate the data.
Because you (as a developer) can't guarantee the quality of the source data you do need to perform and handle additional validation in your code, if you try to match and validate the data in the RegEx it gets very messy and becomes difficult to support without very concise documentation.
Garbage in, garbage out.
Having said that, if you do have mixed formats where the date values vary, and you have to extract as much as you can; You can combine a couple of expressions together like so;
This (disastrous) expression matches DMY and YMD dates
(\b(0?[1-9]|[12]\d|30|31)[^\w\d\r\n:](0?[1-9]|1[0-2])[^\w\d\r\n:](\d{4}|\d{2})\b)|(\b(0?[1-9]|1[0-2])[^\w\d\r\n:](0?[1-9]|[12]\d|30|31)[^\w\d\r\n:](\d{4}|\d{2})\b)
BUT you won't be able to tell if dates like 6/9/1973 are the 6th of September or the 9th of June. I'm struggling to think of a scenario where that is not going to cause a problem somewhere down the line, it's bad practice and you shouldn't have to deal with it like that - find the data owner and hit them with the governance hammer.
Finally, if you want to match a YYYYMMDD string with no delimiters you can take some of the uncertainty out and the expression looks like this
\b(\d{4})(0[1-9]|1[0-2])(0[1-9]|[12]\d|30|31)\b
But note again, it will match on well-formed but invalid values like 20010231 (31th Feb!) :)
Test data
In experimenting with the solutions in this thread I ended up with a test data set that includes a variety of valid and non-valid dates and some tricky situations where you may or may not want to match i.e. Times that could match as dates and dates on multiple lines.
I hope this is useful to someone.
Valid Dates in various formats
Day, month, year
2/11/73
02/11/1973
2/1/73
02/01/73
31/1/1973
02/1/1973
31.1.2011
31-1-2001
29/2/1973
29/02/1976
03/06/2010
12/6/90
month, day, year
02/24/1975
06/19/66
03.31.1991
2.29.2003
02-29-55
03-13-55
03-13-1955
12\24\1974
12\30\1974
1\31\1974
03/31/2001
01/21/2001
12/13/2001
Match both DMY and MDY
12/12/1978
6/6/78
06/6/1978
6/06/1978
using whitespace as a delimiter
13 11 2001
11 13 2001
11 13 01
13 11 01
1 1 01
1 1 2001
Year Month Day order
76/02/02
1976/02/29
1976/2/13
76/09/31
YYYYMMDD sortable format
19741213
19750101
Valid dates before Epoch
12/1/10
12/01/660
12/01/00
12/01/0000
Valid date after 2038
01/01/2039
01/01/39
Valid date beyond the year 9999
01/01/10000
Dates with leading or trailing characters
12/31/21/
31/12/1921AD
31/12/1921.10:55
12/10/2016 8:26:00.39
wfuwdf12/11/74iuhwf
fwefew13/11/1974
01/12/1974vdwdfwe
01/01/99werwer
12321301/01/99
Times that look like dates
12:13:56
13:12:01
1:12:01PM
1:12:01 AM
Dates that runs across two lines
1/12/19
74
01/12/19
74/13/1946
31/12/20
08:13
Invalid, corrupted or nonsense dates
0/1/2001
1/0/2001
00/01/2100
01/0/2001
0101/2001
01/131/2001
31/31/2001
101/12/1974
56/56/56
00/00/0000
0/0/1999
12/01/0
12/10/-100
74/2/29
12/32/45
20/12/194
2/12-73
html_entity_decode('エ', 0, 'UTF-8');
This works too. However the json_decode() solution is a lot faster (around 50 times).
$.ajax({
url: "<?php echo site_url('upToWeb/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function (data) {
if (data.web == 0) {
if (confirm('Data product upToWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 1},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
else {
if (confirm('Data product DownFromWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 0},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
Networking code is notoriously difficult to write, test and debug.
You often have lots of things to consider such as:
what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.
are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive
how does congestion in the real world which causes delays in the stream affect your reading/writing logic
If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).
Here are several different ways to handle the exchange:
have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"
use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"
use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.
have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)
Each approach has its pros and cons for "correctness".
The code below uses the "timeout" method, as that seems to be the one you want.
See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream
on the TCPClient
so you can change the ReadTimeout
.
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
// Set a 250 millisecond timeout for reading (instead of Infinite the default)
stm.ReadTimeout = 250;
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
int bytesread = stm.Read(resp, 0, resp.Length);
while (bytesread > 0)
{
memStream.Write(resp, 0, bytesread);
bytesread = stm.Read(resp, 0, resp.Length);
}
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
As a footnote for other variations on this writing network code...when doing a Read
where you want to avoid a "block", you can check the DataAvailable
flag and then ONLY read what is in the buffer checking the .Length
property e.g. stm.Read(resp, 0, stm.Length);
For reasonably modern versions of sed, edit the standard input to yield the standard output with
$ echo 't???? ß?ß??? ?? ??p??' | sed -E -e 's/[[:blank:]]+/\n/g'
t????
ß?ß???
??
??p??
If your vocabulary words are in files named lesson1
and lesson2
, redirect sed’s standard output to the file all-vocab
with
sed -E -e 's/[[:blank:]]+/\n/g' lesson1 lesson2 > all-vocab
What it means:
[[:blank:]]
matches either a single space character or
a single tab character.
[[:space:]]
instead to match any single whitespace character (commonly space, tab, newline, carriage return, form-feed, and vertical tab).+
quantifier means match one or more of the previous pattern.[[:blank:]]+
is a sequence of one or more characters that are all space or tab.\n
in the replacement is the newline that you want./g
modifier on the end means perform the substitution as many times as possible rather than just once.-E
option tells sed to use POSIX extended regex syntax and in particular for this case the +
quantifier. Without -E
, your sed command becomes sed -e 's/[[:blank:]]\+/\n/g'
. (Note the use of \+
rather than simple +
.)For those familiar with Perl-compatible regexes and a PCRE-capable sed, use \s+
to match runs of at least one whitespace character, as in
sed -E -e 's/\s+/\n/g' old > new
or
sed -e 's/\s\+/\n/g' old > new
These commands read input from the file old
and write the result to a file named new
in the current directory.
Going back to almost any version of sed since Version 7 Unix, the command invocation is a bit more baroque.
$ echo 't???? ß?ß??? ?? ??p??' | sed -e 's/[ \t][ \t]*/\
/g'
t????
ß?ß???
??
??p??
Notes:
+
quantifier and simulate it with a single space-or-tab ([ \t]
) followed by zero or more of them ([ \t]*
).\n
for newline, we have to include it on the command line verbatim.
\
and the end of the first line of the command is a continuation marker that escapes the immediately following newline, and the remainder of the command is on the next line.
The commands above all used single quotes (''
) rather than double quotes (""
). Consider:
$ echo '\\\\' "\\\\"
\\\\ \\
That is, the shell applies different escaping rules to single-quoted strings as compared with double-quoted strings. You typically want to protect all the backslashes common in regexes with single quotes.
Although probably not the best method you could add:
#div1 {
...
font-size:0;
}
As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.
It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.
After beating my head on this for at least an hour, I offer this answer to try to expand on the comments some others have made. To ignore a folder/directory, do the following: if you don't have a .gitignore file in the root of your project (that name exactly ".gitignore"), create a dummy text file in the folder you want to exclude. Inside of Source Tree, right click on it and select Ignore. You'll get a popup that looks like this.
Select "Everything underneath" and select the folder you want to ignore from the drop-down list. This will create a .gitignore file in your root directory and put the folder specification in it.
If you do have a .gitignore folder already in your root folder, you could follow the same approach above, or you can just edit the .gitignore file and add the folder you want to exclude. It's just a text file. Note that it uses forward slashes in path names rather than backslashes, as we Windows users are accustomed to. I tried creating a .gitignore text file by hand in Windows Explorer, but it didn't let me create a file without a name (i.e. with only the extension).
Note that adding the .gitignore and the file specification will have no effect on files that are already being tracked. If you're already tracking these, you'll have to stop tracking them. (Right-click on the folder or file and select Stop Tracking.) You'll then see them change from having a green/clean or amber/changed icon to a red/removed icon. On your next commit the files will be removed from the repository and thereafter appear with a blue/ignored icon. Another contributor asked why Ignore was disabled for particular files and I believe it was because he was trying to ignore a file that was already being tracked. You can only ignore a file that has a blue question mark icon.
We can do this by css3 too. Try this:
.halfsize {
-moz-transform:scale(0.5);
-webkit-transform:scale(0.5);
transform:scale(0.5);
}
<img class="halfsize" src="image4.jpg">
len(yourdict.keys())
or just
len(yourdict)
If you like to count unique words in the file, you could just use set
and do like
len(set(open(yourdictfile).read().split()))
I have found an excellent and relatively short explanation here.
A multipart request is a REST request containing several packed REST requests inside its entity.
It doesn't take the 50% of the whole page is because the "whole page" is only how tall your contents are. Change the enclosing html
and body
to 100%
height and it will work.
html, body{
height: 100%;
}
div{
height: 50%;
}
http://jsfiddle.net/DerekL/5YukJ/1/
^ Your document is only 20px high. 50% of 20px is 10px, and it is not what you expected.
^ Now if you change the height of the document to the height of the whole page (150px), 50% of 150px is 75px, then it will work.
Did you import the packages for the file reading stuff.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
also here
cfiltering(numberOfUsers, numberOfMovies);
Are you trying to create an object or calling a method?
also another thing:
user_movie_matrix[userNo][movieNo]=rating;
you are assigning a value to a member of an instance as if it was a static variable
also remove the Th
in
private int user_movie_matrix[][];Th
Hope this helps.
Using .multiply() (ufunc multiply)
a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0
np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])
From https://texfaq.org/FAQ-nohyph:
TeX won’t hyphenate a word that’s already been hyphenated. For example, the (caricature) English surname Smyth-Postlethwaite wouldn’t hyphenate, which could be troublesome. This is correct English typesetting style (it may not be correct for other languages), but if needs must, you can replace the hyphen in the name with a
\hyph
command, defined\def\hyph{-\penalty0\hskip0pt\relax}
This is not the sort of thing this FAQ would ordinarily recommend… The
hyphenat
package defines a bundle of such commands (for introducing hyphenation points at various punctuation characters).
Or you could \newcommand
a command that expands to multi-discipli\-nary
(use Search + Replace All to replace existing words).
To add timezone
information in Python 3.2+
import datetime
>>> d = datetime.datetime.now(tz=datetime.timezone.utc)
>>> print(d.tzinfo)
'UTC+00:00'
No for-each loop, no extra jQuery plugin needed... Just call the below function.. Got from Difference between two dates in years
function dateDiffInYears(dateold, datenew) {
var ynew = datenew.getFullYear();
var mnew = datenew.getMonth();
var dnew = datenew.getDate();
var yold = dateold.getFullYear();
var mold = dateold.getMonth();
var dold = dateold.getDate();
var diff = ynew - yold;
if (mold > mnew) diff--;
else {
if (mold == mnew) {
if (dold > dnew) diff--;
}
}
return diff;
}
if you don'y want to import any files you can use this:
with open("Test1.txt", "r") as File1:
St = (' '.join(format(ord(x), 'b') for x in File1.read()))
StrList = St.split(" ")
to convert a text file to binary.
and you can use this to convert it back to string:
StrOrgList = StrOrgMsg.split(" ")
for StrValue in StrOrgList:
if(StrValue != ""):
StrMsg += chr(int(str(StrValue),2))
print(StrMsg)
hope that is helpful, i've used this with some custom encryption to send over TCP.
Since new release, it's possible to pass props directly via the Route
component, without using a Wrapper. For example, by using render
prop.
Component:
class Greeting extends React.Component {
render() {
const {text, match: {params}} = this.props;
const {name} = params;
return (
<React.Fragment>
<h1>Greeting page</h1>
<p>
{text} {name}
</p>
</React.Fragment>
);
}
}
Usage:
<Route path="/greeting/:name" render={(props) => <Greeting text="Hello, " {...props} />} />
My preferred way is wrap the Comments
component and pass the wrapper as a route handler.
This is your example with changes applied:
var Dashboard = require('./Dashboard');
var Comments = require('./Comments');
var CommentsWrapper = React.createClass({
render: function () {
return (
<Comments myprop="myvalue"/>
);
}
});
var Index = React.createClass({
render: function () {
return (
<div>
<header>Some header</header>
<RouteHandler/>
</div>
);
}
});
var routes = (
<Route path="/" handler={Index}>
<Route path="comments" handler={CommentsWrapper}/>
<DefaultRoute handler={Dashboard}/>
</Route>
);
ReactRouter.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
If you want to find the control from code behind you have to use runat="server"
attribute on control. And then you can use Control.FindControl
.
<div class="tab-pane active" id="portlet_tab1" runat="server">
Control myControl1 = FindControl("portlet_tab1");
if(myControl1!=null)
{
//do stuff
}
If you use runat server and your control is inside the ContentPlaceHolder
you have to know the ctrl name would not be portlet_tab1 anymore. It will render with the ctrl00 format.
Something like: #ctl00_ContentPlaceHolderMain_portlet_tab1. You will have to modify name if you use jquery.
You can also do it using jQuery on client side without using the runat-server attribute:
<script type='text/javascript'>
$("#portlet_tab1").removeClass("Active");
</script>
For Http Request Default Port number is 80
For Https Default Port Number is 443
For Sql Server Default Port Number is 1433
In latest IntelliJ versions, you should run it from Analyze->Run Inspection By Name:
Than, pick Unused declaration:
And finally, uncheck the Include test sources:
Use the function to clear cookies:
function clearCookies($clearSession = false)
{
$past = time() - 3600;
if ($clearSession === false)
$sessionId = session_id();
foreach ($_COOKIE as $key => $value)
{
if ($clearSession !== false || $value !== $sessionId)
setcookie($key, $value, $past, '/');
}
}
If you pass true
then it clears session
data, otherwise session data is preserved.
Inline-block is a halfway point between setting an element’s display to inline or to block. It keeps the element in the inline flow of the document like display:inline does, but you can manipulate the element’s box attributes (width, height and vertical margins) like you can with display:block.
We must not use block elements within inline elements. This is invalid and there is no reason to do such practices.
You can simply extract the existing zip files also by using "unzip". It will work for any size files and you need to add it as a dependency from npm.
fs.createReadStream(filePath).pipe(unzip.Extract({path:moveIntoFolder})).on('close', function(){_x000D_
//To do after unzip_x000D_
callback();_x000D_
});
_x000D_
What about using a HashMap
? Insertion, deletion, and retrieval are all O(1) operations. If you wanted to sort everything, you could grab a List of the values in the Map and run them through an O(n log n) sorting algorithm.
edit
A quick search has found LinkedHashMap, which maintains insertion order of your keys. It's not an exact solution, but it's pretty close.
Well, defaultdict can also raise keyerror in the following case:
from collections import defaultdict
d = defaultdict()
print(d[3]) #raises keyerror
Always remember to give argument to the defaultdict like defaultdict(int).
Jeffrey Richter recommends following:
public sealed class Singleton
{
private static readonly Object s_lock = new Object();
private static Singleton instance = null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if(instance != null) return instance;
Monitor.Enter(s_lock);
Singleton temp = new Singleton();
Interlocked.Exchange(ref instance, temp);
Monitor.Exit(s_lock);
return instance;
}
}
}
Cohesion is an indication of how related and focused the responsibilities of an software element are.
Coupling refers to how strongly a software element is connected to other elements.
The software element could be class, package, component, subsystem or a system. And while designing the systems it is recommended to have software elements that have High cohesion and support Low coupling.
Low cohesion results in monolithic classes that are difficult to maintain, understand and reduces re-usablity. Similarly High Coupling results in classes that are tightly coupled and changes tend not be non-local, difficult to change and reduces the reuse.
We can take a hypothetical scenario where we are designing an typical monitor-able ConnectionPool
with the following requirements. Note that, it might look too much for a simple class like ConnectionPool
but the basic intent is just to demonstrate low coupling and high cohesion with some simple example and I think should help.
With low cohesion we could design a ConnectionPool
class by forcefully stuffing all this functionality/responsibilities into a single class as below. We can see that this single class is responsible for connection management, interacting with database as well maintaining connection stats.
With high cohesion we can assign these responsibility across the classes and make it more maintainable and reusable.
To demonstrate Low coupling we will continue with the high cohesion ConnectionPool
diagram above. If we look at the above diagram although it supports high cohesion, the ConnectionPool
is tightly coupled with ConnectionStatistics
class and PersistentStore
it interacts with them directly. Instead to reduce the coupling we could introduce a ConnectionListener
interface and let these two classes implement the interface and let them register with ConnectionPool
class. And the ConnectionPool
will iterate through these listeners and notify them of connection get and release events and allows less coupling.
Note/Word or Caution: For this simple scenario it may look like an overkill but if we imagine a real-time scenario where our application needs to interact with multiple third party services to complete a transaction: Directly coupling our code with the third party services would mean that any changes in the third party service could result in changes to our code at multiple places, instead we could have Facade
that interacts with these multiple services internally and any changes to the services become local to the Facade
and enforce low coupling with the third party services.
The syntax you're after is possible with a little helper function that converts a Runnable
into Action<Void, Void>
(you can place it in Action
for example):
public static Action<Void, Void> action(Runnable runnable) {
return (v) -> {
runnable.run();
return null;
};
}
// Somewhere else in your code
Action<Void, Void> action = action(() -> System.out.println("foo"));
Different types to check the values exists
d = {"key1":"value1", "key2":"value2"}
"value10" in d.values()
>> False
What if list of values
test = {'key1': ['value4', 'value5', 'value6'], 'key2': ['value9'], 'key3': ['value6']}
"value4" in [x for v in test.values() for x in v]
>>True
What if list of values with string values
test = {'key1': ['value4', 'value5', 'value6'], 'key2': ['value9'], 'key3': ['value6'], 'key5':'value10'}
values = test.values()
"value10" in [x for v in test.values() for x in v] or 'value10' in values
>>True
I'd go for regexp_replace, although I'm not 100% sure this is usable in PL/SQL
my_value := regexp_replace(my_value, '[[:space:]]*','');
import csv
from collections import defaultdict
columns = defaultdict(list) # each value in each column is appended to a list
with open('file.txt') as f:
reader = csv.DictReader(f) # read rows into a dictionary format
for row in reader: # read a row as {column1: value1, column2: value2,...}
for (k,v) in row.items(): # go over each column name and value
columns[k].append(v) # append the value into the appropriate list
# based on column name k
print(columns['name'])
print(columns['phone'])
print(columns['street'])
With a file like
name,phone,street
Bob,0893,32 Silly
James,000,400 McHilly
Smithers,4442,23 Looped St.
Will output
>>>
['Bob', 'James', 'Smithers']
['0893', '000', '4442']
['32 Silly', '400 McHilly', '23 Looped St.']
Or alternatively if you want numerical indexing for the columns:
with open('file.txt') as f:
reader = csv.reader(f)
reader.next()
for row in reader:
for (i,v) in enumerate(row):
columns[i].append(v)
print(columns[0])
>>>
['Bob', 'James', 'Smithers']
To change the deliminator add delimiter=" "
to the appropriate instantiation, i.e reader = csv.reader(f,delimiter=" ")
You have to use a negative lookahead assertion.
(?!^ABC$)
You could for example use the following.
(?!^ABC$)(^.*$)
If this does not work in your editor, try this. It is tested to work in ruby and javascript:
^((?!ABC).)*$
You can't, never need to and don't really want to.
In Python, everything is an object. Classes are things, so they are objects. So are methods.
There is an object called A
which is a class. It has an attribute called stackoverflow
. It can only have one such attribute.
When you write def stackoverflow(...): ...
, what happens is that you create an object which is the method, and assign it to the stackoverflow
attribute of A
. If you write two definitions, the second one replaces the first, the same way that assignment always behaves.
You furthermore do not want to write code that does the wilder of the sorts of things that overloading is sometimes used for. That's not how the language works.
Instead of trying to define a separate function for each type of thing you could be given (which makes little sense since you don't specify types for function parameters anyway), stop worrying about what things are and start thinking about what they can do.
You not only can't write a separate one to handle a tuple vs. a list, but also don't want or need to.
All you do is take advantage of the fact that they are both, for example, iterable (i.e. you can write for element in container:
). (The fact that they aren't directly related by inheritance is irrelevant.)
a.update(b)
Will add keys and values from b to a, overwriting if there's already a value for a key.
Just see the below code snippet if you are implementing a REST API through express and mongoose. (Example for ADD)
...._x000D_
exports.AddSomething = (req,res,next) =>{_x000D_
const newSomething = new SomeEntity({_x000D_
_id:new mongoose.Types.ObjectId(), //its very own ID_x000D_
somethingName:req.body.somethingName,_x000D_
theForeignKey: mongoose.Types.ObjectId(req.body.theForeignKey)// if you want to pass an object ID_x000D_
})_x000D_
}_x000D_
...
_x000D_
Hope it Helps
I had a similar problem, however in my case I could pull/push to the remote branch but git status
didn't show the local branch state w.r.t the remote ones.
Also, in my case git config --get remote.origin.fetch
didn't return anything
The problem is that there was a typo in the .git/config
file in the fetch line of the respective remote block. Probably something I added by mistake previously (sometimes I directly look at this file, or even edit it)
So, check if your remote entry in the .git/config
file is correct, e.g.:
[remote "origin"]
url = https://[server]/[user or organization]/[repo].git
fetch = +refs/heads/*:refs/remotes/origin/*
Suppose you bound your combobox to a List<Person>
List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource
pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;
Of course this means that you need to add a checking code when you try to use the info from the combobox
if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
MessageBox.Show("Please select a person name");
else
......
The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection
In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to
DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);
An example (listing the methods of the optparse.OptionParser
class):
>>> from optparse import OptionParser
>>> import inspect
#python2
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
('add_option', <unbound method OptionParser.add_option>),
('add_option_group', <unbound method OptionParser.add_option_group>),
('add_options', <unbound method OptionParser.add_options>),
('check_values', <unbound method OptionParser.check_values>),
('destroy', <unbound method OptionParser.destroy>),
('disable_interspersed_args',
<unbound method OptionParser.disable_interspersed_args>),
('enable_interspersed_args',
<unbound method OptionParser.enable_interspersed_args>),
('error', <unbound method OptionParser.error>),
('exit', <unbound method OptionParser.exit>),
('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
...
]
# python3
>>> inspect.getmembers(OptionParser, predicate=inspect.isfunction)
...
Notice that getmembers
returns a list of 2-tuples. The first item is the name of the member, the second item is the value.
You can also pass an instance to getmembers
:
>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...
What about?
If oSheet.QueryTables.Count > 0 Then
oCmbBox.AddItem oSheet.Name
End If
Or
If oSheet.ListObjects.Count > 0 Then
'// Source type 3 = xlSrcQuery
If oSheet.ListObjects(1).SourceType = 3 Then
oCmbBox.AddItem oSheet.Name
End IF
End IF
I developed these 3 useful functions:
def loadModule(moduleName):
module = None
try:
import sys
del sys.modules[moduleName]
except BaseException as err:
pass
try:
import importlib
module = importlib.import_module(moduleName)
except BaseException as err:
serr = str(err)
print("Error to load the module '" + moduleName + "': " + serr)
return module
def reloadModule(moduleName):
module = loadModule(moduleName)
moduleName, modulePath = str(module).replace("' from '", "||").replace("<module '", '').replace("'>", '').split("||")
if (modulePath.endswith(".pyc")):
import os
os.remove(modulePath)
module = loadModule(moduleName)
return module
def getInstance(moduleName, param1, param2, param3):
module = reloadModule(moduleName)
instance = eval("module." + moduleName + "(param1, param2, param3)")
return instance
And everytime I want to reload a new instance I just have to call getInstance() like this:
myInstance = getInstance("MyModule", myParam1, myParam2, myParam3)
Finally I can call all the functions inside the new Instance:
myInstance.aFunction()
The only specificity here is to customize the params list (param1, param2, param3) of your instance.
Most commands/programs return a 0 on success and some other value, called errorlevel
, to signal an error.
You can check for this in you batch for example by:
call <THE_COMMAND_HERE>
if %ERRORLEVEL% == 0 goto :next
echo "Errors encountered during execution. Exited with status: %errorlevel%"
goto :endofscript
:next
echo "Doing the next thing"
:endofscript
echo "Script complete"
What you could do is, a validation of the values, for example:
if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");
// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");
// Form
let contactForm = document.getElementById("form");
// Event listener
contactForm.addEventListener("submit", function (e) {
let messageName = [];
let messageAddress = [];
if (fullname.value === "" || fullname.value === null) {
messageName.push("* This field is required");
}
if (address.value === "" || address.value === null) {
messageAddress.push("* This field is required");
}
// Statement to shows the errors
if (messageName.length || messageAddress.length > 0) {
e.preventDefault();
errorElement.innerText = messageName;
errorElementAddress.innerText = messageAddress;
}
// if the values length is filled and it's greater than 2 then redirect to this page
if (
(fullname.value.length > 2,
address.value.length > 2)
) {
e.preventDefault();
window.location.assign("https://www.google.com");
}
});
_x000D_
.error {
color: #000;
}
.input-container {
display: flex;
flex-direction: column;
margin: 1rem auto;
}
_x000D_
<html>
<body>
<form id="form" method="POST">
<div class="input-container">
<label>Full name:</label>
<input type="text" id="fullname" name="fullname">
<div class="error" id="name_error"></div>
</div>
<div class="input-container">
<label>Address:</label>
<input type="text" id="address" name="address">
<div class="error" id="address_error"></div>
</div>
<button type="submit" id="submit_button" value="Submit request" >Submit</button>
</form>
</body>
</html>
_x000D_
Try this:
cc=is.na(DF$y)
m=which(cc==c("TRUE"))
DF=DF[-m,]
Lots of these solutions work, but this is an alternative.
String hex="#00FF00"; // green
long thisCol=Long.decode(hex)+4278190080L;
int useColour=(int)thisCol;
If you don't add 4278190080 (#FF000000) the colour has an Alpha of 0 and won't show.
I have used Unlocker for years and really like it. It not only will identify programs and offer to unlock the folder\file, it will allow you to kill the processing that has the lock as well.
Additionally, it offers actions to do to the locked file in question such as deleting it.
Unlocker helps delete locked files with error messages including "cannot delete file," and "access is denied." Video tutorial available.
Some errors you might get that Unlocker can help with include:
- Cannot delete file: Access is denied.
- There has been a sharing violation.
- The source or destination file may be in use.
- The file is in use by another program or user.
- Make sure the disk is not full or write-protected and that the file is not currently in use.
For me none of the packages mentioned above did help.
I finally managed to install lxml
after running:
sudo apt-get install python3.5-dev
This works and gives you the installed at path for each gem. This super helpful when trying to do multi-stage docker builds.. You can copy in the specific directory post-bundle install.
bash-4.4# gem list -d
Output::
aasm (5.0.6)
Authors: Thorsten Boettger, Anil Maurya
Homepage: https://github.com/aasm/aasm
License: MIT
Installed at: /usr/local/bundle
State machine mixin for Ruby objects
I had similar Issue where we have GenericResponse object containing list of values
ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
redisMatchedDriverUrl,
HttpMethod.POST,
requestEntity,
ResponseDTO.class
);
Usage of objectMapper helped in converting LinkedHashMap into respective DTO objects
ObjectMapper mapper = new ObjectMapper();
List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });
I using "+" (plus) to insert div to html :
document.getElementById('idParent').innerHTML += '<div id="idChild"> content html </div>';
Hope this help.
Sometimes Google Chrome throws this error, even if it should not. I experienced it when Chrome had a new version, and it needed to be restarted. After restarting the same page worked without any errors. The error in the console was:
net::ERR_INSECURE_RESPONSE
you can use json_decode
function
foreach (json_decode($response) as $area)
{
print_r($area); // this is your area from json response
}
See this fiddle
the sort method contains an optional argument to pass a custom compare function.
Assuming you wanted an array of arrays:
var arr = [[3, "Mike", 20],[5, "Alex", 15]];
function compareName(a, b)
{
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}
arr.sort(compareName);
Otherwise if you wanted an array of objects, you could do:
function compareName(a, b)
{
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
Copy and paste this xml to show as a Dropdown and change your Dropdown color
<?xml version="1.0" encoding="UTF-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:background="@drawable/red">
<Spinner android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dropDownWidth="fill_parent"
android:popupBackground="@drawable/textbox"
android:spinnerMode="dropdown"
android:background="@drawable/drop_down_large"
/>
</LinearLayout>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignLeft="@+id/linearLayout1"
android:layout_alignRight="@+id/linearLayout1"
android:layout_below="@+id/linearLayout1"
android:layout_marginTop="25dp"
android:background="@drawable/red"
android:ems="10"
android:hint="enter card number" >
<requestFocus />
</EditText>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignLeft="@+id/editText1"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="33dp"
android:orientation="horizontal"
android:background="@drawable/red">
<Spinner
android:id="@+id/spinner3"
android:layout_width="72dp"
android:layout_height="wrap_content"
android:popupBackground="@drawable/textbox"
android:spinnerMode="dropdown"
android:background="@drawable/drop_down_large"
/>
<Spinner
android:id="@+id/spinner2"
android:layout_width="72dp"
android:layout_height="wrap_content"
android:popupBackground="@drawable/textbox"
android:spinnerMode="dropdown"
android:background="@drawable/drop_down_large"
/>
<EditText
android:id="@+id/editText2"
android:layout_width="22dp"
android:layout_height="match_parent"
android:layout_weight="0.18"
android:ems="10"
android:hint="enter cvv" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/linearLayout2"
android:layout_below="@+id/linearLayout2"
android:layout_marginTop="26dp"
android:orientation="vertical"
android:background="@drawable/red" >
</LinearLayout>
<Spinner
android:id="@+id/spinner4"
android:layout_width="15dp"
android:layout_height="18dp"
android:layout_alignBottom="@+id/linearLayout3"
android:layout_alignLeft="@+id/linearLayout3"
android:layout_alignRight="@+id/linearLayout3"
android:layout_alignTop="@+id/linearLayout3"
android:popupBackground="@drawable/textbox"
android:spinnerMode="dropdown"
android:background="@drawable/drop_down_large"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/linearLayout3"
android:layout_marginTop="18dp"
android:text="Add Amount"
android:background="@drawable/buttonsty"/>
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
Trying to open multiple panels of a collapse control that is setup as an accordion i.e. with the data-parent
attribute set, can prove quite problematic and buggy (see this question on multiple panels open after programmatically opening a panel)
Instead, the best approach would be to:
To allow each panel to toggle individually, on the data-toggle="collapse"
element, set the data-target
attribute to the .collapse
panel ID selector (instead of setting the data-parent
attribute to the parent control. You can read more about this in the question Modify Twitter Bootstrap collapse plugin to keep accordions open.
Roughly, each panel should look like this:
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title"
data-toggle="collapse"
data-target="#collapseOne">
Collapsible Group Item #1
</h4>
</div>
<div id="collapseOne"
class="panel-collapse collapse">
<div class="panel-body"></div>
</div>
</div>
To manually enforce the accordion behavior, you can create a handler for the collapse show event which occurs just before any panels are displayed. Use this to ensure any other open panels are closed before the selected one is shown (see this answer to multiple panels open). You'll also only want the code to execute when the panels are active. To do all that, add the following code:
$('#accordion').on('show.bs.collapse', function () {
if (active) $('#accordion .in').collapse('hide');
});
Then use show
and hide
to toggle the visibility of each of the panels and data-toggle
to enable and disable the controls.
$('#collapse-init').click(function () {
if (active) {
active = false;
$('.panel-collapse').collapse('show');
$('.panel-title').attr('data-toggle', '');
$(this).text('Enable accordion behavior');
} else {
active = true;
$('.panel-collapse').collapse('hide');
$('.panel-title').attr('data-toggle', 'collapse');
$(this).text('Disable accordion behavior');
}
});
You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:
{el1, el2, {el31, el32, el33}, {el41, el42}}
var MainObj = {_x000D_
_x000D_
prop1: "prop1MainObj",_x000D_
_x000D_
Obj1: {_x000D_
prop1: "prop1Obj1",_x000D_
prop2: "prop2Obj1", _x000D_
Obj2: {_x000D_
prop1: "hey you",_x000D_
prop2: "prop2Obj2"_x000D_
}_x000D_
},_x000D_
_x000D_
Obj3: {_x000D_
prop1: "prop1Obj3",_x000D_
prop2: "prop2Obj3"_x000D_
},_x000D_
_x000D_
Obj4: {_x000D_
prop1: true,_x000D_
prop2: 3_x000D_
} _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
This is what you have to do since sess.createCriteria is deprecated:
CriteriaBuilder builder = getSession().getCriteriaBuilder();
CriteriaQuery<User> q = builder.createQuery(User.class);
Root<User> usr = q.from(User.class);
ParameterExpression<String> p = builder.parameter(String.class);
q.select(usr).where(builder.like(usr.get("name"),p))
.orderBy(builder.asc(usr.get("name")));
TypedQuery<User> query = getSession().createQuery(q);
query.setParameter(p, "%" + Main.filterName + "%");
List<User> list = query.getResultList();
That depends on what firewall do you have installed. In my case I do have disabled the built-in Windows Firewall and I am using ESET Smart Security so my rules looks like:
445
:Maybe this is not the answer since it's not related to Windows Firewall but could give you a clue in what to do.
Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
searchedValue = rows(0).Item("ColumnName2")
End If
With FirstOrDefault
:
Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
searchedValue = row.Item("ColumnName2")
End If
In C#:
var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
searchedValue = row["ColumnName2"];
Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:
#container {
min-width:800px;
width: auto !important;
width:800px;
}
That will effectively give you 800px min-width in IE6 and any up-to-date browsers.
this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in this case:
you specify
transaction_status varchar(10)
but you actually trying to store
_transaction_status
which contain 19 characters.
that's why you faced this type of error in this code..
The functions getElementById
and getElementsByClassName
are very specific, while querySelector
and querySelectorAll
are more elaborate. My guess is that they will actually have a worse performance.
Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".
If you need this to work in a textarea the accepted solution will not work.
<textarea id='textarea'></textarea>
$("#textarea").append(formatJSON(JSON.stringify(jsonobject),true));
function formatJSON(json,textarea) {
var nl;
if(textarea) {
nl = " ";
} else {
nl = "<br>";
}
var tab = "    ";
var ret = "";
var numquotes = 0;
var betweenquotes = false;
var firstquote = false;
for (var i = 0; i < json.length; i++) {
var c = json[i];
if(c == '"') {
numquotes ++;
if((numquotes + 2) % 2 == 1) {
betweenquotes = true;
} else {
betweenquotes = false;
}
if((numquotes + 3) % 4 == 0) {
firstquote = true;
} else {
firstquote = false;
}
}
if(c == '[' && !betweenquotes) {
ret += c;
ret += nl;
continue;
}
if(c == '{' && !betweenquotes) {
ret += tab;
ret += c;
ret += nl;
continue;
}
if(c == '"' && firstquote) {
ret += tab + tab;
ret += c;
continue;
} else if (c == '"' && !firstquote) {
ret += c;
continue;
}
if(c == ',' && !betweenquotes) {
ret += c;
ret += nl;
continue;
}
if(c == '}' && !betweenquotes) {
ret += nl;
ret += tab;
ret += c;
continue;
}
if(c == ']' && !betweenquotes) {
ret += nl;
ret += c;
continue;
}
ret += c;
} // i loop
return ret;
}
The bug has been fixed in the latest androidx version. And the famous workaround will cause crash now. so we need not it now.
All's correct. return
logically processes from left to right and returns the last value.
function foo(){
return 1,2,3;
}
>> foo()
>> 3
UPDATE TABLE <tablename>
SET <COLUMN=VALUE>
WHERE <CONDITION>
Example:
UPDATE TABLE teacher SET teacher_name='NSP' WHERE teacher_id='1'
function gotoItem( item ){
var url = window.location.href;
var separator = (url.indexOf('?') > -1) ? "&" : "?";
var qs = "item=" + encodeURIComponent(item);
window.location.href = url + separator + qs;
}
More compat version
function gotoItem( item ){
var url = window.location.href;
url += (url.indexOf('?') > -1)?"&":"?" + "item=" + encodeURIComponent(item);
window.location.href = url;
}
After creating your QVBoxLayout
in Qt Designer, right-click on the background of your widget/dialog/window (not the QVBoxLayout
, but the parent widget) and select Lay Out -> Lay Out in a Grid from the bottom of the context-menu. The QVBoxLayout
should now stretch to fit the window and will resize automatically when the entire window is resized.
As User Mr. Brownstone
suggested you can use a stored procedure; to make it easy for all i created a minimalist example. First create a stored procedure:
Create PROCEDURE MultipleOutParameter
@Input int,
@Out1 int OUTPUT,
@Out2 int OUTPUT
AS
BEGIN
Select @Out1 = @Input + 1
Select @Out2 = @Input + 2
Select 'this returns your normal Select-Statement' as Foo
, 'amazing is it not?' as Bar
-- Return can be used to get even more (afaik only int) values
Return(@Out1+@Out2+@Input)
END
To execute the stored procedure a few local variables are needed to receive the value:
DECLARE @GetReturnResult int, @GetOut1 int, @GetOut2 int
EXEC @GetReturnResult = MultipleOutParameter
@Input = 1,
@Out1 = @GetOut1 OUTPUT,
@Out2 = @GetOut2 OUTPUT
To see the values content you can do the following
Select @GetReturnResult as ReturnResult, @GetOut1 as Out_1, @GetOut2 as Out_2
This will be the result:
s = s.Replace( """", "" )
Two quotes next to each other will function as the intended " character when inside a string.
<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />
<head>
<base href="${baseURL}" />
In my case it was something else: the object I was saving should first have an id(e.g. save() should be called) before I could set any kind of relationship with it.
I would recommend to use css, but php to use to set some class or id for the element, in order to make it generated dynamically.
rows, columns = list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(rows):
a=list(map(int,input().split()))
b.append(a)
print(b)
input
2 3
1 2 3
4 5 6
output [[1, 2, 3], [4, 5, 6]]
Simulator is something more broader than Emulator and it seems like the duality of this terms is overthought in the posts above.
Emulator
People decided to use a new word emulation in the "computer world" when they started replacing some hardware parts of the existing system in straightforward manner - imitating their behaviour and relying on the computational nature to be sure to not break something and leave everything in the equivalent state. So we have emulated the piece of this! (and the whole still works as before)
Emulator usually used in narrow sense in digital area as replacement and virtualization - presenting in digital form as a piece of software - of something known and existed before (virtual chips, circuit boards, electronic devices). So when the world became more digital and brought the emulator word to the masses, the masses added uncertainty to it (or additional reasons).
Simulator
First of all, I saw many comments about emulators do or replace something real but simulators not.
BUT flight simulator is used for a real thing - it trains pilots, gives them skill up and knowledge and it replaces expensive real planes and saves much of money. And we cannot just say a plane-emulator because we have inner feeling that this is much more than that, so we call it simulator :) Plane simulator could contain emulated radar or transponder that is true.
Contra-statements that simulators are used for analysis and study (and emulators for something real), but that analysis and study not less a real thing than emulated GSM boards (even more in the informational age we live in). Analysis adds a value to the business, cuts costs or points out to profits not less than the replaced (emulated) hardware.
Simulator is similar to modelling of something that we can't obtain for some reason (cost, technology, physical impossibility). It is usually simulated for something new or intangible or complex or not properly known to us like market, weather, combustion, user. So here comes the flight, black hole, stock exchange, simulations.
So finally:
As for words origin
All came from Latin and mean:
As per this answer over here: str='foo%20%5B12%5D'
encodes foo [12]
:
%20 is space
%5B is '['
and %5D is ']'
This is called percent encoding and is used in encoding special characters in the url parameter values.
EDIT By the way as I was reading https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURI#Description, it just occurred to me why so many people make the same search. See the note on the bottom of the page:
Also note that if one wishes to follow the more recent RFC3986 for URL's, making square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following may help.
function fixedEncodeURI (str) {
return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
}
Hopefully this will help people sort out their problems when they stumble upon this question.
public static IEnumerable<IEnumerable<T>> SplitEvery<T>(this IEnumerable<T> values, int n)
{
var ls = values.Take(n);
var rs = values.Skip(n);
return ls.Any() ?
Cons(ls, SplitEvery(rs, n)) :
Enumerable.Empty<IEnumerable<T>>();
}
public static IEnumerable<T> Cons<T>(T x, IEnumerable<T> xs)
{
yield return x;
foreach (var xi in xs)
yield return xi;
}
In my case, it seems ng is not registered into my environment path. I have been using npm run command to run the ng commands. Be aware in order to pass arguments you need an extra --
as per the npm run specification.
Example:
npm run ng g c components/scheduling **--** --module=app
Or:
npm run ng g c components/scheduling **--** --skip-import
You can use not only now()
, also current_timestamp()
and localtimestamp()
.
The main reason of incorrect display timestamp is inserting NOW() with single quotes! It didn't work for me in MySQL Workbench because of this IDE add single quotes for mysql functions and i didn't recognize it at once )
Don't use functions with single quotes like in MySQL Workbench. It doesn't work.
It depends on context. There a lot benefits that are appropriate to dynamic typed system as well as for strong typed. I'm of opinion that the flow of dynamic types language is faster. The dynamic languages are not constrained with class attributes and compiler thinking of what is going on in code. You have some kinda freedom. Furthermore, the dynamic language usually is more expressive and result in less code which is good. Despite of this, it's more error prone which is also questionable and depends more on unit test covering. It's easy prototype with dynamic lang but maintenance may become nightmare.
The main gain over static typed system is IDE support and surely static analyzer of code. You become more confident of code after every code change. The maintenance is peace of cake with such tools.
Simple solution which worked for me.
Now you can also use Talentsoft.Moq.SetupAsync package https://github.com/TalentSoft/Moq.SetupAsync
Which on the base on the answers found here and ideas proposed to Moq but still not yet implemented here: https://github.com/moq/moq4/issues/384, greatly simplify setup of async methods
Few examples found in previous responses done with SetupAsync extension:
mock.SetupAsync(arg=>arg.DoSomethingAsync());
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Callback(() => { <my code here> });
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Throws(new InvalidOperationException());
from __future__ import with_statement
with open('file.txt','r+') as f:
counter = str(int(f.read().strip())+1)
f.seek(0)
f.write(counter)
Use "\n":
file.write("My String\n")
See the Python manual for reference.
This should be a bit more secure hash than some other answers, but in a function, without any preloaded source
I created basicly a minified simplified version of sha1.
You take the bytes of the string and group them by 4 to 32bit "words"
Then we extend every 8 words to 40 words (for bigger impact on the result).
This goes to the hashing function (the last reduce) where we do some maths with the current state and the input. We always get 4 words out.
This is almost a one-command/one-line version using map,reduce... instead of loops, but it is still pretty fast
String.prototype.hash = function(){
var rot = (word, shift) => word << shift | word >>> (32 - shift);
return unescape(encodeURIComponent(this.valueOf())).split("").map(char =>
char.charCodeAt(0)
).reduce((done, byte, idx, arr) =>
idx % 4 == 0 ? [...done, arr.slice(idx, idx + 4)] : done
, []).reduce((done, group) =>
[...done, group[0] << 24 | group[1] << 16 | group[2] << 8 | group[3]]
, []).reduce((done, word, idx, arr) =>
idx % 8 == 0 ? [...done, arr.slice(idx, idx + 8)] : done
, []).map(group => {
while(group.length < 40)
group.push(rot(group[group.length - 2] ^ group[group.length - 5] ^ group[group.length - 8], 3));
return group;
}).flat().reduce((state, word, idx, arr) => {
var temp = ((state[0] + rot(state[1], 5) + word + idx + state[3]) & 0xffffffff) ^ state[idx % 2 == 0 ? 4 : 5](state[0], state[1], state[2]);
state[0] = rot(state[1] ^ state[2], 11);
state[1] = ~state[2] ^ rot(~state[3], 19);
state[2] = rot(~state[3], 11);
state[3] = temp;
return state;
}, [0xbd173622, 0x96d8975c, 0x3a6d1a23, 0xe5843775,
(w1, w2, w3) => (w1 & rot(w2, 5)) | (~rot(w1, 11) & w3),
(w1, w2, w3) => w1 ^ rot(w2, 5) ^ rot(w3, 11)]
).slice(0, 4).map(p =>
p >>> 0
).map(word =>
("0000000" + word.toString(16)).slice(-8)
).join("");
};
we also convert the output to hex to get a string instead of word array.
Usage is simple. for expample "a string".hash()
will return "88a09e8f9cc6f8c71c4497fbb36f84cd"
String.prototype.hash = function(){_x000D_
var rot = (word, shift) => word << shift | word >>> (32 - shift);_x000D_
return unescape(encodeURIComponent(this.valueOf())).split("").map(char =>_x000D_
char.charCodeAt(0)_x000D_
).reduce((done, byte, idx, arr) =>_x000D_
idx % 4 == 0 ? [...done, arr.slice(idx, idx + 4)] : done_x000D_
, []).reduce((done, group) =>_x000D_
[...done, group[0] << 24 | group[1] << 16 | group[2] << 8 | group[3]]_x000D_
, []).reduce((done, word, idx, arr) =>_x000D_
idx % 8 == 0 ? [...done, arr.slice(idx, idx + 8)] : done_x000D_
, []).map(group => {_x000D_
while(group.length < 40)_x000D_
group.push(rot(group[group.length - 2] ^ group[group.length - 5] ^ group[group.length - 8], 3));_x000D_
return group;_x000D_
}).flat().reduce((state, word, idx, arr) => {_x000D_
var temp = ((state[0] + rot(state[1], 5) + word + idx + state[3]) & 0xffffffff) ^ state[idx % 2 == 0 ? 4 : 5](state[0], state[1], state[2]);_x000D_
state[0] = rot(state[1] ^ state[2], 11);_x000D_
state[1] = ~state[2] ^ rot(~state[3], 19);_x000D_
state[2] = rot(~state[3], 11);_x000D_
state[3] = temp;_x000D_
return state;_x000D_
}, [0xbd173622, 0x96d8975c, 0x3a6d1a23, 0xe5843775,_x000D_
(w1, w2, w3) => (w1 & rot(w2, 5)) | (~rot(w1, 11) & w3),_x000D_
(w1, w2, w3) => w1 ^ rot(w2, 5) ^ rot(w3, 11)]_x000D_
).slice(0, 4).map(p =>_x000D_
p >>> 0_x000D_
).map(word =>_x000D_
("0000000" + word.toString(16)).slice(-8)_x000D_
).join("");_x000D_
};_x000D_
let str = "the string could even by empty";_x000D_
console.log(str.hash())//9f9aeca899367572b875b51be0d566b5
_x000D_
The method select
accepts a list of column names (string) or expressions (Column) as a parameter. To select columns you can use:
-- column names (strings):
df.select('col_1','col_2','col_3')
-- column objects:
import pyspark.sql.functions as F
df.select(F.col('col_1'), F.col('col_2'), F.col('col_3'))
# or
df.select(df.col_1, df.col_2, df.col_3)
# or
df.select(df['col_1'], df['col_2'], df['col_3'])
-- a list of column names or column objects:
df.select(*['col_1','col_2','col_3'])
#or
df.select(*[F.col('col_1'), F.col('col_2'), F.col('col_3')])
#or
df.select(*[df.col_1, df.col_2, df.col_3])
The star operator *
can be omitted as it's used to keep it consistent with other functions like drop
that don't accept a list as a parameter.
You can do this In the parent component declare:
get self(): ParenComponentClass {
return this;
}
In the child component,after include the import of ParenComponentClass, declare:
private _parent: ParenComponentClass ;
@Input() set parent(value: ParenComponentClass ) {
this._parent = value;
}
get parent(): ParenComponentClass {
return this._parent;
}
Then in the template of the parent you can do
<childselector [parent]="self"></childselector>
Now from the child you can access public properties and methods of parent using
this.parent
DELETE FROM table WHERE date < '2011-09-21 08:21:22';
Try adding "bDestroy": true to the options object literal, e.g.
$('#dataTable').dataTable({
...
....
"bDestroy": true
});
Source: iodocs.com
or Remove the first:
$(document).ready(function() {
$('#example').dataTable();
} );
In your case is the best option vjk.
In Asp Net Core, to quickly get it working for development; in Startup.cs
, Configure method
add
app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
In Tomcat 8.0.44 I did this: create the JNDI on Tomcat's server.xml between the tag "GlobalNamingResources" For example:
<GlobalNamingResources>_x000D_
<!-- Editable user database that can also be used by_x000D_
UserDatabaseRealm to authenticate users_x000D_
-->_x000D_
<!-- Other previus resouces -->_x000D_
<Resource auth="Container" driverClassName="org.postgresql.Driver" global="jdbc/your_jndi" _x000D_
maxActive="100" maxIdle="20" maxWait="1000" minIdle="5" name="jdbc/your_jndi" password="your_password" _x000D_
type="javax.sql.DataSource" url="jdbc:postgresql://localhost:5432/your_database?user=postgres" username="database_username"/>_x000D_
</GlobalNamingResources>
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<Context reloadable="true" >_x000D_
<ResourceLink name="jdbc/your_jndi"_x000D_
global="jdbc/your_jndi"_x000D_
auth="Container"_x000D_
type="javax.sql.DataSource" />_x000D_
</Context>
_x000D_
So if you're using Hiberte with spring you can tell to him to use the JNDI in your persistence.xml
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"_x000D_
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">_x000D_
<persistence-unit name="UNIT_NAME" transaction-type="RESOURCE_LOCAL">_x000D_
<provider>org.hibernate.ejb.HibernatePersistence</provider>_x000D_
_x000D_
<properties>_x000D_
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />_x000D_
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />_x000D_
_x000D_
<!-- <property name="hibernate.jdbc.time_zone" value="UTC"/>-->_x000D_
<property name="hibernate.hbm2ddl.auto" value="update" />_x000D_
<property name="hibernate.show_sql" value="false" />_x000D_
<property name="hibernate.format_sql" value="true"/> _x000D_
</properties>_x000D_
</persistence-unit>_x000D_
</persistence>
_x000D_
So in your spring.xml you can do that:
<bean id="postGresDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />_x000D_
</bean>_x000D_
_x000D_
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">_x000D_
<property name="persistenceUnitName" value="UNIT_NAME" />_x000D_
<property name="dataSource" ref="postGresDataSource" />_x000D_
<property name="jpaVendorAdapter"> _x000D_
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />_x000D_
</property>_x000D_
</bean>
_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />
_x000D_
In this example I used spring with xml but you can do this programmaticaly if you prefer.
That's it, I hope helped.
Response.Cookies
contains the cookies that will be sent back to the browser. If you want to know whether a cookie exists, you should probably look into Request.Cookies
.
Anyway, to see if a cookie exists, you can check Cookies.Get(string)
. However, if you use this method on the Response object and the cookie doesn't exist, then that cookie will be created.
See MSDN Reference for HttpCookieCollection.Get
Method (String)
$(function () {
$('#myTab a:last').tab('show');
});
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target = $(e.target).attr("href");
if ((target == '#messages')) {
alert('ok');
} else {
alert('not ok');
}
});
the problem is that attr('href') is never empty.
Or to compare the #id = "#some value" and then call the ajax.