_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d14901 | val | You didn't registered the default task. Add this after the last loadNpmTask
grunt.registerTask('default', ['execute']);
The second parameter is what you want to be executed from the config, you can put there more tasks.
Or you can run run existing task by providing the name as parameter in cli.
grunt execute
With you config you can use execute and watch. See https://gruntjs.com/api/grunt.task for more information.
A: If you run grunt in your terminal it is going to search for a "default" task, so you have to register a task to be executed with Grunt defining it with the grunt.registerTask method, with a first parameter which is the name of your task, and a second parameter which is an array of subtasks that it will run.
In your case, the code could be something like that:
...
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-execute');
grunt.registerTask("default", ["execute", "watch"]);
...
In this way the "default" task will run rispectively the "execute" and the "watch" commands.
However here you can find the documentation to create tasks with Grunt.
Hope it was helpful. | unknown | |
d14902 | val | SELECT * FROM <table>
WHERE
(PRIMARY="0" AND TRANSTYPE = "A") OR
(PRIMARY="1" AND TRANSTYPE = "B") OR
(PRIMARY="1" AND TRANSTYPE = "C")
A: you can do
CREATE PROCEDURE PROC_NAME()
BEGIN
select * from table
where (TRANSTYPE = 'A' and PRIMARY = '0')
or (TRANSTYPE in ('B','C') and PRIMARY = '1');
END; | unknown | |
d14903 | val | The function returns a tuple
return jelly_beans, jars, crates
or more explicitly
return (jelly_beans, jars, crates)
The next part is called tuple unpacking
sometuple = secret_formula(start_point)
beans, jars, crates = sometuple
since your function returns a tuple of 3,it can be unpacked to 3 variables
you can also do this in one step
beans, jars, crates = secret_formula(start_point)
A: formula = secret_formula(start_point)
print type(formula) # <type 'tuple'>
So when you are returning its return a tuple.
beans, jars, crates = secret_formula(start_point)
by this you are initialising these variables with data in tuple like this:-
In [6]: a, b, c = (1, 2, 3)
In [7]: a
Out[7]: 1
In [8]: b
Out[8]: 2
In [9]: c
Out[9]: 3
so if you do something like this even storing in a single variable it works fine,
print "We'd have {!r} formula" .format(formula)
A: def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print "With a starting point of: %d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)
breakdown:
*
*Define start_point as 10,000
*Pass that into secret_formula()
*Inside secret_formula is a new 'scope' - a place where variables can exist. It's like being in a house with one-way glass windows. You can see variables in the scope outside, but the outside cannot see in. {Scope exists in part so you can have different functions using the same variable names like x and y without clashes}.
*In the secret_formula scope, create the variables jelly_beans and jars and crates and do calculations, and link (bind) the resulting numbers to those names.
*Inside secret_formula, combine these three into a tuple. That's what jelly_beans, jars, crates is doing by having them with commas between them. A tuple is a collection of a few things grouped together and treated as one thing for convenience. You can only return one thing, so this is a workaround to return three-numbers-as-one-thing. The tuple contains the numbers, not the names.
*Inside secret_formula, return the tuple and finish.
*Python clears up the secret_formula scope and removes the jelly_beans and jars and crates names that were running inside it somewhen around now. The function is no longer running and all the names used inside it have "fallen out of scope" and get cleaned up.
*The tuple coming out of the function is a group of three numbers, in order. Create three new variable names, split the three numbers up, and bind the numbers to those new names, in this outer scope.
Does this mean that jelly_beans, jars, crates from the return can be replaced with any combo of three?
Yep. NB. When print prints "%d" it's looking for a whole number, so you would have to replace them with any three numbers 3,55,100 or number variables.
A: One interesting difference between python with other languages such as java and C# is python can return several results, that is what we called tuple
So to your question:
Does this mean that jelly_beans, jars, crates from the return can be replaced with any combo of three?
My answer is yes,
after the code: the three variable would be initialized, and know the type of themselves...
beans, jars, crates = secret_formula(start_point)
if the secret_formula() function returns as:
return 1, 'a', {'key':'value'}
that also make senses, beans, jars, crates will know they are int, string and dict type respectively | unknown | |
d14904 | val | Because oplog tailing is disabled.
When there's no oplog tailing, Meteor uses "poll-and-diff" strategy that execute mongodb queries every 10 seconds and then do a diff to see if some data changed.
To solve it, you can activate oplog tailing this way: https://github.com/meteor/meteor/wiki/Oplog-Observe-Driver#oplogobservedriver-in-production | unknown | |
d14905 | val | I'd suggest copying your data range to a memory-based array and checking that, then using that data to adjust the visibility of each row. It minimizes the number of interactions you have with the worksheet Range object, which takes up lots of time and is a big performance hit for large ranges.
Sub HideHiddenRows()
Dim dataRange As Range
Dim data As Variant
Set dataRange = Sheet1.Range("A13:A2019")
data = dataRange.Value
Dim rowOffset As Long
rowOffset = IIf(LBound(data, 1) = 0, 1, 0)
ApplicationPerformance Flag:=False
Dim i As Long
For i = LBound(data, 1) To UBound(data, 1)
If data(i, 1) = "Hide" Then
dataRange.Rows(i + rowOffset).EntireRow.Hidden = True
Else
dataRange.Rows(i + rowOffset).EntireRow.Hidden = False
End If
Next i
ApplicationPerformance Flag:=True
End Sub
Public Sub ApplicationPerformance(ByVal Flag As Boolean)
Application.ScreenUpdating = Flag
Application.DisplayAlerts = Flag
Application.EnableEvents = Flag
End Sub
A: to increase perfomance you can populate dictionary with range addresses, and hide or unhide at once, instead of hide/unhide each particular row (but this is just in theory, you should test it by yourself), just an example:
Sub HideHiddenRows()
Dim cl As Range, x As Long
Dim dic As Object: Set dic = CreateObject("Scripting.Dictionary")
x = Cells(Rows.Count, "A").End(xlUp).Row
For Each cl In Range("A1", Cells(x, "A"))
If cl.Value = 0 Then dic.Add cl.Address(0, 0), Nothing
Next cl
Range(Join(dic.keys, ",")).EntireRow.Hidden = False
End Sub
demo:
A: Another possibility:
Dim mergedRng As Range
'.......
rng_HideFormula.EntireRow.Hidden = False
For Each rng_Item In rng_HideFormula
If rng_Item.Value2 = str_HideRef Then
If Not mergedRng Is Nothing Then
Set mergedRng = Application.Union(mergedRng, rng_Item)
Else
Set mergedRng = rng_Item
End If
End If
Next rng_Item
If Not mergedRng Is Nothing Then mergedRng.EntireRow.Hidden = True
Set mergedRng = Nothing
'........ | unknown | |
d14906 | val | Swift 2.0:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UINavigationBar.appearance().titleTextAttributes = [
NSFontAttributeName: UIFont(name: "DINNextLTW04-Regular", size: 20)!
]
return true
}
Or
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBarHidden = false
self.title = "SAMPLE"
//Set Color
let attributes: AnyObject = [ NSForegroundColorAttributeName: UIColor.redColor()]
self.navigationController!.navigationBar.titleTextAttributes = attributes as? [String : AnyObject]
//Set Font Size
self.navigationController!.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Arial", size: 37.0)!];
}
A: You got it already,but you can also use following attributes methods.
For Color,
NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor RedColor],UITextAttributeTextColor, nil];
self.navigationController.navigationBar.titleTextAttributes = attributes;
For Size,
NSDictionary *size = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Arial" size:17.0],UITextAttributeFont, nil];
self.navigationController.navigationBar.titleTextAttributes = size;
Thanks.
For iOS 7 and above
For Size:
NSDictionary *size = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Arial" size:17.0],NSFontAttributeName, nil];
self.navigationController.navigationBar.titleTextAttributes = size;
A: You need to grab the navigation bar property and the use @property(nonatomic, copy) NSDictionary *titleTextAttributes.
For further info see UINavigationBar Class Reference and Customizing UINavigationBar section.
To understand better your question: What type of controller do you have?
EDIT
[self.navigationController.navigationBar setTitleTextAttributes:...];
if you access the navigationController within a pushed controller.
[navigationController.navigationBar setTitleTextAttributes:...];
if navigationController is your current UINavigationController. This could be used when for example if you have the following code:
UINavigationController* navigationController = ...;
[navigationController.navigationBar setTitleTextAttributes:...];
A: Since iOS7, I always do like following:
[[UINavigationBar appearance] setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"Helvetica-Bold" size:18.0],NSFontAttributeName,
nil]];
The Keyword UITextAttributeFont has been depressed from iOS7, you'd supposed to replace with
NSFontAttributeName.
You can use
[self.navigationController.navigationBar setTitleTextAttributes:]to set someone navigationController's appearence, while [UINavigationBar appearance] setTitleTextAttributes:] works for your whole App directly.(Of course you need to put it in a property position.)
A: My example
guard let sansLightFont = UIFont(name: "OpenSans", size: 20) else { return }
navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName : sansLightFont] | unknown | |
d14907 | val | Reasons to throw securityError exception.
*
*Invalid path,
*Trying to access a URL, that not permitted by the security sandbox,
*Trying a socket connection, that exceeding the port limit, and
*Trying to access a device, that has been denied by the user(Ex., camera, microphone.)
try this
private var _loader:Loader = new Loader();
private var _context:LoaderContext = new LoaderContext();
private var _url:URLRequest = new URLRequest("demo1/mic.jpg");
_context.checkPolicyFile = false;
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageloaded);
//_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
_loader.load(_url, _context);
private function onImageloaded(e:Event):void{
addChild(e.target.content);
}
A: Use slashes instead of back slashes :
loader.load(new URLRequest("C:/Documents and Settings/Owner/Desktop/23Aug/demo1\mic.jpg"), context);
But the best way is to use relative path like "./mic.jpg" and do not use absolute path. | unknown | |
d14908 | val | Reads each line and searches each line. Also remembers the previous search and directory.
Two issues that you can fix.
*
*It will now hits the 5 million statement timeout message esp if going through exe files.
*It won't find Unicode text.
This is the third time I've written the program.
<HTML>
<HEAD><TITLE>Simple Validation</TITLE>
<SCRIPT LANGUAGE="VBScript">
Dim Dirname
Dim Searchterm
Dim FSO
Dim objOutFile
Sub Browse
On Error Resume Next
Set bffShell = CreateObject("Shell.Application")
Set bff = bffShell.BrowseForFolder(0, "Select the My Documents folder", 9)
If Err.number<>0 Then
MsgBox "Error Setting up Browse for Folder"
Else
A = bff.ParentFolder.ParseName(bff.Title).Path
If err.number=424 then err.clear
tb2.value = A
End If
End Sub
Sub Search
On Error Resume Next
Set WshShell = CreateObject("WScript.Shell")
WshShell.RegWrite "HKCU\Software\StackOverflow\VBS\Searchterm", tb1.value
WshShell.RegWrite "HKCU\Software\StackOverflow\VBS\Directory", tb2.value
Set fso = CreateObject("Scripting.FileSystemObject")
Set objOutFile = fso.CreateTextFile("results.txt",True)
Dirname = tb2.value
Searchterm = tb1.value
ProcessFolder DirName
End Sub
Sub ProcessFolder(FolderPath)
On Error Resume Next
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
Set contents = thing.OpenAsTextStream
If err.number = 0 then
Linenum = 0
Do Until contents.AtEndOfStream
line = contents.readline
Linenum = Linenum + 1
Test = Instr(line, searchterm)
If Isnull(test) = false then If Test > 0 then ObjOutFile.WriteLine LineNum & " " & thing.path
Loop
Else
err.clear
End If
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
ProcessFolder thing.path
Next
End Sub
Sub Init
On Error Resume Next
Set WshShell = CreateObject("WScript.Shell")
tb1.value = WshShell.RegRead("HKCU\Software\StackOverflow\VBS\Searchterm")
tb2.value = WshShell.RegRead("HKCU\Software\StackOverflow\VBS\Directory")
End Sub
</script>
</head>
<body Onload=Init>
<p><INPUT Name=tb1 TYPE=Text Value="Search">
<p><INPUT Name=tb2 TYPE=Text Value="Folder"> <INPUT NAME="Browse" TYPE="BUTTON" VALUE="Browse" OnClick=Browse>
<p><INPUT NAME="Search" TYPE="BUTTON" VALUE="Search" OnClick=Search>
</body>
</html> | unknown | |
d14909 | val | The this in your function in the setInterval isn't the this from ComponentWillMount .. that's why it fails. Do something like:
var that = this;
before you call setInterval and then
that.setState()
You can read more about the this keyword here. | unknown | |
d14910 | val | Its as simple as that, you can use your code and just do one thing extra here
String.format("%06d", number);
this will return your number in string format, so the "0" will be "000000".
Here is the code.
public static String getRandomNumberString() {
// It will generate 6 digit random Number.
// from 0 to 999999
Random rnd = new Random();
int number = rnd.nextInt(999999);
// this will convert any number sequence into 6 character.
return String.format("%06d", number);
}
A: If you need a six digit number it has to start at 100000
int i = new Random().nextInt(900000) + 100000;
Leading zeros do not have effect, 000000 is the same as 0. You can further simplify it with ThreadLocalRandom if you are on Java 7+:
int i = ThreadLocalRandom.current().nextInt(100000, 1000000)
A: 1 + nextInt(2) shall always give 1 or 2. You then multiply it by 10000 to satisfy your requirement and then add a number between [0..9999].
already solved here
public int gen()
{
Random r = new Random( System.currentTimeMillis() );
return ((1 + r.nextInt(2)) * 10000 + r.nextInt(10000));
}
A: i know it’s very difficult but you can do something like this:
create a class for BinaryNumber;
create a constructor that generate a char[] of 6 character where every single one is generated with a randomiser from 0 to 1
override the toStrig() method so that it will return the digits char[] as a string if you want to display it. then crate a method toInt() that esaminate the string char by char with a for and turn it in a decimal base number by multiplying current digit to 10 to the pow of i:
char[] digits = {‘1’ , ‘0’ , ‘1’ , ‘1’ , ‘0’ , ‘1’};
//random
int result = 0;
for( int i = 0; i < digits.length; i++) {
result += Integer.parseInt(digits[i]) * Math.pow(10, i);
}
return result;
A: This is the code in java which generate a 6 digit random code.
import java.util.*;
public class HelloWorld{
public static void main(String []args)
{
Random r=new Random();
HashSet<Integer> set= new HashSet<Integer>();
while(set.size()<1)
{
int ran=r.nextInt(99)+100000;
set.add(ran);
}
int len = 6;
String random=String.valueOf(len);
for(int random1:set)
{
System.out.println(random1);
random=Integer.toString(random1);
}
}
} | unknown | |
d14911 | val | For demonstration only, don't do this
As @Abra said, you need to call the open method:
import javax.sound.midi.*;
public class MiniMusicApp {
public static void main(String[] args){
MiniMusicApp mini = new MiniMusicApp();
mini.play();
}//Close main
public void play(){
try{
Sequencer player = MidiSystem.getSequencer();
player.open();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, 44, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
player.setSequence(seq);
player.start();
}catch(Exception ex){
ex.printStackTrace();
}
}//close play
}//close class
However you should also close it at the end:
import javax.sound.midi.*;
public class MiniMusicApp {
public static void main(String[] args){
MiniMusicApp mini = new MiniMusicApp();
mini.play();
}//Close main
public void play(){
Sequencer player = null;
try{
player = MidiSystem.getSequencer();
player.open();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, 44, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
player.setSequence(seq);
player.start();
}catch(Exception ex){
ex.printStackTrace();
}
finally {if(player!=null) player.close();}
}//close play
}//close class
The correct way
But this way is error prone, so in modern Java you should use try-with-resource to close it automatically:
import javax.sound.midi.*;
public class MiniMusicApp {
public static void main(String[] args){
MiniMusicApp mini = new MiniMusicApp();
mini.play();
}//Close main
public void play(){
Sequencer debug = null; // just for demonstrating that it is really closed at the end
try(Sequencer player = MidiSystem.getSequencer())
{
debug = player;
player.open();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, 44, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
player.setSequence(seq);
player.start();
}catch(Exception ex){
ex.printStackTrace();
}
System.out.println(debug.isOpen());
}//close play
}//close class
A: You forgot to open the Sequencer, which is why you got an exception. To open the player
Sequencer player = MidiSystem.getSequencer();
player.open(); | unknown | |
d14912 | val | It is the design pattern of java. We cannot write any code after return statement. If you are trying to compile with this code, compilation will fail. It is same for throwing exception.
This is because after return or throwing exception statement the control will goes to the caller place. So those lines cannot be executed.
In your case you must return some Boolean values.
Code should be like this,
public static boolean debug(int a, int b) {
boolean flag = false;
if(a+b == 12) {
flag = true;
}else if(a+b == 18){
flag = false;
}
a = 8;
return flag;
}
A: You don't have any code after a return. The warning is saying you're missing a return
Note: It's not recommended to alter your parameters a = 8;, but if neither your if statements are entered, you must return something. In this case true or false after that line
You might also want to capture the result of debug(4, 5);
A: The compiler is trying to tell you (in its own way) that the else case (a+b != 12 && a+b != 18) is falling through to the a=8 line and that branch of code is missing a return statement.
Java compiler is extremely smart with program flow analysis, so when it tells something is wrong then something is indeed wrong.
A: Every possible execution path should end with a return statement.
In this case, not all your paths return a value. If a+b is neither 12 nor 18, it'll fall through to the line a=8. That is not followed by a return statement, it just falls through to the end of the method. The compiler doesn't know what it should return in this case, so it issues an error.
A: Think what happens if you call debug(0, 0). Neither of the if statements are executed so the debug method is not returning nothing.
You must return some boolean value in each possible ramification.
A: What will return if the both the if the condition fails?. The code is not returning anything if both if the condition fails. So you should return something for that. You must return value for every condition possible.
A: Return will be the last statement of your method if you want to return any value. Your method need to return some value here.
Lets take a scenario : What if both your if else condition is wrong then what will your method return.
A: you can write a =8; inside else block. | unknown | |
d14913 | val | Auto-layout makes multiple "passes" when laying out the UI elements for Collection views (and Table views).
Frequently, particularly when using variable-sized cell content, auto-layout will throw warnings as it walks its way through the constraints.
Probably the easiest way to get rid of that warning is to give your Aspect Ratio constraint a Priority of less-than Required.
If you set it to Default High (750), that tells auto-layout it's allowed to "break" it without throwing the warning (but it will still be applied).
A: I had the same issue on a horizontal slider with dynamic item widths. I found the solution in my case which looks like a bug to me.
There are two functions to create a NSCollectionLayoutGroup. Using the other one fixed it for me.
This breaks my constraints:
let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitem: item, count: 1)
This doesnt:
let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitems: [item]) | unknown | |
d14914 | val | You are getting an IndexError because you are trying to access items in an unpopulated list. I imagine you are trying to fill out something more like this:
tours = [[],[],[]]
There are a few other problems here. You are indexing by integers starting from 1 it seems from your example of how each city is set up. You need to adjust for the offset. You don't need to iterate the indices of city.orders you really only need the values.
The below code requires hard coding the number of lists you will need to fill out. Easy if it is known, but annoying if it can change. The below code assumes there are 3 tours as in your example.
tours = [[],[],[]]
city = City.create(arrayCity)
for i in city.orders:
tours[i-1].append(city)
Ideally you might want a more dynamic set up where you don't have to specify the number of groups before hand:
tours = []
city = City.create(arrayCity)
for i in city.orders:
while len(tours) < i:
tours.append([])
tours[i-1].append(city)
The above code introduces a while loop that will add lists to tours if you have not yet created the sub-lists you are trying to fill out.
A: If you want list1 to contain Cities that have 1 in their order, you can test for that and take action:
if 1 in city.order:
list1.append(city)
Similarly
if 2 in city.order:
list2.append(city)
if 3 in city.order:
list3.append(city)
A: class City:
def __init__(self,name,x,y,orders):
self.name = name
self.x = x
self.y = y
self.orders = orders
City1 = City('City1',0.0,0.0,[1,2])
City2 = City('City2',1.0,0.0,[2,3])
City3 = City('City3',2.0,0.0,[1,3])
City4 = City('City4',3.0,0.0,[2])
list_cities = [City1, City2, City3, City4]
group_cities_by_orders = {}
for i in range(1,len(list_cities)+1):
for city in list_cities:
if i in city.orders:
if i in group_cities_by_orders:
group_cities_by_orders[i].append(city.name)
else:
group_cities_by_orders[i] = [city.name]
print(group_cities_by_orders)
Output:
{1: ['City1', 'City3'], 2: ['City1', 'City2', 'City4'], 3: ['City2', 'City3']} | unknown | |
d14915 | val | Unbounded Knapsack can be solved using 2D matrix, which will make printing the included items easy. The items included in the knapsack can be backtracked from the matrix in the same way as in 0/1 Knapsack.
After the dp[][] matrix is populated, this will print the included items:
// dp[val.length+1][sackWeight+1] is the matrix for caching.
// val[] is the array that stores the values of the objects
// and wt[] is the array that stores the weight of the corresponding objects.
int x = val.length, y = sackWeight;
while (x > 0 && y > 0) {
if (dp[x][y] == dp[x - 1][y])
x--;
else if (dp[x - 1][y] >= dp[x][y - wt[x - 1]] + val[x - 1])
x--;
else {
System.out.println("including wt " + wt[x - 1] + " with value " + val[x - 1]);
y -= wt[x - 1];
}
}
A: Assuming dp[][] is a matrix that is populated correctly.
We can backtrack to find selected weights
def print_selected_items(dp, weights, capacity):
idxes_list = []
print("Selected weights are: ", end='')
n = len(weights)
i = n - 1
while i >= 0 and capacity >= 0:
if i > 0 and dp[i][capacity] != dp[i - 1][capacity]:
# include this item
idxes_list.append(i)
capacity -= weights[i]
elif i == 0 and capacity >= weights[i]:
# include this item
idxes_list.append(i)
capacity -= weights[i]
else:
i -= 1
weights = [weights[idx] for idx in idxes_list]
print(weights)
return weights
For details on how to generate this DP array from bottom up DP.
def solve_knapsack_unbounded_bottomup(profits, weights, capacity):
"""
:param profits:
:param weights:
:param capacity:
:return:
"""
n = len(profits)
# base checks
if capacity <= 0 or n == 0 or len(weights) != n:
return 0
dp = [[-1 for _ in range(capacity + 1)] for _ in range(n)]
# populate the capacity=0 columns
for i in range(n):
dp[i][0] = 0
# process all sub-arrays for all capacities
for i in range(n):
for c in range(1, capacity + 1):
profit1, profit2 = 0, 0
if weights[i] <= c:
profit1 = profits[i] + dp[i][c - weights[i]]
if i > 0:
profit2 = dp[i - 1][c]
dp[i][c] = max(profit1, profit2)
# maximum profit will be in the bottom-right corner.
print_selected_items(dp, weights, capacity)
return dp[n - 1][capacity] | unknown | |
d14916 | val | You need to use the parameter mapping functionality of API Gateway to map the parameters from the incoming query string to a parameter passed to your Lambda function. From the documentation link you provided, it looks like you'll at least need to map the hub.challenge query string parameter, but you may also need the other parameters (hub.mode, hub.topic, and hub.verify_token) depending on what validation logic (if any) that you're implementing.
The first step is to declare your query string parameters in the method request page. Once you have declared the parameters open the integration request page (where you specify which Lambda function API Gateway should call) and use the "+" icon to add a new template. In the template you will have to specify a content type (application/json), and then the body you want to send to Lambda. You can read both query string and header parameters using the params() function. In that input mapping field you are creating the event body that is posted to AWS Lambda. For example: { "challenge": "$input.params('hub.challenge')" }
Documentation for mapping query string parameters | unknown | |
d14917 | val | If you setup gitcredentials (https://git-scm.com/docs/gitcredentials.html) you should be able to script all of it like that:
#!/bin/bash
echo "This is a shell script"
my_pass="awesomePassword"
server="awesomeServer"
sshpass -p $my_pass ssh $server "git status; git pull origin development; git checkout testing; git merge origin development"
(untested)
You will have to install sshpass and you should note that it is not really a good practice to hardcord passwords like that. Could be avoided by using user input. | unknown | |
d14918 | val | You can use subprocess :
# -*- coding: utf-8 -*-
import sys
import subprocess
from time import sleep
for x in range(1, 3):
subprocess.call('clear')
print('')
print('Some information #{0}'.format(x))
print('And a lot of different prints')
sleep(1)
A: An Unbutu solution would be to call reset:
for x in range(1, 3):
subprocess.call('reset')
print('Some information #{0}'.format(x))
print('And a lot of different prints')
sleep(1) | unknown | |
d14919 | val | As a general solution for manipulating HTML data, I would recommend :
*
*Loading it to a DOM document : DOMDocument::loadHTML
*Manipulating the DOM
*
*For example, here, you'll probably use DOMDocument::getElementById
*and DOMNode::removeChild
*Get the new HTML string, with DOMDocument::saveHTML
Note : it'll add some tags arround your HTML, as DOMDocument::saveHTML generates the HTML that corresponds to a full HTML Document :-(
A couple of str_replace to remove those might be OK, I suppose... It's not the hardest part of the work, and should work fine. | unknown | |
d14920 | val | Its a warning. If you need that permission (and it seems your app does), then you're fine. If you didn't really need it, you should remove it. Google isn't going to scan your description to see if you explain it, that level of AI isn't really possible yet. So you'll continue to get the warning. | unknown | |
d14921 | val | In these case you can use the instruction break:
Serial.println("got to assignment number finder");
for (int AssignCheck = 2; AssignCheck < 250; AssignCheck++){
Serial.println("Finding a good assignment number " + String(AssignCheck));
if (EEPROM.read(AssignCheck) == 255){ //Looks for a blank space which can be used to store the new card
if (EEPROM.read(AssignCheck + 1) == 255){
if (EEPROM.read(AssignCheck + 2) == 255){
if (EEPROM.read(AssignCheck + 3) == 255){
if (EEPROM.read(AssignCheck + 4) == 255){
Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ". Scanner value = " + String(Scanner));
int StoreValue = AssignCheck;
break;
}
}
}
}
}
}
As you can read here, it does exactly what you want.
Please note that your second attempt doesn't work because the for loop is inside the while: it completes before the whole for loop and, after, it compare the "scanner" variable of the while loop
You can correct it in this way:
Serial.println("got to assignment number finder");
int Scanner = 1;
for (int AssignCheck = 2; (AssignCheck < 250) && (Scanner == 1); AssignCheck++){
Serial.println("Finding a good assignment number " + String(AssignCheck) + ". Scanner value = " + String(Scanner));
if (EEPROM.read(AssignCheck) == 255){ //Looks for a blank space which can be used to store the new card
if (EEPROM.read(AssignCheck + 1) == 255){
if (EEPROM.read(AssignCheck + 2) == 255){
if (EEPROM.read(AssignCheck + 3) == 255){
if (EEPROM.read(AssignCheck + 4) == 255){
Scanner = 0;
Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ". Scanner value = " + String(Scanner));
int StoreValue = AssignCheck;
}
}
}
}
}
}
A: Reading EEPROM is expensive, please consider this:
Serial.println("got to assignment number finder");
int Scanner = 1;
char rollingBuffer[5];
rollingBuffer[0] = EEPROM.read(2 + 0);
rollingBuffer[1] = EEPROM.read(2 + 1);
rollingBuffer[2] = EEPROM.read(2 + 2);
rollingBuffer[3] = EEPROM.read(2 + 3);
rollingBuffer[4] = EEPROM.read(2 + 4);
pointRoll = 0;
for (int AssignCheck = 7; (AssignCheck < 255); AssignCheck++)
{
if ((rollingBuffer[0] == 255) && (rollingBuffer[1] == 255) && (rollingBuffer[2] == 255) && (rollingBuffer[3] == 255) && (rollingBuffer[4] == 255))
{
Serial.println("Found assignment numbers " + String(AssignCheck-5) + " through to " + String(int(AssignCheck-1)) + ". Scanner value = " + String(Scanner));
int StoreValue = AssignCheck;
break;
}
rollingBuffer[pointRoll] = EEPROM.read(AssignCheck);
pointRoll++;
if (pointRoll > 4) pointRoll = 0;
} | unknown | |
d14922 | val | The purpose of regular expressions is to describe the syntax of a language. These regular expressions can then be used to find strings that match the syntax of these languages. That’s it.
What you actually do with the matches, depends on your needs. If you’re looking for all matches, repeat the find process and collect the matches. If you want to split the string, repeat the find process and split the input string at the position the matches where found.
So basically, regular expression libraries can only do one thing: perform a search for a match. Anything else are just extensions.
A good example for this is JavaScript where there is RegExp.prototype.exec that actually performs the match search. Any other method that accepts regular expression (e. g. RegExp.prototype.test, String.prototype.match, String.prototype.search) just uses the basic functionality of RegExp.prototype.exec somehow:
// pseudo-implementations
RegExp.prototype.test = function(str) {
return RegExp(this).exec(str);
};
String.prototype.match = function(pattern) {
return RegExp(pattern).exec(this);
};
String.prototype.search = function(pattern) {
return RegExp(pattern).exec(this).index;
}; | unknown | |
d14923 | val | Try changing:
"<td style='width:10%; height:80px>  ; $counter</td>"
to:
"<td style='width:10%; height:80px'> $counter</td>" | unknown | |
d14924 | val | href is not a property of the global object. i believe you are looking for window.location.href:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Sample", "Callscript(window.location.href);", true);
A: You are not passing the href from aspx.cs file properly. It should be something like below.
Page.ClientScript.RegisterStartupScript(this.GetType(), "Sample", "Callscript('" + this.href + "');", true);
function Callscript(href)
{
alert(href);
}
Hope this Helps!!
A: "This" is two different things - it's one thing on the server and another on the client.
You may try modifying your startup script like so:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Sample", "Callscript('" + this.href + "');", true); | unknown | |
d14925 | val | Performance difference should be very small in your case, It may be big when your constructor has complex code inside it or multiple fields to be set. In general, it's good to practise keeping the constructor simple and doing the object initialization inside it.
When you are setting the field directly not in the constructor you are escaping from doing the things which the constructor does apart from setting this particular field.
your code should be readable, easily maintainable and scalable, so chose the approach accordingly.
If you are really concerned about the performance then you could do a benchmark and compare the results. | unknown | |
d14926 | val | This probably won't help with the initial problem at this point but it might save someone a few minutes.
The problem is that the sort method on hash freaks out if a hash has a mixture of symbol and string keys. Oauth adds some entries keyed by strings into the params hash. | unknown | |
d14927 | val | You forgot to call env.configure()
env = gym.make('flashgames.DuskDrive-v0')
env.configure(remotes=1)
observation_n = env.reset() | unknown | |
d14928 | val | Injecting a string to represent the file contents seems like it would be the most straightforward way of testing a class such as this. However, directly instantiating a QFile instance in your class constructor makes this impossible (in other words, it's impossible to inject your dependency). Moreover, it's quite a bit of work to create a "Fake" or "Mock" version of a QFile (a.k.a. a Test Double of a QFile).
The easiest way to resolve this is to pass a QIODevice into your class constructor (QFile inherits from QIODevice). In your unit test, you can fake the contents of the file by passing in a QIODevice with the contents you wish to test. In this case, you can accomplish this with a QBuffer, which allows you to arbitrarily set its contents. As such, your class would like something like the following:
class MyXmlParser
{
MyXmlParser(QIODevice* device);
...
};
Your unit test constructs the class with a QBuffer; your production code constructs it with a QFile.
Should I use a real XML file in my test?
Generally speaking, the more external dependencies your unit test has, the more costly it is to ensure that it doesn't break in the future (it potentially makes your unit test sensitive to its context). As such, it is advisable to avoid using a real XML file in order to ensure that your test is self-contained. Moreover, passing in a real XML means that you are now implicitly testing QFile as well as your XML parser (in other words, it's not longer a unit test, it's an integration test). You can generally assume that the IO device that you pass into your parser works; you only need to verify that your parser uses the IO device correctly and that it can parse the XML properly.
Consider reading through the material at xunitpatterns.com, particularly the section on Test Smells. | unknown | |
d14929 | val | If you have a predefined distribution of words in a pre-trained model you can just pass a bow_corpus through that distribution as a function. Gensims LDA and LDAMallet can both be trained once then you can pass a new data set through for allocation without changing the topics.
Steps:
*
*Import your data
*Clean your data: nix punctuation, numbers, lemmatize, remove stop-words, and stem
*Create a dictionary
dictionary = gensim.corpora.Dictionary(processed_docs[:])
dictionary.filter_extremes(no_below=15, no_above=0.5, keep_n=100000)
*Define a bow corpus
bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs]
*Train your model - skip if it's already trained
ldamallet = gensim.models.wrappers.LdaMallet(mallet_path,
corpus=bow_corpus, num_topics=15, id2word=dictionary)
*Import your new data and follow steps 1-4
*Pass your new data through your model like this:
ldamallet[bow_corpus_new[:len(bow_corpus_new)]]
*Your new data is allocated now and you can put it in a CSV | unknown | |
d14930 | val | Just add one static method as "getInstance()" to retreive the object of class main_activity, then you can use the object to call non-static methods.
jmethodID midGetInstance = (*env)->GetStaticMethodID(env, main_activity_class, "getInstance", "()Lcom/package/yourapp/MainActivity;");
jobject main_activity_obj = (*env)->CallStaticObjectMethod(env, main_activity_class, midGetInstance);
...NewGlobalRef(main_activity_obj);
where main_activity_class is the same of your original jclass main_activity.
On Java side, you need
onCreate(...) {mInstance = this;...}
public static MainActivity getInstance() {return mInstance;}
Then you can use main_acitivty_obj to access the non-static methods. | unknown | |
d14931 | val | Your example is not self contained, but I think you need to replace:
plt.axvline(x=4)
with:
ax.axvline(x=4)
You are adding the line to an axis that you are not displaying. Using plt. is the pyplot interface which you probably want to avoid for a GUI. So all your plotting has to go on an axis like ax.
A: matplotlib.pyplot.vlines
*
*The difference is that you can pass multiple locations for x as a list, while matplotlib.pyplot.axvline only permits one location.
*
*Single location: x=37
*Multiple locations: x=[37, 38, 39]
*If you're plotting a figure with something like fig, ax = plt.subplots(), then replace plt.vlines or plt.axvline with ax.vlines or ax.axvline, respectively.
import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(1, 21, 200)
plt.vlines(x=[37, 38, 39], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple')
plt.vlines(x=40, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single')
plt.axvline(x=36, color='b', label='avline')
plt.legend()
plt.show() | unknown | |
d14932 | val | *
*Take the first number from your list (e.g., 1).
*Remove this number from your list, as well as deduct it from your "destination" total.
*Now you have a new list and a new destination total. Repeat.
*If your total exceeds your destination, skip the current number (i.e., retain the number within the list, don't update the destination) and move to the next.
*If none of the remaining items in the list let you reach your destination, pop the last number you added to your destination total, and update it with the next number in the list.
*If you reach your destination total, you have a subset of numbers from your original list (with a size that is anything between 1 and the number of elements in the list) that add up to your intended total. | unknown | |
d14933 | val | First, you need to understand that Arduino serial terminal is not like a real terminal software It does not support a command sent on UART. So to achieve what you want you will require real terminal software such as putty. Which allows you to make changes by sending character bytes using UART communication.
//ADD these lines before printing on a serial terminal
Serial.write(27); // 27 is an ESC command for terminal
Serial.print("[2J"); // this will clear screen
Serial.write(27); // 27 is an ESC command for terminal
Serial.print("[H"); // move cursor to home
//now print what you want...
Serial.print("Vacant Spots: ");
Serial.println(vslots);
For more info and methods you can check this post here. But had tried everything and suggesting to go with putty.
A: The ln suffix in println stands for new line. That means println will "print" the value and a newline.
So as an initial solution you could change from using println to plain print:
Serial.print("Vacant Spots: ");
Serial.print(vslots); // Note: not println
Then we have to solve the problem of going back to the beginning of the line. to overwrite the old text. This is typically done with the carriate-return character '\r'. If we add it to the beginning of the printout:
Serial.print("\rVacant Spots: "); // Note initial cariage-return
Serial.print(vslots); // Note: not println
Then each printout should go back to the beginning of the line, and overwrite the previous content on that line.
To make sure that each line is equally long, you could use e.g. sprintf to format the string first, and then write it to the serial port:
char buffer[32];
// - for left justification,
// 5 for width of value (padded with spaces)
sprintf(buffer, "\rVacant Spots: %-5d", vslots);
Serial.print(buffer); | unknown | |
d14934 | val | If you use a cloud provider, the answer is to use Packer to create an image for each build, and then deploy images as needed. If you use bare metal, then you can easily use either normal attributes or roles to setup the versions. I'd suggest attributes.
*
*Set node['myapp']['test_version'] = 'some version' on the nodes to be updated
*In your recipe, check the value of that attribute. If set, then install that version, otherwise install your master version.
To remove a node from the experiment, you can just reset that attribute to nil on the node. The next chef run will result in that node going back to the master version.
If you want a way to install the master version on ALL nodes, including ones that are in experiments, you can either write a second recipe that ignores the setting, or you can add an override attribute like node['myapp']['force_master'] or such. You could then set that on the environment to override the experiments. But you'd need to remember to reset it at a later time. | unknown | |
d14935 | val | You must specify figsize together with dpi to get the plot big enough and has proper resolution. For the text's size, specify smaller font_size. For example, the relevant code is as follows:-
fig, ax = plt.subplots(figsize=(12,9), dpi=360)
nx.draw(G, with_labels=True, node_size=node_sizes, font_size=4) | unknown | |
d14936 | val | when you put somthing like "cclks" in your textbox, your validation will also not happen or?
if not then you have some sort of "numeric only textbox" and if you have such a textbox you can go further and create a "integer numeric only textbox"
i always use string properties in my viewmodels so i can easily validate all input, but of course i have to cast to the real type for my models | unknown | |
d14937 | val | It sounds like eclipse is aware of your dependency on this class and is able to add it to the classpath for you. What you need is a way to add the dependency to the classpath when you run it outside of eclipse. To fix this, ensure the class org.apache.logging.log4j.jul.LogManager is on the classpath. This can be done with -cp and the path to the jar file. For example if you have a class com.org.Main you are trying to run.
java -cp your.jar:log4j-jul-2.3.jar com.org.Main
your.jar is the jar containing your application and log4j-jul-2.3.jar is the jar containing the missing class. | unknown | |
d14938 | val | Actually I needed the feature so badly too that I have decided to make an OSX utility to do so. BUT... then I found a utility in the Mac Appstore that (partially) solves this problem (it was free for some time, I do not know its current state). Its called JSONModeler and what it does is parsing a json tree and generates the coredata model and all derived NSManagedObject subclasses automatically. So a typical workflow would be:
*
*Export the tables from MySQL to xml
*Convert the xml to json
*Feed the utility with that json and get your coredata model
Now, for a more complicated scenario (relationships etc) I guess you would have to tweak your xml so it would reflect a valid object tree. Then JSONModeler will be able to recreate that tree and export it for coredata.
A: The problem here is that entities are not tables and properties are not columns. Core Data is an object graph management system and not a database system. The difference is subtle but important. Core Data really doesn't have anything to do with SQL it just sometimes uses SQL as one its persistence options.
Core Data does use a proprietary sqlite schema and in principle you can duplicate that but I don't know of anyone who has succeeded in a robust manner except for very simple SQL databases. Even when they do, its a lot of work. Further, doing so is unsupported and the schema might break somewhere down the line.
The easiest and most robust solution is to write a utility app to read in the existing DB and create the object graph as it goes. You only have to run it once and you've got to create the data model anyway so it doesn't take much time. | unknown | |
d14939 | val | It's perfectly possible to write a ForEach extension method for IEnumerable<T>.
I'm not really sure why it isn't included as a built-in extension method:
*
*Maybe because ForEach already existed on List<T> and Array prior to LINQ.
*Maybe because it's easy enough to use a foreach loop to iterate the sequence.
*Maybe because it wasn't felt to be functional/LINQy enough.
*Maybe because it isn't chainable. (It's easy enough to make a chainable version that yields each item after performing an action, but that behaviour isn't particularly intuitive.)
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
foreach (T item in source)
{
action(item);
}
} | unknown | |
d14940 | val | Why does it not work? Because you are resolving the promise before the asynchronous method runs. The reason why the object shows the value is the console lazy loading the object.
What do you do? Move the resolve line after the for loop inside the callback.
refReview.on("value", function(snap) {
var data = snap.val();
for (var key in data) { //data retrieved must be REVIEWEE NAME, REWIEVER NAME, RATING, ,CONTENT
Collect.push({
"RevieweeName": data[key].revieweeID.firstname.concat(" ", data[key].revieweeID.lastname),
"ReviewerName": data[key].reviewerID.firstname.concat(" ", data[key].reviewerID.lastname),
rating: data[key].rating,
content: data[key].content
})
} //end of for loop
resolve(); < --RIGHT
}); //end of snap
// resolve(); <-- WRONG
Ideally with a promise you do not use global variables, you pass the value through the resolve.
var myPromise = new Promise(function(resolve, reject) {
var str = "Hello!";
resolve(str);
});
myPromise.then(function(value) {
console.log(value);
}); | unknown | |
d14941 | val | Found a simple way without the need to change web.xml:
I changed the static "html" files to "htm". | unknown | |
d14942 | val | This would give you the node names for the children of the first ID node:
DECLARE @x xml
SET @x = '<ROOT>
<IDS>
<ID>
<NAME>bla1</NAME>
<AGE>25</AGE>
</ID>
<ID>
<NAME>bla2</NAME>
<AGE>26</AGE>
</ID>
</IDS>
</ROOT>'
SELECT T.c.value('local-name(.)', 'varchar(50)')
FROM @x.nodes('/ROOT/IDS/ID[1]/*') T(c) | unknown | |
d14943 | val | You should not need to import FirebaseDatabasePlugin in your plugin. There are no public APIs of the Java FirebaseDatabasePlugin class for you to call. Instead, you can import the Firebase native classes directly, and add a dependency on the Firebase libraries in the build.gradle of your plugin. Just use the same build.gradle values that the firebase_database plugin does. | unknown | |
d14944 | val | You will need a separate IP address for every user, right? Which doesn't sound like a very scalable solution, but if you do decide to do this you will then need as many IP addresses as you have users, and tell JBoss to listen to all interfaces using a startup argument like bin/run.sh -b 0.0.0.0. Then, your Servlets will be able to tell the full IP address by checking (eg) HttpServletRequest#getRequestUrl(). Or, you could have a separate instance of JBoss running for each user, binding each one to a different IP.
However, this is a very unusual design. It offers poor scalability, difficult maintenance, difficult network config and sysadmin tasks, and confusion for any new devs on the project. Appservers are designed to be able to serve multiple users on the same instance. I can't really see any positives to a design like this. Unless you have very good reasons for doing so (in which case please share!) you should probably use different URLs for different users, like:
http://192.168.11.21/MBeanProject/user1/servcount
http://192.168.11.21/MBeanProject/user2/servcount
or
http://192.168.11.21/MBeanProject/servcount?user=user1
http://192.168.11.21/MBeanProject/servcount?user=user2 | unknown | |
d14945 | val | It's related to the baseline of the element. An empty inline-block will have its bottom edge as the baseline:
The baseline of an 'inline-block' is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its 'overflow' property has a computed value other than 'visible', in which case the baseline is the bottom margin edge. ref
So in both cases the baseline is not the same.
To better understand consider some text next to your inline-block element to see how baseline is creating that space:
.box {
height: 100px;
width: 100px;
display: inline-block;
background: red;
}
<div style="border:2px solid">
<div class="box block">
<p>hello</p>
</div>
pq jy
</div>
<div style="border:2px solid">
<div class="box block">
</div>
pq jy
</div>
I think the above is self-explanatory. I have used descender letter to understand why we need that bottom space.
If you change the alignment, which is the common solution provided in most of the question, you will no more have that space:
.box {
height: 100px;
width: 100px;
display: inline-block;
background: red;
vertical-align:top; /* or bottom or middle */
}
<div style="border:2px solid">
<div class="box block">
<p>hello</p>
</div>
pq jy
</div>
<div style="border:2px solid">
<div class="box block">
</div>
pq jy
</div> | unknown | |
d14946 | val | There might be some problem with your jquery file inclusion. Your code is working absolutely fine with me. I tried your code by saving it in a new php file as follows.
<?php
sleep(1);
$mail_reg = '/^(?i)(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9] {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/';
$return = array();
$mesaj = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (empty($_POST['inputName']) || is_numeric($_POST['inputName'])) {
$mesaj = "Please enter your name!";
$return['error'] = true;
$return['msg'] = 'oops'.$mesaj;
echo json_encode($return);
exit();
} elseif (empty($_POST['inputEmail']) || !preg_match($mail_reg, $_POST['inputEmail'])) {
$mesaj = "Please enter your e-mail!";
$return['error'] = true;
$return['msg'] = 'oops'.$mesaj;
echo json_encode($return);
exit();
} elseif (empty($_POST['inputMess'])) {
$mesaj = "Please tell us something";
$return['error'] = true;
$return['msg'] = 'oops'.$mesaj;
echo json_encode($return);
exit();
} else {
$return['error'] = false;
$return['msg'] = 'Thank you for getting in touch. We will contact you!';
echo json_encode($return);
exit();
}
}
?>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label for="inputName">Your name</label>
<input type="text" name="inputName" class="form-control" id="inputName" placeholder="Name">
</div>
<div class="form-group">
<label for="inputEmail">Your e-mail</label>
<input type="text" name="inputEmail" class="form-control" id="inputEmail" placeholder="E-mail">
</div>
<div class="form-group">
<label for="inputMess">Your message for us</label>
<textarea name="inputMess" class="form-control" id="inputMess"></textarea>
</div>
<button type="submit" name="send" class="btn btn-default">Send</button>
</form>
<div id='mess'></div>
<script>
$(document).ready(function() {
var email_reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;
$('form').submit(function(event) {
event.preventDefault();
if ($('#inputName').val() == '' || $('#inputName').val().length < 2 || !isNaN($('#inputName').val())) {
alert('Please enter your name');
} else if (!email_reg.test($('#inputEmail').val())) {
alert('Please enter a valid e-mail adress');
} else if ($('#inputMess').val() == '' || !isNaN($('#inputMess').val())) {
alert('Please tell us something');
} else {
var formData = $('form').serialize();
submitForm(formData);
}
})
function submitForm(formData) {
$.ajax({
type: 'POST',
url: $('form').action,
data: formData,
dataType: 'json',
cache: false,
timeout: 7000,
success: function(data) {
$('#mess').text(data.msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#mess').text('A communication error occured');
},
complete: function(XMLHttpRequest, status) {
//$('form')[0].reset();
}
})
}
})
</script>
</body>
</html>
Output:
A: Try add header('Content-Type: application/x-javascript'); in php before outputing the json string. | unknown | |
d14947 | val | You can convert your string to NSURL and access its query and fragment properties:
if let url = NSURL(string: "https://www.google.co.jp/search?hl=ja&q=test#q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d"), query = url.query, fragment = url.fragment {
print(query) // "hl=ja&q=test\n"
print(fragment) // "q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d\n"
} | unknown | |
d14948 | val | The JLS says,
"The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C."
http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.8
When you declared a variable of the raw interface type, you forced the member methods to have raw types also. That's what screwed up the class cast.
The documentation rules.
A: Here:
PluginDriver driver = DriverManager.getDriver(transformer.getPlugin());
You are creating a raw type. Bad idea.
Can lead to all sorts of problems - see here.
Thus the answer is simple: never do that! When you are using generic types, then make sure that you have a "generic" on (one/both) sides of your declaration/definition! | unknown | |
d14949 | val | if the ProjectIssues or PostJobContext have no data you are looking for, you can use the web API rest:
WsRequest wsRequest = new GetRequest("api/...");
but beware the last measures will not be computed at the moment of @BatshSide, you have to wait for the Compute Engine to finish his work. So as you cannot wait in 'BatchSide', look for moving your plugin under @ComputeEngineSide | unknown | |
d14950 | val | Your error is saying you have a list object, not an instance of your class that you've tried to call your function on.
I suggest making your class actually hold the list, and the add function take the info you want
You don't need a parameter for the list, at that point.
class Car():
def __init__(self, brand, year):
self.brand = brand
self.year = year
def __repr__(self):
return self.brand + "," + str(self.year)
class CarList():
def __init__(self):
self.cars = []
def dump(self):
return str(self.cars)
def add(self, brand, year):
self.cars.append(Car(brand, year))
carList1 = CarList()
carList1.add('honda', 2009)
print(carList1.dump()) | unknown | |
d14951 | val | setWidget sets the widget for the scroll are, and that is why the code you have doesn't work since it removes the previous widget from the scroll area, and sets the new label as the scroll area widget.
You need to create a new instance of QLabel, and add it to the layout of the scroll area widget, which is self.verticalLayout for the above class.
def add_new_label(self):
newLabel = QtWidgets.QLabel('Hello World')
self.verticalLayout.addWidget(newLabel)
The code to create new label and assign it class instance attribute as self.label_99 = QtWidgets.QLabel() is useless in your case. You just need to create a local variable to hold the label, and finally add it to the scroll area's widget's layout. | unknown | |
d14952 | val | Form my experience is better recall a (re)initilizeMap() function when you click the tab for show the map.
Due the problem/difficulties related to the correct congfiguration of the map in this case if you, wher click the tab for show the map call the initializzazion of the map. the problem is structurally solved. | unknown | |
d14953 | val | Try to Gradle Clean and Rebuild and Sync all Gradle files. After that restart Android Studio, and go to:
When you create the style incorrectly or from an existing style, this problem usually occurs. So select the "Graphical Layout" select "AppTheme"-->The tab with a blue star. And select any of the predefined style. In my case "Light" which should resolve the problem.
In case still the problems remain just temporary remove <item name="cardStyle">@style/CardView.Light</item> from your theme and give a try. | unknown | |
d14954 | val | Found a solution, posting it here in case someone is interested.
In Python 3, the run method allows to get the output.
Using the parameters as shown in the example, TimeoutExpired returns the output before the timeout in stdout:
import subprocess as sp
for cmd in [['ls'], ['ls', '/does/not/exist'], ['sleep', '5']]:
print('Running', cmd)
try:
out = sp.run(cmd, timeout=3, check=True, stdout=sp.PIPE, stderr=sp.STDOUT)
except sp.CalledProcessError as e:
print(e.stdout.decode() + 'Returned error code ' + str(e.returncode))
except sp.TimeoutExpired as e:
print(e.stdout.decode() + 'Timed out')
else:
print(out.stdout.decode())
Possible output:
Running ['ls']
test.py
Running ['ls', '/does/not/exist']
ls: cannot access '/does/not/exist': No such file or directory
Returned error code 2
Running ['sleep', '5']
Timed out
I hope it helps someone. | unknown | |
d14955 | val | Add a drop callback to the droppables and apply the style changes necessary. Because right now the item is still positioned absolutely it will not recognize your center css.
Something like this: WRONG (see below)
drop: function(ev, ui) {
$(this).css({position: 'static'})
}
I updated the fiddle. I was wrong before. this is the droppable, and ui.draggable is the draggable.
drop: function(ev, ui) {
$(this).append(ui.draggable.css('position','static'))
} | unknown | |
d14956 | val | If the client will never make requests to the server and the server will be doing all the pushing, then you should use server-sent events.
However, for a chat application, because clients need to constantly send requests to the server, the WebSocket API is the natural choice.
The "polyfills" for the WebSocket API are other technologies that mimic a socket connection in a much less efficient manner, like, for example, Ajax long polling.
WebSocket libraries like Socket.IO are designed to use the WebSocket API when available and fall back to other technologies like Ajax long polling when the WebSocket API is not available.
Certain server side languages also handle resources differently. For example, PHP will require 1 process per socket connection, which can fill a thread limit quickly, whereas NodeJS (IIRC) can loop through the connections and handle them all on 1 thread. So how the language handles resources given your chosen solution should be considered as well.
A: First of all think about compatibility.
SSE: http://caniuse.com/#feat=eventsource
IE: no support
Firefox: Version 6+
Opera: Version 11+
Chrome: Unknown version +
Safari: Version 5.1+
WebSocket: (protocol 13) http://caniuse.com/#feat=websockets
IE: Version 10+
Firefox: Version 11+
Opera: Version 12.1+
Chrome: Version 16+
Safari: Version 6+
I know a lot of modules that works with WebSockets (including one made by me simpleS, I made a simple demo chat to show how should the connections be organized in channels, give it a try), and a bit lesser those which works with SSE, I guess that the last ones are less tested and you cannot rely to much on them in comparison with modules that works with WebSockets.
You can find mode information about the WebSockets and SSE here: WebSockets vs. Server-Sent events/EventSource
A: there is a polyfill - https://github.com/Yaffle/EventSource (IE8+)
and example of chat - https://github.com/Yaffle/EventSource/blob/master/tests/server.js | unknown | |
d14957 | val | As I mentioned in my comment to make the value labels bold use geom_text(..., fontface = "bold") and to make the axis labels bold use axis.text.x = element_text(angle=0, hjust=.5, face = "bold").
Using a a minimal reproducible example based on the ggplot2::mpg dataset:
library(ggplot2)
library(dplyr)
# Create exmaple data
md.df2 <- mpg |>
count(Group.1 = manufacturer, name = "value") |>
mutate(
variable = value >= max(value),
Group.1 = reorder(Group.1, -value)
)
ggplot(md.df2, aes(x = Group.1, y = value, group = variable, fill = variable)) +
geom_col(color = "black", position = "dodge") +
geom_text(aes(label = value), vjust = -0.3, size = 4, position = position_dodge(0.9), fontface = "bold") +
labs(x = "Species", y = "Values", title = "Order variables in barplot") +
theme_bw() +
theme(
text = element_text(size = 16),
axis.text.x = element_text(angle = 90, vjust = .5, face = "bold"),
plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)
)
A: In addition to @stefan 's answer, you can also set tick length and thickness like so:
## ... plot code +
theme(## other settings ...,
axis.ticks = element_line(linewidth = 5),
axis.ticks.length = unit(10, 'pt'))
However, the example "phenotype conditions" will probably remain hard to appraise, regardless of optimization on the technical level. On the conceptual level it might help to display aggregates, e. g. condition counts per Frequency and supplement a textual list of conditions (sorted alphabetically and by Frequency, or the other way round) for those readers who indeed want to look up any specific condition. | unknown | |
d14958 | val | You are right, you should be using the new operator. Aside from that, it looks like you're trying to make this some type of factory hybrid. I suggest the following.
Use a Constructor Function
Include an optional configuration that you can use when creating the object.
var Element = function (initialConfig) {
if (initialConfig) {
this.create(initialConfig);
}
};
Add to the Prototype
All your shared Element members should be part of the prototype.
Element.prototype = {
aArguments: {
"id" : false,
"name" : false,
"type" : false,
"title" : false,
"style" : false,
"action" : [],
"parent" : false,
"children" : {},
},
create:function ($aPassArguments) {
for (var prop in this.aArguments)
if (prop in $aPassArguments)
this.aArguments[prop] = $aPassArguments[prop];
return this;
},
append: function () {
$argList = arguments;
for ($i = 0; $i < $argList.length-1; $i++)
if (typeof $argList[$i]=="string")
this.setChild(this.importDB($argList[$i],true));
else
this.setChild($argList[$i]);
return this;
},
setChild: function($oChild) {
this.aArguments["children"][this.aArguments["children"].length-1]=$oChild;
},
getInfo: function($sKey) {
return this.aArguments[$sKey];
}
};
Examples
Your examples should now work as you expected. Notice that you can't call new Element.create() as that would treat Element.create as a constructor. Instead, pass your initial values into the constructor.
$set = new Element({"id": 1, "name" : "wrapper"}).
append(new Element({"id" : 3, "name" : "elm A"}));
alert($set.getInfo("name"));
Be Careful
You're not checking for own properties in your loops, omitting {}, and I spotted at least one implied global. JavaScript will bite you if you're not careful. Consider using JSLint or JSHint to help you spot these problems.
A: Your create function does not create any object, but rather changes on place the Element. aArguments object. Any strange thing might follow.
Anyway, just go for a clean and simple prototypal inheritance scheme, do not use $, remember to always declare your vars, and keep things simple :
function Element(initialValues) {
this.id = this.prototype.id++;
this.name = null;
this.type = null;
this.title = null;
this.style = null;
this.action = [];
this.parent = null;
this.children = [];
for (var prop in initialValues)
if (this[prop] != undefined) this[prop] = initialValues[prop];
}
Element.prototype = {
append: function () {
for (var i = 0; i < arguments.length - 1; i++) {
var thisElement = arguments[i];
if (typeof thisElement == "string") this.setChild(this.importDB(thisElement, true));
else this.setChild(thisElement);
}
return this;
},
setChild: function (child) {
this.children.push(child);
return this;
},
getInfo: function (key) {
return this[Key];
},
id: 0
}; | unknown | |
d14959 | val | Problem is that you pass the place_holder to the function getIndex.
You may transform your function in struct like that
template< typename Set, typename Index > struct getIndex
: mpl::integral_c<unsigned long long, ( mpl::distance<
typename mpl::begin<Set>::type,
typename mpl::find<Set, Index>::type
>::type::value )>
{
};
template <class Set, class PartialSet>
constexpr auto tupleBitset() {
using type =
typename mpl::fold<
PartialSet,
mpl::integral_c<unsigned long long, 0>,
mpl::eval_if<
mpl::has_key<Set, mpl::_2>,
mpl::plus<
mpl::_1,
mpl::shift_left<mpl::integral_c<unsigned long long, 1ull>,
getIndex<Set, mpl::_2>>
>,
mpl::_1
>
>::type;
return std::bitset<mpl::size<Set>::value>(type::value);
}
Demo | unknown | |
d14960 | val | An "upload key" isn't really anything special- it is just another key in a keystore. You need to register this key as an upload key in the developer console for Google to recognize it as your upload key.
To generate an upload key, simply follow the steps for generating a key and a keystor under "Generate a key and keystore" on the Sign Your App documentation. The key you generate there will be your upload key.
Once you have your upload key generated, you need to export it using
keytool -export -rfc -keystore upload-keystore.jks -alias upload -file upload_certificate.pem
where upload-keystore.jks is the name of the keystore containing the key you want to use as an upload key and upload is the alias of the key.
Finally, you need to go to your app in the developer console, go to Release Management > App signing, then click the "Upload Public Key Certificate" button to upload the .pem file you generated earlier. This registers your key an "upload key" for that app.
A: Maybe you mean for Google App Signing?
All process is same like before by creating your key from AndroidStudio, choose Build -> Generate Signed APK -> Create new -> Back -> Then follow the dialog process.
So where is the Google App Signing?
per the Help page, it's a security feature for developer if you lose your key.
If you lose your keystore or think it may be compromised, Google Play App Signing makes it possible to request a reset to your upload key. If you're not enrolled in Google Play App Signing and lose your keystore, you'll need to publish a new app with a new package name. | unknown | |
d14961 | val | Yes, the using blocks will always dispose the objects, no matter what. (Well, short of events like a power outage...)
Also, the disposing of the objects is very predictable, that will always happen at the end of the using block. (Once the objects are disposed, they are removed from the finalizer queue and are just regular managed objects that can be garbage collected, which happens when the garbage collector finds it convenient.)
In contrast, the Close calls will only be called if there are no unhandled exceptions inside the block. If you wanted them to surely be executed you would place them in finally blocks so that they are exected even if there is an exception. (That's what the using blocks are using to make sure that they can always dispose the objects.)
A: There are plenty of circumstances in which a using won't dispose of the resource in question. For example, if you pull the plug on the machine while the using is running, the finally block (which the using is translated to) won't run.
There is no situation in which the finally block wouldn't get run in which duplicating the same cleanup steps inside the using would be any better suited to handle.
A: If disputes like this ever come up, just fire up ILSpy (http://ilspy.net/) and peek inside the framework to see what it is actually doing on the Dispose that gets called from the end of the using statement.
In this case, you are right and all four of StringWriter, StringReader, XmlTextReader, and XmlTextWriter do their disposal work in the Dispose method and Close simply calls Dispose, so those four lines are redundant. (But note that StringWriter and StringReader don't seem to do anything interesting in their Dispose methods.) | unknown | |
d14962 | val | The actual limit seems to be 8192 bytes.
You have to check your Web.config in the system.serviceModel tag :
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
<message clientCredentialType="UserName" algorithmSuite="Default"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
You need to change maxStringContentLength="8192" to a greater value.
You may also make multiple requests instead of one to get the list of GUID page by page, using an offset parameter in each request. For example, to get list of GUID by pages of 200, first request with offset=0, second with offset=200, ... until you get less than 200 items.
A: I know it won't be of much help for you but I'd like to point out that the JSON spec does not set any limit; however, it allows parsers to do so:
An implementation may set limits on the size of texts that it
accepts. An implementation may set limits on the maximum depth of
nesting. An implementation may set limits on the range of numbers.
An implementation may set limits on the length and character contents
of strings.
RFC4627: The application/json Media Type for JavaScript Object Notation (JSON)
See if this answer applies to you. | unknown | |
d14963 | val | Possibly could be that it is looking through your text and say you have:
test \n
test
You then explode the words and you will get
"test<br />"
" test<br/>"
This is because of the space that you are not removing between the first word and the enter key or \n. Use the following and it should work fine for you:
foreach (explode("<br />", $text) as $ok) {
echo "944" . ltrim($ok) . "<BR />";
}
A: nl2br does not replace newline characters with <br />, it simply inserts them before newline characters. The existing newline characters may be causing you problems. You may have to write your own function. Something like:
function nl2br2($string) {
return str_replace(array("\r", "\n", "\r\n"), "<br />", $string);
}
Alternatively, you can just trim space off the resulting array as well.
foreach (array_map('trim', explode('<br />', nl2br2($text))) as $ok) {
echo "944". $ok ."<br />";
} | unknown | |
d14964 | val | Yes you can accomplish this. You'll need to use the DocuSign API and more specifically, the Embedding functionality which will allow you to sign through a webview or an iFrame on the mobile device.
With Embedding you can control the redirects URLs based on actions the user takes. For instance, if the user signs you can navigate to the Visual Force page in question. Or, if the user declines to sign then you can navigate them to a different page if you'd like. Same thing for if they hit the X to close the signing window.
To get started with learning DocuSign's APIs check out the DocuSign Developer Center:
http://www.docusign.com/developer-center
And for code samples of Embedded Signing in 6 different language stacks see the bottom 3 API Walkthroughs in the API Tools section:
http://iodocs.docusign.com/apiwalkthroughs | unknown | |
d14965 | val | this should work
$("#newsublevel").click(function() {
$(".navoptions").append('<div><select class="newoption"><option value="Home">Home</option><option value="Home">Home</option><option value="Home">Home</option><option value="Home">Home</option><option value="Home">Home</option></select><a href="#" class="remove">Remove</a></div>');
});
$(".navoptions").on('click','.remove',function() {
$(this).closest('div').remove()
});
i have added a container div element. on clicking the remove the code will find the container element and will remove only that
here is the updated jsfiddle http://jsfiddle.net/8ddAW/6/
A: Try this:
$(".navoptions").on('click','.remove',function() {
$(this).prev().andSelf().remove();
});
Fiddle Here
A: Try this out:- http://jsfiddle.net/adiioo7/8ddAW/4/
JS:-
$(function() {
$("#newsublevel").click(function() {
$(".navoptions").append('<div><br/><select class="newoption"><option value="Home">Home</option><option value="Home">Home</option><option value="Home">Home</option><option value="Home">Home</option><option value="Home">Home</option></select><a href="#" class="remove">Remove</a></div>');
});
$(".navoptions").on('click','.remove',function() {
$(this).parent().remove();
});
});
A: Actually, by using the fieldset element inside your form, you can perform grouping of all the <select> statements that you would like to be "related" and control them all at once. Even deeper, if you can keep track of the indexes of the groups that you're dynamically adding to, you could use those same indexes to clear them out without having to differentiate between them using unique classes. | unknown | |
d14966 | val | This answer might help: Create new dataframe in pandas with dynamic names also add new column
The approach suggested in the post would be to create a dictionary that would store the dataframe as the value and the stock ticker as the key.
df_dict = {}
for stock in tickers:
df = pdr.get_data_yahoo(tickers, start=start_date,end=end_date)
df_dict[stock] = df
Then you can iterate over the dictionary using the stock tickers as keys. | unknown | |
d14967 | val | If your trying to do a merge for a local branch use http://www.wdtutorials.com/drupal-7/github-windows-tutorial-3-branching-local-merging#.VYsBlRNVhBc
This is a pretty good github source for beginners.
http://rogerdudler.github.io/git-guide/
A: open terminal cd to your local root
git add .
git commit -m "your commit"
git push
This will move all of your local changes to master
*If you are working with someone else that has updated code you will need to do a git pull before the push | unknown | |
d14968 | val | Update : Modifying for generic size.
For step size of k, You can get size of List in O(n) or O(1) - depending upon C++ compiler. After that compute steps you're allowed to take by:
size_t steps_allowed = list.size()/k;
// list.size() is O(n) for C++98 and O(1) for standard C++ 11.
Then loop over another variable i and inside loop termination condition check for i against steps_allowed.
A: You can't advance past the .end() iterator. You have to use either a counter, or check all intermediate iterators. For example:
template<class It>
void checked_advance(It& it, It last, std::size_t n) {
while (n-- > 0 && it != last)
++it;
}
assert(!list.empty());
for (auto it = std::next(list.begin()); it != list.end();
checked_advance(it, list.end(), step)) {
// ...
}
A: You can change you condition to check and make sure the difference between the current iterator and the end iterator is more then the step amount. That would look like
for(auto list_it = std::next(list.begin());
std::distance(list_it, list.end()) > step;
std::advance(list_it, step))
{
// Do something
}
A: With range-v3, you might do:
for (auto& e : list | ranges::view::drop(1) | ranges::views::stride(2)) {
// e
} | unknown | |
d14969 | val | The hunk error normally came because it will not match the file lines. In this case you can do 2 things.
*
*Replace those mention error files with new same version Magento setup and then try to install the patch using SSH.
*Install the patch manually.
In this patch in front end only form key is added in checkout and cart files so you can do it manually.
Thanks.
A: I had a similar issue.
The solution for me was next:
*
*Check if you have 'downloader' folder in your project, if not (usually it is not under git) - download it (better from the current project, versions can be different);
*Revert the previous version of this patch (description of the patch - "Note that you must revert SUPEE-9767 version 1 before deploying version 2.")
($ bash ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh -R)
and after that try to patch 2nd version. | unknown | |
d14970 | val | Here's one option: merge. (Today is 27.05.2020 which is between start and end date stored in the abc table).
Sample data:
SQL> select * From abc;
FIN_C START_DATE END_DATE ACCOUNT_CLASS
----- ---------- ---------- -------------
F2018 27.05.2020 29.05.2020 2003
SQL> select * From xyz;
ACCOUNT_NO ACCOUNT_CLASS A
---------- ------------- -
1234 2003
Merge statement:
SQL> merge into xyz a
2 using (select account_class,
3 case when sysdate between start_date and end_date then 'Y'
4 else 'N'
5 end ac_no_dr
6 from abc
7 ) x
8 on (a.account_class = x.account_class)
9 when matched then update set a.ac_no_dr = x.ac_no_dr;
1 row merged.
Result:
SQL> select * From xyz;
ACCOUNT_NO ACCOUNT_CLASS A
---------- ------------- -
1234 2003 Y
SQL>
The bottom line: you don't need a procedure nor a loop (which is inefficient) as everything can be done with a single SQL statement.
If - as you commented - has to be a procedure, no problem either:
create or replace procedure p_merge as
begin
merge into xyz a
using (select account_class,
case when sysdate between start_date and end_date then 'Y'
else 'N'
end ac_no_dr
from abc
) x
on (a.account_class = x.account_class)
when matched then update set a.ac_no_dr = x.ac_no_dr;
end;
/ | unknown | |
d14971 | val | Use HTML Tidy library first to clean your string.
Also I'd better use DOMDocument instead of XMLReader.
Something like that:
$tidy = new Tidy;
$config = array(
'drop-font-tags' => true,
'drop-proprietary-attributes' => true,
'hide-comments' => true,
'indent' => true,
'logical-emphasis' => true,
'numeric-entities' => true,
'output-xhtml' => true,
'wrap' => 0
);
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();
$xml = $tidy->value; // Get clear string
$dom = new DOMDocument;
$dom->loadXML($xml);
... | unknown | |
d14972 | val | I recently found myself having to automatically move messages on an IMAP server from one folder to another.
To do this reliably, I wrote a script which I call imap-helper. It connects to an IMAP server and moves messages matching a given query string between two folders. It uses Mail::IMAPClient which is supplied by a package (perl-mail-imapclient) in my distribution (Arch).
In my coment on the original post I suggested using gnutls-cli to connect to your IMAP server; I still recommend doing this to get a grasp of what's happening behind the scenes (and so you can debug your query syntax more quickly). Here's an example raw IMAP session just for reference, but the script that follows it should be better suited for your problem.
*
*(The tool rlwrap provides GNU Readline editing and history to the interaction)
$ rlwrap -S "> " gnutls-cli imap.mail.yahoo.com -p 993
> A LOGIN myusername mypassword
A OK LOGIN completed
> A LIST "" * # List all the folders on the server
* LIST (\HasNoChildren) "/" "ALL"
* LIST (\Junk \HasNoChildren) "/" "Bulk Mail"
* LIST (\HasNoChildren) "/" "Inbox"
...
A OK LIST completed
> A SELECT Inbox
* 12 EXISTS
* 0 RECENT
...
A OK [READ-WRITE] SELECT completed; now in selected state
> A SEARCH BEFORE 01-Jan-2021
* SEARCH 11 12
A OK SEARCH completed
> A MOVE 11,12 "Bulk Mail"
* OK [COPYUID 1609256255 58:59 57:58]
...
A OK MOVE completed
As for the script, I have tested it on my Gmail Inbox which has 13000 messages. I moved them all from INBOX to INBOX2 (which Gmail created automatically). This took a couple of minutes. Then I moved them back again. I'd be glad to hear if it works on your server.
For your case what you'd do is first create a file called ~/.imap-creds.pl with your server, username, and password.
Then you'd run something like
$ imap-helper outlook FOLDER1 'SINCE "01-Jan-2019" BEFORE "01-Jan-2020"' FOLDER2 -e
to move all messages in FOLDER1 that were received in 2019, into FOLDER2. The user interface is designed so that you can build the command one argument at a time:
$ imap-helper # lists accounts from config file
gmail
...
$ imap-helper gmail # lists folders in the gmail account
INBOX
Personal
Receipts
...
$ imap-helper gmail INBOX # lists messages in INBOX
...
etc.
Here is the script:
#!/usr/bin/perl
# 21 Jan 2021
use warnings;
use strict;
use open (":encoding(UTF-8)", ":std" );
use Mail::IMAPClient;
use Data::Dumper;
$Data::Dumper::Indent=0;
$Data::Dumper::Purity=1;
$Data::Dumper::Terse=1;
use Getopt::Long;
Getopt::Long::Configure ("bundling", "no_ignore_case");
use Carp;
$SIG{__DIE__} = sub {
my $error = shift;
Carp::confess "Error: ";
};
# change the help text if you change this
my $credfn=glob("~/.imap-creds.pl");
my($bad_args, $help, $verbose, $execute, $max, $zero_results_ok);
GetOptions('-h|help' => \$help,
'-v|verbose' => \$verbose,
'-e|execute' => \$execute,
'-z|zero-results-ok' => \$zero_results_ok,
'-m|max=f' => \$max
) or $bad_args = 1;
my ($action);
my ($acct, $src, $dst, $query);
sub verb {
warn "imap-helper: ",@_,"\n" if $verbose;
}
if(@ARGV>4) {
warn "Expected 4 arguments but you passed ".scalar(@ARGV);
$bad_args = 1;
} elsif(@ARGV==4) {
$action = "move";
} elsif(@ARGV==3) {
$action = "search";
} elsif(@ARGV==2) {
$action = "list";
} elsif(@ARGV==1) {
$action = "folders";
} elsif(@ARGV==0) {
$action = "accounts";
}
($acct,$src,$query,$dst) = @ARGV;
sub usage {
"Usage: imap-helper [-h | -v | -e | -z] ACCOUNT SRC_FOLDER QUERY DST_FOLDER\n";
}
sub help {
q{
Options:
-h --help print this message
-v --verbose be verbose
-e --execute execute the move
-z --empty-search-ok exit 0 on empty search (for scripts)
By default no messages are moved, pass -e to execute the move.
Configuration: ~/.imap-creds.pl
Config syntax: [ SERVER_NAME => { Server => "HOST",
User => "USER",
Password => "PASS"
}, ... ]
With zero arguments, lists accounts. With only the ACCOUNT argument,
lists folders on ACCOUNT. With SRC_FOLDER argument, list contents of
SRC_FOLDER. With QUERY argument, list results of QUERY. With
DST_FOLDER argument, plan a move of messages matching QUERY from
SRC_FOLDER to DST_FOLDER. Pass "-e" to execute the move.
QUERY is an IMAP query, like "ALL" or 'BEFORE "15-Jan-2021"' (dates must
be in this exact format). Other keywords include TO, CC, FROM,
SUBJECT, TEXT; AND, OR, NOT; LARGER, SMALLER; NEW, RECENT, SEEN,
ANSWERED. See <https://tools.ietf.org/html/rfc3501> for a full list.
IMAP queries can be combined, for example:
$ imap-helper gmail INBOX 'SINCE "01-Jan-2020" BEFORE "01-Jan-2021"'
# (lists all INBOX messages from 2020)
This tool uses MOVE which is not part of the original IMAP RFC but
which should be well supported.
Example interaction:
$ cat .imap-creds.pl
[ yahoo =>
{ Server => 'imap.mail.yahoo.com',
User => 'napoleon',
Password => 'MYPASSWORD123'
},
gmail => ...
]
$ imap-helper
yahoo
gmail
$ imap-helper yahoo
ALL
Archive
Inbox
...
$ imap-helper yahoo Inbox
48 19 Jan 2021 [email protected] [email protected] test 2
...
$ imap-helper yahoo Inbox "BEFORE 15-Jan-2021"
50 29 Dec 2020 [email protected] [email protected] test 1
...
$ imap-helper yahoo Inbox "BEFORE 15-Jan-2021" Archive -e -v -z
imap-helper: Connecting to server imap.mail.yahoo.com as XXXXX
imap-helper: Searching for BEFORE 15-Jan-2021
imap-helper: Found 1 matches for BEFORE 15-Jan-2021
imap-helper: Moving 1 messages
};
}
if($bad_args) { print STDERR usage; exit(1) }
if($help) {
my $pager = $ENV{PAGER};;
open STDOUT, "| $pager" or warn "Not paging STDOUT: $!\n" if defined $pager;
print (usage, help);
close(STDOUT); wait(); exit(0);
}
die "Shouldn't get here" if !defined $action;
################################################################
## LOGIN
if(!-e $credfn) {
die "Missing credential file $credfn\n";
}
my $creds = eval `cat $credfn`;
#verb (Dumper($creds));
ref $creds eq "ARRAY" or die "Expected an array: $credfn\n".
"Got: ".(Dumper($creds))."\n";
if($action eq "accounts") {
# no account specified, just list them all
verb "Listing accounts from $credfn\n";
my $ind = 0;
my @accts = grep {!($ind++ % 2)} (@$creds);
print "$_\n" for(@accts);
exit(0);
}
my %creds = @$creds;
my $srvcr = $creds{$acct};
if(!defined $srvcr) {
die "Account $acct not found in $credfn\n";
}
verb "Connecting to server $srvcr->{Server} as $srvcr->{User}";
my $imap = Mail::IMAPClient->new(
Server => $srvcr->{Server},
User => $srvcr->{User},
Password => $srvcr->{Password},
Ssl => 1,
Uid => 1,
) or die "Could not connect to $srvcr->{Server} as $srvcr->{User}\n";
if($action eq "folders") {
my $folders = $imap->folders
or die "Error listing folders: ", $imap->LastError, "\n";
print join("\n",@$folders),"\n";
exit(0);
}
$imap->select( $src )
or die "Select $src error: ", $imap->LastError, "\n";
# Truncate a string $s to width $w, for use in a table
sub trunc {
my ($s, $w) = @_;
$s = "" if !defined($s);
if(ref $s eq "ARRAY") {
$s = join(",",@$s);
}
my $l = length($s);
my $o;
if($l>=$w) {
$o = substr($s,0,$w-3)."...";
} else {
$o = $s.(" "x($w-$l));
}
return $o;
}
sub show_msgs {
my @msgs = @_;
# this should but doesn't work (as first argument to parse_headers)
# my $r = $imap->Range(@msgs);
my $heads = $imap->parse_headers(\@msgs, "Date", "Subject", "To", "From");
# for my $msg (sort {$a <=> $b} (keys %$heads)) {
for my $msg (@msgs) {
my $hs = $heads->{$msg};
my $date = $hs->{Date}->[0]||"";
# remove weekday and HH:MM:SS from date
$date =~ s/^\D+,\s*//;
$date =~ s/ \d\d:.*$//;
print trunc($msg,7)," ",
trunc($date,12)," ",
trunc($hs->{To},25)," ",
trunc($hs->{From},25)," ",
trunc($hs->{Subject},25),
"\n";
}
}
if($action eq "list") {
my @msgs = $imap->messages;
if(defined($max) && @msgs>$max) { @msgs = @msgs[0..($max-1)]; }
show_msgs(@msgs);
exit(0);
}
verb "Searching for $query";
my @msgs = $imap->search($query);
if(!@msgs) {
if(!$zero_results_ok) {
die "Error or no matches for $query ",$imap->LastError,"\n";
} else {
verb "No matches found for $query";
exit 0;
}
}
verb "Found ".(@msgs)." matches for $query";
if(defined $max && @msgs > $max) { @msgs = @msgs[0..($max-1)]; }
if($action eq "search") {
show_msgs(@msgs);
exit(0);
}
if($action eq "move") {
verb "Moving ".(@msgs)." messages";
my $msgstr=join(",",@msgs);
if(!$execute) {
warn "Would have moved $msgstr from $src to $dst\n";
warn "Pass -e to execute move\n";
} else {
$imap->move($dst,$msgstr)
or die "Could not move messages\n";
}
exit(0);
}
die "Something wrong"; | unknown | |
d14973 | val | An index speeds up searching, at the expense of storage space. Think of the index as an additional copy of an attribute's (or column's) data, but in order. If you have an ordered collection you can perform something like a binary search, which is much faster than a sequential search (which you'd need if the data wasn't ordered). Once you find the data you need using the index, you can refer to the corresponding record.
The tradeoff is that you need the additional space to store the "ordered" copy of that column's data, and there's a slight speed tradeoff because new records have to be inserted in the correct order, a requisite for the quick search algorithms to work.
For details on mongodb indexing see http://www.mongodb.org/display/DOCS/Indexes. | unknown | |
d14974 | val | I made some attempts and finally got it working, but doing this logic below;
// date functionality
$(document).ready(function() {
var year = (new Date).getFullYear();
$('.input-daterange').datepicker({
format: "dd-mm-yyyy",
autoclose:true,
minDate: new Date(year, 0, 1),
maxDate:new Date(year, 11, 31)
});
}); | unknown | |
d14975 | val | check valid matrics sklearn.neighbors.VALID_METRICS['ball_tree'])
and use instead of cosine | unknown | |
d14976 | val | Try this i think it will work for you.
public class AnsTest {
public static void main(String[] args) {
try {
String url = "http://mail.google.com";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setReadTimeout(5000);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Request URL ... " + url);
boolean redirect = false;
// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
System.out.println("Response Code ... " + status);
if (redirect) {
// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
// open the new connnection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Redirect to URL : " + newUrl);
}
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
} | unknown | |
d14977 | val | Make your code a bit more DRY would save you a bit of time, in validating that your counter has a "real" value. For the rest, the onclick inside an html element is not encouraged anymore, you can just update your code like
// wait until the page has loaded
window.addEventListener('load', function() {
// get your elements once
const counterElement = document.querySelector('#counter1');
const signupButton = document.querySelector('.signupbutton');
// assign a click event to your button
signupButton.addEventListener('click', updateCounter);
// function to retrieve the counter from your localStorage
function getKeyOrDefault( key, defaultValue = 0 ) {
return localStorage.getItem( key ) || defaultValue;
}
function updateCounter( e ) {
let counter = parseInt( getKeyOrDefault( 'counter' ) );
counter++;
counterElement.innerHTML = counter;
localStorage.setItem( 'counter', counter );
e.preventDefault();
}
// set the initial value
counterElement.innerHTML = getKeyOrDefault( 'counter' );
} );
Ofcourse, don't forget to change your html, to remove the counter function from the html element like
<button class="signupbutton"> Yes I'm in!</button>
<div id="counter">
<p>Number of people that have signed up for the newsletter: </p>
<div id="counter1">0</div>
</div>
A sample of this code can be found on this jsfiddle (it is not here, as stackoverflow doesn't support localstorage)
Now, the only thing I am really worried about, is the text of your HTML, note that the localStorage will be a personal storage for all clients, so, if this is a website run from the internet, all persons who arrive there once will start with null (or 0) and just increase by 1 each time they click the button, you will be none the wiser, as it is localStorage.
Ofcourse, if you handle it on 1 computer, where people have to input their data, then you have at least some data stored locally, but still, this isn't a real storage you can do something with ;)
A: The code does work. However, you have to make sure, that the counter function is interpreted before the page has loaded. Put the JS at the end of the document head, or rewrite the onlick using addEventListener.
A: You should convert to integer ..
function counter() {
var elem = document.getElementById('counter1');
var count = localStorage.getItem('count');
if (count == null) {
count = 0;
}
count = parseInt(count);
count++;
localStorage.setItem('count', count);
elem.innerHTML = count;
}
console.log(localStorage.getItem('count'));
var count1 = localStorage.getItem('count');
var elem = document.getElementById('counter1');
elem.innerHTML = count1;
Please Try again
A: getItem/setItem are unavailable until didFinish will have executed unless
Read local storage data using WKWebView | unknown | |
d14978 | val | You can use the recode function of thedplyr package. Assuming the missing spots are NA' s, you can then subsequently set all NA's to "Other" with replace_na of the tidyr package. It depends on the format of your missing data spots.
mydata <- tibble(
id = 1:10,
coatcol = letters[1:10]
)
mydata$coatcol[5] <- NA
mydata$coatcol[4] <- ""
mydata <- mydata %>%
mutate_all(list(~na_if(.,""))) %>% # convert empty string to NA
mutate(Coatcolor_old = replace_na(coatcol, "Unknown")) %>% #set all NA to Unknown
mutate(Coatcolor_new = recode(
Coatcolor_old,
'spotted'= 'Spotted',
'bayspotted' = 'Spotted',
'old_name' = 'new_name',
'a' = 'A', #etc.
))
mydata | unknown | |
d14979 | val | .plan-box:last-child Selects last of plan.box element
.plan-box :last-child Selects last elements in all of plan.box elements
Css Selectors
A: It will select second .plan-box div in the HTML code.
See the Link here
Again you can easily select any child div with CSS .Example is Here
I have used here .plan-box:nth-child(2) {} for select second div. | unknown | |
d14980 | val | The application name that Task Manager shows is the Window text of the taskbar window. If you want to hide it you'll just have to set that text to an empty string.
If a blank string is no good, and you don't want your app to appear in the list at all, then don't register a taskbar button.
If you don't want your app to appear in the process list, then don't start it. | unknown | |
d14981 | val | You can do this:
function open(item: keyof typeof FormMapper) {
console.log(FormMapper[item]);
}
That way you restrict item values to be keys of the FormMapper class, and the compiler won't complain. | unknown | |
d14982 | val | Set dtype=float when you define A:
A = np.array([[eps, 1, 0], [1, 0, 0], [0, 1, 1]], dtype=float)
The reason you assignment failed was because you were assigning floats to an integer array.
Assigning integers to an integer slice works fine, as you noticed. | unknown | |
d14983 | val | If you are willing to upgrade to 2.1, then take a look at Espresso-Intents:
Using the intending API (cousin of Mockito.when), you can provide a response for activities that are launched with startActivityForResult
This basically means it is possible to build and return any result when a specific activity is launched (in your case the BarActivity class).
Check this example here: https://google.github.io/android-testing-support-library/docs/espresso/intents/index.html#intent-stubbing
And also my answer on a somewhat similar issue (but with the contact picker activity), in which I show how to build a result and send it back to the Activity which called startActivityForResult()
A: If meanwhile you switched to the latest Espresso, version 3.0.1, you can simply use an ActivityTestRule and get the Activity result like this:
assertThat(rule.getActivityResult(), hasResultCode(Activity.RESULT_OK));
assertThat(rule.getActivityResult(), hasResultData(IntentMatchers.hasExtraWithKey(PickActivity.EXTRA_PICKED_NUMBER)));
You can find a working example here.
A: this works for me:
@Test
fun testActivityForResult(){
// Build the result to return when the activity is launched.
val resultData = Intent()
resultData.putExtra(KEY_VALUE_TO_RETURN, true)
// Set up result stubbing when an intent sent to <ActivityB> is seen.
intending(hasComponent("com.xxx.xxxty.ActivityB")) //Path of <ActivityB>
.respondWith(
Instrumentation.ActivityResult(
RESULT_OK,
resultData
)
)
// User action that results in "ActivityB" activity being launched.
onView(withId(R.id.view_id))
.perform(click())
// Assert that the data we set up above is shown.
onView(withId(R.id.another_view_id)).check(matches(matches(isDisplayed())))
}
Assuming a validation like below on onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
data?.getBooleanExtra(KEY_VALUE_TO_RETURN, false)?.let {showView ->
if (showView) {
another_view_id.visibility = View.VISIBLE
}else{
another_view_id.visibility = View.GONE
}
}
}
I follow this guide as reference : https://developer.android.com/training/testing/espresso/intents and also i had to check this links at the end of the above link https://github.com/android/testing-samples/tree/master/ui/espresso/IntentsBasicSample
and
https://github.com/android/testing-samples/tree/master/ui/espresso/IntentsAdvancedSample
A: If you're using ActivityScenario (or ActivityScenarioRule) as is the current recommendation in the Android Developers documentation (see the Test your app's activities page), the ActivityScenario class offers a getResult() method which you can assert on as follows:
@Test
fun result_code_is_set() {
val activityScenario = ActivityScenario.launch(BarActivity::class.java)
// TODO: execute some view actions which cause setResult() to be called
// TODO: execute a view action which causes the activity to be finished
val activityResult = activityScenario.result
assertEquals(expectedResultCode, activityResult.resultCode)
assertEquals(expectedResultData, activityResult.resultData)
} | unknown | |
d14984 | val | Not at all? Sorry. You know, there are serious security implications allowing this. | unknown | |
d14985 | val | Please refer to the official How to migrate from Newtonsoft.Json to System.Text.Json.
There are 3.1 and 5 versions provided. Please note that in 3.1 you can install the 5.0 package to get the new features (for example deserializing fields). | unknown | |
d14986 | val | I can think of this solution:
# data:
dt <- structure(list(wl = 431:436,
ex421 = c(0.6168224, 0.6687435, 0.6583593, 0.6832814, 0.642783, 0.7393562),
wl = 321:326,
ex309 = c(0.1267943, 0.2416268, 0.4665072, 0.3576555, 0.2194976, 0.1866029),
wl = 301:306,
ex284 = c(0.06392694, 0.05631659, 0.05327245, 0, 0.12328767, 0.08675799),
wl = 361:366,
ex347 = c(0.15220484, 0.08961593, 0.13134187, 0.32432432, 0.50308203, 0.34660977)),
row.names = c(NA, -6L),
class = c("data.table", "data.frame"))
# get vectors with wl names
wls <- grep("wl", names(dt))
# get vectors with ex_numbers names
exs <- grep("ex", names(dt))
# reformat the data:
newDt <- cbind(stack(dt, select = wls), stack(dt, select = exs))
# Assign reasonable names:
names(newDt) <- c("wlNumber", "wlInd", "exValue", "exNumber")
Now the data is ready to be plotted with any command:
ggplot(newDt, aes(x = wlNumber, y = exValue, color = exNumber))+geom_point()+geom_line()
The main advantage of this approach is that you can have the table spread into many columns. It doesn't matter, as long as their name has "wl" on it ("ex" for the other variables).
A: Here I load a data frame with your data, making sure to allow repeated names with check.names = F, otherwise it would rename the wl columns to be distinct:
df <- read.table(
header = T, check.names = F,
stringsAsFactors = F,
text = " wl ex421 wl ex309 wl ex284 wl ex347
431 0.6168224 321 0.1267943 301 0.06392694 361 0.15220484
432 0.6687435 322 0.2416268 302 0.05631659 362 0.08961593
433 0.6583593 323 0.4665072 303 0.05327245 363 0.13134187
434 0.6832814 324 0.3576555 304 0.00000000 364 0.32432432
435 0.6427830 325 0.2194976 305 0.12328767 365 0.50308203
436 0.7393562 326 0.1866029 306 0.08675799 366 0.34660977")
Then here's a way to reshape, by just stacking subsets of the data. Since there weren't too many column pairs, I thought a semi-manual method would be ok. It preserves the distinct column headers so we can gather those into long form and map to color like in your plot.
library(tidyverse)
df2 <- bind_rows(
df[1:2],
df[3:4],
df[5:6],
df[7:8]
) %>%
gather(variable, value, -wl) %>%
drop_na()
ggplot(df2, aes(x=wl,y=value,color=variable)) +
geom_point(shape = 1, fill = NA) +
geom_path(size = 1) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) | unknown | |
d14987 | val | May be this might help you :
ParameterTool parameters = ParameterTool.fromPropertiesFile("src/main/resources/application.properties"); // one can specify the properties defined in conf/flink-conf.yaml in this properties file
Configuration config = Configuration.fromMap(parameters.toMap());
TaskExecutorResourceUtils.adjustForLocalExecution(config);
StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment(config);
env.setParallelism(3);
System.out.println("Config Params : " + config.toMap());
Make a note to set the parallelism equal to the number of task slots for task manager as per this link. By default, the number of task slots for a task manager is one. | unknown | |
d14988 | val | $result = mysql_query("SELECT * FROM product
WHERE `category` like '" . mysql_real_escape_string($_GET['category']) . "' LIMIT 0, 10");
is it what are you looking for? It will give you ten rows maximally..
Additionally, please read this article about SQLi | unknown | |
d14989 | val | I think you should change your style.xml and your Android Theme since you don't ne the Android appcompat libarary anymore.
styles.xml:
<style name="AppBaseTheme" parent="@style/Theme.Holo.Light.DarkActionBar">
<!-- nothing API level dependent yet -->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
AndroidManifest.xml:
<application
android:theme="@style/AppTheme"
... | unknown | |
d14990 | val | Split the array, use Array#slice to get the last two elements, and then Array#join with slashes:
var url = 'www.example.com/products/cream/handcreamproduct1';
var lastTWo = url
.split("/") // split to an array
.slice(-2) // take the two last elements
.join('/') // join back to a string;
console.log(lastTWo);
A: There is no built in array function to do that.
Instead use
const urlParts = 'url'.split('/');
return urlParts[urlParts.length - 2] + "/" + urlParts[urlParts.length - 1];
A: I love the new array methods like filter so there is a demo with using this
let o = 'www.example.com/products/cream/handcreamproduct1'.split('/').filter(function(elm, i, arr){
if(i>arr.length-3){
return elm;
}
});
console.log(o);
A: You can use String.prototype.match() with RegExp /[^/]+\/[^/]+$/ to match one or more characters that are followed by "/" followed by one or more characters that are followed by end of string
let url = "https://www.example.com/products/handcream/cream/handcreamproduct1";
let [res] = url.match(/[^/]+\/[^/]+$/);
console.log(res);
A: Note that if the URL string has a trailing / then the answers here would only return the last part of the URL:
var url = 'www.example.com/products/cream/handcreamproduct1/';
var lastTWo = url
.split("/") // split to an array
.slice(-2) // take the two last elements
.join('/') // join back to a string;
console.log(lastTWo);
To fix this, we simply remove the trailing /:
const urlRaw = 'www.example.com/products/cream/handcreamproduct1/';
const url = urlRaw.endsWith("/") ? urlRaw.slice(0, -1) : urlRaw
const lastTWo = url
.split("/") // split to an array
.slice(-2) // take the two last elements
.join('/') // join back to a string;
console.log(lastTWo); | unknown | |
d14991 | val | Just for reference, there are two types of index signatures, string and numeric.
String index signature:
[index: string]: SomeType
This says that when I access a property of this object by a string index, the property will have the type SomeType.
Numeric index signature:
[index: number]: SomeOtherType
This says that when I access a property of this object by a numeric index, the property will have the type SomeOtherType.
To be clear, accessing a property by string index is like this:
a["something"]
And by numeric index:
a[123]
You can define both a string index signature and a numeric index signature, but the type for the numeric index must either be the same as the string index, or it must be a subclass of the type returned by the string index.
So, this is OK:
interface SomeInterface {
[index: string]: Fruit;
[index: number]: Fruit;
}
Because both index signatures have the same type Fruit. But you can also do this:
interface SomeInterface {
[index: string]: Fruit;
[index: number]: Apple;
}
As long as Apple is a subclass of Fruit. | unknown | |
d14992 | val | An article on how plugins are loaded is included in https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#how-plugins-are-loaded
The Sqlite plugin by default is initialised during PerformBootstrapActions in Setup - see https://github.com/MvvmCross/MvvmCross/wiki/Customising-using-App-and-Setup#setupcs for where this occurs in the start sequence.
From your question, it's not clear which overrides in Setup you've tried - I'm not sure which positions "all sorts" includes. However, it sounds like want to register your ISQLiteConnectionFactory at any point after PerformBootstrapActions and before InitializeApp - so one way to do this would be to override InitializeApp:
protected virtual void InitializeApp(IMvxPluginManager pluginManager)
{
// your code here
base.InitializeApp(pluginManager);
}
Some possible other ideas to consider:
*
*if you want to prevent the Sqlite plugin from self-initializing in the Wpf case, then you could remove the Sqlite bootstrap file from your Wpf project (but beware that nuget might try to add it again later)
*the new "community fork" of the MvvmCross sqlite project has source code updated to the latest SQLite-net version (via @jarroda) and has a BasePath CreateEx option to allow the folder to be specified - see https://github.com/MvvmCross/MvvmCross-SQLite/blob/master/Sqlite/Cirrious.MvvmCross.Community.Plugins.Sqlite.Wpf/MvxWpfSqLiteConnectionFactory.cs#L24 | unknown | |
d14993 | val | It looks like your route helper is incorrect. The documentation for resource route helpers may be helpful for your situation: https://guides.rubyonrails.org/routing.html#path-and-url-helpers
Have you tried running rake routes to get the list of available routes and route helpers? I imagine you need something more like:
<%= link_to "Add Warranty Service URL",
new_warranty_management_url_path,
class: 'button green right' %>
You can pass a sponsor_id param as an argument to the path helper, but that won't work unless the sponsor has been saved, which isn't true for a new record. | unknown | |
d14994 | val | You can use this script to convert php array to javascript:
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>
A: You can simply convert by JSON encode.
echo json_encode($your_array); | unknown | |
d14995 | val | I found the solution, to set up Intersystems IRIS on Quarkus you need to add manually the jar file, and also you need to set up the pom.xml also some setup from Intersystems was made as a java class. you can see the solution looking at my project on GitHub
this is the link: https://github.com/JoseAdemar/quarkus-project-with-intersystems-ris-database | unknown | |
d14996 | val | Try importing ApolloProvider from @apollo/client
import { ApolloProvider } from '@apollo/client'; | unknown | |
d14997 | val | I have prepared two icon buttons for you. One works with a hover and the other without a hover.
.btn {
background-color: #333333;
border: none;
color: white;
padding: 12px 16px;
font-size: 16px;
cursor: pointer;
height: 60px;
margin: 10px;
position: relative;
width: 660px;
border-bottom: solid gray 1px
}
/* Darker background on mouse-over */
.btn:hover {
background-color: #444444;
}
.btn .ic-line {
width: 1px;
height: 60px;
background: #ddd;
float: right;
position: absolute;
right: 60px;
top: 0;
}
.fa-custom {
float: right;
position: absolute;
right: 20px;
top: 22px;
font-size: 1.1rem;
color: #fff;
}
.btn .ic-line1 {
width: 1px;
height: 60px;
background: #ddd;
float: right;
position: absolute;
right: 60px;
top: 0;
visibility: hidden;
}
.fa-custom1 {
float: right;
position: absolute;
right: 20px;
top: 22px;
font-size: 1.1rem;
visibility: hidden;
color: #fff;
}
.btn:hover .ic-line1 {
visibility: visible;
}
.btn:hover .fa-custom1 {
visibility: visible;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<h2>Icon Buttons</h2>
<p>Icon buttons:</p>
<button class="btn"><i class="fa fa-arrow-right fa-custom"></i><i class="ic-line"></i>Send</button>
<h2>Icon Buttons When hover</h2>
<p>Icon buttons:</p>
<button class="btn"><i class="fa fa-arrow-right fa-custom1"></i><i class="ic-line1"></i>Send</button> | unknown | |
d14998 | val | Extend you ACurrentDayInfo class with a getter like this
class ACurrentDayInfo
{
public string UserName
{
get
{
return JsonConvert.DeserializeObject<UserInfo>(UserInfo).RealName ?? "";
}
}
}
and modify your query like this:
db.ReadonlyQuery<Transaction>()
.Select(t => new ACurrentDayInfo
{
OrderId = t.TransactionIdentifier,
OrderTime = t.TransactionTime,
UserInfo = t.UserInfo
}).ToListAsync();
A: In EF Dbcontext don't support cast json in query, You need fix same that:
var listData = db.ReadonlyQuery<Transaction>()
.Select(t => new ACurrentDayInfo
{
OrderId = t.TransactionIdentifier,
OrderTime = t.TransactionTime,
UserInfo = t.UserInfo
}).ToListAsync();
foreach (var item in listData)
{
item.UserName = JsonConvert.DeserializeObject<UserInfo>(t.UserInfo).RealName ?? ""
} | unknown | |
d14999 | val | I'd need a little more context to say exactly what your problem is - you'd not generally call getConversion() yourself unless you were writing a serialiser.
The lookup for field -> converter is in the actual generated class; look for this: private static final org.apache.avro.Conversion<?>[] conversions
This conversion table seems to only be applicable to serialisation. When deserialising, you'll need to register the conversions. I'm not sure why this is the case, but you should be able to fix the issue by adding the following code at startup, which should register the conversions you need.
SpecificData.get().addLogicalTypeConversion(new Conversions.DecimalConversion());
SpecificData.get().addLogicalTypeConversion(new TimeConversions.DateConversion());
SpecificData.get().addLogicalTypeConversion(new TimeConversions.TimeConversion());
SpecificData.get().addLogicalTypeConversion(new TimeConversions.TimestampConversion());
Depending on the exact codepaths, you may also need to call that code on GenericData.get()... | unknown | |
d15000 | val | The custom AuthenticationProvider-implementation is not needed in this case. The available Spring-Security components should be sufficient. I would strongly recommend to stick with these components.
Besides that, the current implementation looks a "broken" (eg. why is the UserDetails-Model actually a Sevice??).
Let's try to fix the things...
(Mis-)Using the AuthenticationProvider (which is a Singleton Instance) as an Authentication-Holder was the reason, why the last successful login showed up. That is why a singleton instance basically shouldn't keep state.
The important thing to know is how to access the currently logged in user: Spring-Security stores an Authentication object into the SecurityContext. It can be accessed like this (eg. in your Handler-method):
import org.springframework.security.core.context.SecurityContextHolder;
...
@Controller
class SiteController {
@GetMapping("/admin")
String adminArea() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
MyUser principal = (MyUser) auth.getPrincipal();
// The object-type is the same that is returned by the `UserDetailsService#loadUserByName()` implementation
String username = user.getUsername();
...
}
}
Alternatively there is a convenient way to inject the currently logged in User into a Handler-Method like this (see @AuthenticationPrincipal for details):
@Controller
class SiteController {
@GetMapping("/admin")
String admin(@AuthenticationPrincipal MyUser user, Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
MyUser principal = (MyUser) auth.getPrincipal();
// `user` and `principal` is referencing the same object!
model.addAttribute("user", user);
model.addAttribute("principal", principal);
...
}
}
A working example
Lets see the components needed to get a working example.
The Security-Config
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login")
.and()
.logout()
.deleteCookies("JSESSIONID")
.and()
.rememberMe();
// @formatter:on
}
}
The UserDetailsService
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class UserService implements UserDetailsService {
private MyUserRepository userRepository;
public UserService(MyUserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
MyUser user = userRepository.findByUsername(username);
if (user != null) {
// if user already implements the `UserDetails`-interface, the object could be directly returned
// if not, wrap it into a pojo fulfilling the `UserDetails`-contract - eg.
// return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), AuthorityUtils.createAuthorityList("ROLE_ADMIN"));
return user;
}
throw new UsernameNotFoundException(username + " could not be found");
}
}
The Login Controller and Form
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
class LoginController {
@GetMapping("/login")
String loginForm() {
return "login";
}
}
resources/templates/login.html (thymeleaf)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
Also take a look at the getting-started series: https://spring.io/guides/gs/securing-web/
A: @fateddy has made me realize that I didn't consider the scope at all, and that was the key to solve the issue.
In the way I have set Spring Security, the implementation of the AuthenticationProvider, seems to be the starting point of the login process. Setting there a Session Scope has worked out:
@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RwAuthenticationProvider implements AuthenticationProvider {...
I have the user details in the UserDetailsService implementation with its roles, and at the AuthenticationProvider implementation (RwAuthenticationProvider), from where I retrieve them to set them at a Controller Model, with with this class:
@Service
public class UserDetailsModel {
Integer idproperty;
Integer idweb;
@Autowired
private RwAuthenticationProvider userDetails;
@Autowired
private PropertyRepository propertyRepository;
//Navigation bar - adminTmplt.htnl
public Model getUserDetailsModel(Model model){
model.addAttribute("userName", userDetails.getUserDetails().getName());
model.addAttribute("surname", userDetails.getUserDetails().getSurname());
model.addAttribute("email", userDetails.getUserDetails().getUser().getUsername());
model.addAttribute("property", userDetails.getUserDetails().getPropertyName());
model.addAttribute("idproperty", getIdProperty());
return model;
}
public Integer getIdProperty(){
idproperty = userDetails.getUserDetails().getIdproperty();
return idproperty;
}
public Integer getIdWeb(){
idweb = userDetails.getUserDetails().getIdweb();
return idweb;
}
public String getPropertyName(){
String propertyName = userDetails.getUserDetails().getPropertyName();
return propertyName;
}
public void setIdproperty(Integer idproperty){
userDetails.getUserDetails().setIdproperty(idproperty);
String propertyName = propertyRepository.getPropertyById(idproperty).getName();
userDetails.getUserDetails().setPropertyName(propertyName);
}
}
That's the customized implementation of UserDetails:
@Entity
@Table(name = "users")
public class RentalWebsUser implements UserDetails, Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "idweb")
private Integer idweb;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "username")
private String username;
//Not persistent
private int idproperty;
private String propertyName;
private User user;
@NotNull
@Column(name = "password")
private String password;
@Column(name = "enabled")
private boolean enabled;
@NotNull
@Column(name = "name")
private String name;
@NotNull
@Column(name = "surname")
private String surname;
@NotNull
@Column(name = "idcountry")
private int idcountry;
//private List<GrantedAuthority> authorities;
public RentalWebsUser(){}
public RentalWebsUser(User user, int idweb, String name, String surname) {
this.idweb = idweb;
this.name = name;
this.surname = surname;
this.user = user;
}
...Getters and Setters
@Override
public boolean isAccountNonExpired() {
return this.user.isAccountNonExpired();
}
@Override
public boolean isAccountNonLocked() {
return this.user.isAccountNonLocked();
}
@Override
public boolean isCredentialsNonExpired() {
return this.user.isCredentialsNonExpired();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
throw new UnsupportedOperationException("Not supported yet.");
}
...hashCode, equals and toString methods omitted.
I fear that my settings are not accurate enough, therefore any recommendation to improve them will be more than welcome.
Thanks a lot, once more to all you.
A: I think the issue happens when you log in with a different user WITHOUT logging out first.
If this is the case then it happens because the actual session is not renewed after the successful login. This should be done by an eventListener what is called by the AuthenticationManager if it was set up properly.
I think we have 2 AuthenticationManagers here - one is set up properly by the WebSecurityConfigurerAdapter and an other one what is created by the builder what is passed to the configureGlobalSecurity method and actually is in use later.
I had a similar issue a long time ago.
Try the following:
Add the following line into the configuration method:
http.authenticationProvider(authenticationProvider);
Comment out the configureGlobalSecurity method
Oh, one more thing: Try to extend the DaoAuthenticationProvider instead of creating your own. You will thank it later... | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.