text:
Q: Adding custom AnnotationView in iphone I am using following code to make custom AnnotationView.
My CustomPointAnnotation is a subclass of MKPointAnnotation with a setter/getter of Player
   -(void) showMarkers
    {
        [self.mapView removeAnnotations:[self.mapView annotations]];
        for (int i = 0 ; i < [self.playersArray count];  i ++)
        {
            Players *player = [self.playersArray objectAtIndex:i];

            CustomPointAnnotation *annotationPoint = [[CustomPointAnnotation alloc] init];
            [annotationPoint setPlayer:player];

            if ([player.name isEqualToString:self.name.text])
            {
                NSLog(@"%@ , %@" , player.name,self.name.text);
                annotationPoint.coordinate = CLLocationCoordinate2DMake([player.latitude doubleValue]+.1, [player.longitude doubleValue]+.1);
                  [self.mapView addAnnotation:annotationPoint];
            }
            else
            {
                NSLog(@"%@ , %@" , player.name,self.name.text);
                annotationPoint.coordinate = CLLocationCoordinate2DMake([player.latitude doubleValue], [player.longitude doubleValue]);
                [self.mapView addAnnotation:annotationPoint];
            }
         }
        [self.mapView setUserInteractionEnabled:YES];

    }

    - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
    {
      //  self.mapView.centerCoordinate = userLocation.location.coordinate;
        myLocation = userLocation;
    }

    -(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
    {
        if ([[annotation title] isEqualToString:@"Current Location"] )
        {
               return nil;
        }

        CustomAnnotationView *annView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"players"];
        CustomPointAnnotation *ptAnnotation = (CustomPointAnnotation *) annotation;
        [annView setPlayer:ptAnnotation.player];

        annView.image = [UIImage imageNamed:@"marker.png"];
        annView.enabled = YES;
        [annView setUserInteractionEnabled:YES];

        return annView;

    }

The problem comes at [annView setPlayer:ptAnnotation.player]; Unrecognized selector sent to instance
I am adding CustomPointAnnotation so it should convert it back. How can i solve this issue

A: OK, Im not sure how you declared the custom class, but it goes like this:
.h:
@interface CustomPointAnnotation: NSObject <MKAnnotation> {

}

@property (nonatomic) CLLocationCoordinate coordinate;
// Other properties like title, subtitle, etc.

.m
@implementation CustomPointAnnotation

@synthesize coordinate; // and other properties

A:
@interface CustomPointAnnotation : NSObject <MKAnnotation&gt
{

    Player *player;
}
@property(nonatomic,retain) Player *player;
@property (nonatomic) CLLocationCoordinate coordinate;

Do not subclass MKAnnotation istead confirm to MKAnnotation protocal.

@interface CustomAnnotationView : MKAnnotationView
{

}

no need to set the player. when you need to access the player object access it using the annotation in CustomAnnotationView.

CustomPointAnnotation *annotation=self.annotation;
annotation.player;


text:
Q: finding DB connections that are not closed properly There have been some leaks found in the code of a large project where DB connections are opened yet not closed.
The DB is DB2 and the connections are opened in a java program and not properly closed in a try catch, finally..
Is there any way to search in java for all methods which open a connection yet don't close it?
I'm trying to avoid manually looking through each method that opens a connection to see if it's closed properly.
any help with this tedious task would be cool.

A: Both FindBugs and PMD (open-source static code checkers) support detecting unclosed DB connections. They could be integrated into your build process and / or IDE.
PMD, in particular, can be noisy by default, but it can be tuned down using a custom ruleset or via other means.

A: The first thing that comes to my mind is implementing a tool utilizing abstract syntax trees (e.g. as an eclipse plugin). You could write a tool that goes through your methods, checks the nodes for connection initialization commands, and also checks for closing commands.
See:
 - http://en.wikipedia.org/wiki/Abstract_syntax_tree see:
 - http://www.eclipse.org/articles/Article-JavaCodeManipulation_AST/index.html
Otherwise, I think also some kind of custom parser could be used that checks there is an equivalent .close() statement within the same level as the equivalent database open statement.
You would have to check how many levels in you are (utilizing "{" and "}" characters.
See: Write a custom syntax interpreter in java?

A: In relation to your question you could also implement a class with methods that ensure you to close connections. Under I have posted an example.
public class Cleaner {

private String dbName = "";
private Connection connection;

public static void CloseResSet(ResultSet res) {
    try {
        if (res != null) {
            res.close();
        }
    } catch (SQLException e) {
        writeMessage(e, "CloseResSet()");
    }
}

public static void closeStatement(Statement stm) {
    try {
        if (stm != null) {
            stm.close();
        }
    } catch (SQLException e) {
        writeMessage(e, "closeStatement()");
    }
}

public static void closeConnection(Connection connection) {
    try {
        if (connection != null) {
            connection.close();
        }
    } catch (SQLException e) {
        writeMessage(e, "closeConnection()");
    }
}

public static void rollBack(Connection connection) {
    try {
        if (connection != null && !connection.getAutoCommit()) {
            connection.rollback();
        }
    } catch (SQLException e) {
        writeMessage(e, "rollBack()");
    }
}

public static void setAutoCommit(Connection connection) {
    try {
        if (connection != null && !connection.getAutoCommit()) {
            connection.setAutoCommit(true);
        }
    } catch (SQLException e) {
        writeMessage(e, "setAutoCommit()");
    }
}

public static void writeMessage(Exception e, String message) {
    System.err.println("*** Error: " + message + ". ***");
    e.printStackTrace(System.err);
}

private void OpenConnection() {
    try {
        connection = DriverManager.getConnection(dbName);
        System.out.println("Databaseconnection established");
    } catch (SQLException e) {
        Cleaner.writeMessage(e, "Constructor");
        Cleaner.closeConnection(connection);
    }
}

private void closeConnection() {
    System.out.println("Closes databaseconnection");
    Cleaner.closeConnection(connection);
}
public static void main(String[] args){
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Evenly distribute X values within a given range This is driving me nuts. I am looking for the formula to evenly calculate x values within a range of minimum and maximum values. For instance...
min = 4
max = 20
x = 3
Should equate to...
= 8, 12, 16
I feel like the answer is right in front of my face, I'm sure I covered it at some point during one of my math or statistics courses, but I just can't puzzle it out. I have looked at similar questions here, but they are all programming specific and aren't really shedding any light for me. I would think there has to be a basic formula for this. Any help would be greatly appreciated.

A: assuming t = 1..x:
a[t] = min+t*(max-min) / (x+1)


text:
Q: Print all even values in all object key end with odd value I want to print all even values in all object key end with odd value but the coding I made just now is only specified for arr1, arr3, and arr5. Can anyone suggest me how to fix  'let oddArr' method (maybe in loop) so that when I changed arr1 into arr7, the result would be the same.

var num = {
    arr1 : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    arr2 : [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
    arr3 : [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
    arr4 : [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
    arr5 : [41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
    };

    let oddArr = [...num.arr1, ...num.arr3, ...num.arr5] //need some correction here
    let evenNum = oddArr.filter(number => number % 2 == 0);

    console.log(evenNum.toString());

    //help me fix 'let oddArr' (maybe in loop method) so that when I changed the object of the array (e.g: arr1 -> arr7) it would come out with the same result

    //the result/output should be 2,4,6,8,10,22,24,26,28,30,42,44,46,48,50 based on var num

A: You might want to use
let oddArr = Object.entries(num).filter(   // filter key names
   e => +e[0].replace("arr", '') % 2 !== 0 // replace "arr" and check if X in arrX is odd
).map(e => e[1]).flat()                    // merge values and flattern array

You can also make use of regex if the "arrX"-naming is not consistent:
+e[0].match(/\d+/) % 2 !== 0

See a working snippet below:

var num = {
  arr1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  arr2: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
  arr3: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
  arr4: [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
  arr5: [41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
};

let oddArr = Object.entries(num).filter(
  e => +e[0].replace("arr", '') % 2 !== 0
).map(e => e[1]).flat()

let evenNum = oddArr.filter(number => number % 2 == 0);
console.log(evenNum.toString());

A: You can try like below using for in loop and it works with any last character as odd.
var num = {
  arr1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  arr2: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
  arr3: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
  arr4: [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
  arr7: [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
};

let oddArr = [];
for (let key in num) {
  if (key.charAt(key.length - 1) % 2 !== 0) {
    oddArr = [...oddArr, ...num[key]];
  }
}

let evenNum = oddArr.filter((number) => number % 2 === 0);

console.log(evenNum.toString());

A: This also works.

var num = {
  arr1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  arr2: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
  arr3: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
  arr4: [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
  arr5: [41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
  arr6: [51, 52, 53, 55, 55, 56, 57, 58, 59, 60],
  arr7: [61, 62, 63, 66, 65, 66, 67, 68, 69, 70],
};

var evenNums = Object.keys(num).filter((item) => {
    itemNum = item.replace("arr", "");
    return itemNum % 2 !== 0;
}).map((o) => num[o]).flat().filter((x) => x % 2 == 0);

console.log(evenNums);


text:
Q: Convert to predicate logic: the relation $R$ on the set $X$ is antisymmetric How would I cast the following to logical symbols

The relation $R$ on the set $X$ is antisymmetric.

A: $(\forall a \in X)(\forall b \in X)\left [(aRb  \wedge a\not = b) \implies \lnot bRa \right]$


text:
Q: Installing .air without admin rights? i would like to distribute an Adobe Air App. But most enterprise companies doen't allow the installation of new apps.
Is there any workaround to make an Air App installable to as many users as possible?
THanks

A: You can not I think. I have to install my application as Administrator and then it works fine. But I have got the same issue when auto update is running...
Damien

A: Now with AIR 3.0 you can pack the captive runtime together with the air app.
and this is an article that describes a technique to create an AIR app that can be updated without admin rights: http://www.mabulous.net/air-applications-that-can-be-updated-without-requiring-admin-rights


text:
Q: Laravel: How to clear cache with Bash .sh script Using Windows.
I want to write and call a .sh script which will contain:
ssh root@api.*name*.com
cd /var/www/api.*name*.com
php artisan cache:clear
php artisan responsecache:clear
php artisan config:cache

At the moment it'll just login but not navigate to the directory or run the php artisan parts.
I will then schedule this to run with windows task scheduler.

A: You can call Artisan command from code (controller, model etc). For example:
 Artisan::call("cache:clear");


text:
Q: Sum with central trinomial coefficients I am trying to evaluate the following sum:
\begin{equation}
 \sum_{n=0}^\infty \frac{(-ix)^n}{(n+2)!} T_n
\end{equation}
where $T_n$ represent the central trinomial coefficients , with the following convetion: $T_0 = 1, T_1 =1, T_2 = 3, T_3 = 7 ...$. I know that this sum converges, however I do not know if there is a way to evaluate it. If it is not possible (or too hard) it would be nice if I could obtain at least the asymptotic behavior when $x \to \infty$ .

A: We can use the exponential generating function (see OEIS A002426) $$\sum_{n=0}^\infty T_n \frac{z^n}{n!}=e^z I_0(2z)$$ to obtain an integral representation for the sum. Here $I_0(x)$ is the zeroth modified Bessel function, but the substitution $z=-i x$ converts it to
$$\sum_{n=0}^\infty T_n \frac{(-i x)^n}{n!}=e^{-i x} I_0(-2i x)=e^{-i x}J_0(2x)$$
where $J_0(x)$ is the regular zeroth Bessel function. Integrating both sides twice (with base point $0$) and dividing by $x^2$ produces
\begin{align}
 \sum_{n=0}^\infty T_n \frac{(-i x)^{n}}{(n+2)!}
&=\frac{1}{x^2}\int_0^x\int_0^{x''} e^{-i x''}J_0(2x'')\,dx''\,dx'\\
&=\frac{1}{x^2}\int_0^x (x-t)e^{-i t}J_0(2t)\,dt.
\end{align}
where in the second line I've made use of the Cauchy formula for repeated integration. This is as far as I know how to go, unfortunately: Mathematica does not yield a closed form. But this may be sufficient for asymptotics or numerical exploration.


text:
Q: Cannot login to Kibana via Amazon Cognito I've deployed Amazon Elasticsearch with Cognito as the auth provider. I'm receiving an error when I try to login to Kibana.
I can sign up and do receive the verification code but when I enter it to try and confirm I get an error page.

I'm using Terraform and was able to run my code multiple times with it working but something changed and now the authentication between Kibana and Cognito is failing. I noticed that my user does get added to the User Pool but an identity for it doesn't show up in the Identity Pool Console.
The access Policy on the Elasticsearch node looks like this:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::<my_account_id>:role/Cognito-<identity_pool_name>-Auth-Role"
      },
      "Action": "es:ESHttp*",
      "Resource": "arn:aws:es:us-west-2:<my_account_id>:domain/<elasticsearch_domain_name>/*"
    }
  ]
}

The Authenticated Role from above, i.e. "arn:aws:iam::<my_account_id>:role/Cognito-<identity_pool_name>-Auth-Role" has this policy attached to it which gives the identity pool access to Kibana.
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Action": [
                "mobileanalytics:PutEvents",
                "cognito-sync:*",
                "cognito-identity:*"
            ],
            "Resource": "*"
        }
    ]
}

Any help is appreciated!


text:
Q: Imagemagick chop 30px off each edge (variable width and height) I need to chop 30px off each side (top bottom left right). I've tried crop and also -chop 30x30 but that only seems to work on one side;
convert -verbose -density 150 -trim pdfs/test/test.pdf -quality 80  -chop 30x30 images/agents/test/temp/test.jpg

A: If it's an even amount on both sides of a dimension, then the command you want is -shave
convert -verbose -density 150 -trim pdfs/test/test.pdf -quality 80 -shave 30x30 images/agents/test/temp/test.jpg


text:
Q: What's Property hits volume? Property hits volume = pageview?
I checked my Google Analytics and yearsterday I got 200 users but when i go to Administrator->Property->Property Configurations->Property hits volume, I saw that i got 10,000 Property hits volume yearsterday.
Where is this traffic coming from?!
I want to know the meaning of "Property hits volume".

A: Here's the definition from Google:
Hit
An interaction that results in data being sent to Analytics. Common hit types include page tracking hits, event tracking hits, and ecommerce hits.
Each time the tracking code is triggered by a user's behavior (for example, user loads a page on a website or a screen in a mobile app), Analytics records that activity. Each interaction is packaged into a hit and sent to Google's servers. Examples of hit types include:

*

*page tracking hits

*event tracking hits

*ecommerce tracking hits

*social interaction hits

https://support.google.com/analytics/answer/6086082?hl=en
Essentially combine your total number of non-unique pageviews and total number of non-unique event counts over the last 30 days, it should match closely (unless you have ecommerce and social as well)


text:
Q: ffprobe does not show packet size of a mpeg transport stream as 188 bytes I created a transport stream from a H.264 encoded file using the following ffmpeg command:
ffmpeg -i encoded.mp4 -c copy -map 0 -vbsf h264_mp4toannexb mpegts sample.ts
Now I want to check the frames and packets within the transport stream. I used
ffprobe -show_frames
which shows the frame details for audio and video frames. But I'm confused about the pkt_size field. Is it the actual frame size of each elementary stream of audio and video (I/B/P frames)?
Also, when I run
ffprobe -show_packets
is it supposed to give each packet details in the transport stream? Because the size field of each packet is not 188 bytes, rather it is same as the pkt_size I got with -show_frames.
Could someone please explain why the size in -show_packets of transport stream is not 188 bytes? Did I do anything wrong while multiplexing mp4 to TS?

A: Both pkt_size must to be equals. See this ffprobe test from src code from gitHub.
[packets_and_frames.packet.0]
codec_type=audio
stream_index=0
pts=0
pts_time=0.000000
dts=0
dts_time=0.000000
duration=1024
duration_time=0.023220
convergence_duration=N/A
convergence_duration_time=N/A
size=2048
pos=642
flags=K

[packets_and_frames.frame.0]
media_type=audio
stream_index=0
key_frame=1
pkt_pts=0
pkt_pts_time=0.000000
pkt_dts=0
pkt_dts_time=0.000000
best_effort_timestamp=0
best_effort_timestamp_time=0.000000
pkt_duration=1024
pkt_duration_time=0.023220
pkt_pos=642
pkt_size=2048
sample_fmt=s16
nb_samples=1024
channels=1
channel_layout=unknown

[packets_and_frames.packet.1]
codec_type=video
stream_index=1
pts=0
pts_time=0.000000
dts=0
dts_time=0.000000
duration=2048
duration_time=0.040000
convergence_duration=N/A
convergence_duration_time=N/A
size=230400
pos=2717
flags=K

[packets_and_frames.frame.1]
media_type=video
stream_index=1
key_frame=1
pkt_pts=0
pkt_pts_time=0.000000
pkt_dts=0
pkt_dts_time=0.000000
best_effort_timestamp=0
best_effort_timestamp_time=0.000000
pkt_duration=2048
pkt_duration_time=0.040000
pkt_pos=2717
pkt_size=230400
width=320
height=240
pix_fmt=rgb24
sample_aspect_ratio=1\:1
pict_type=I
coded_picture_number=0
display_picture_number=0
interlaced_frame=0
top_field_first=0
repeat_pict=0

[packets_and_frames.packet.2]
codec_type=video
stream_index=2
pts=0
pts_time=0.000000
dts=0
dts_time=0.000000
duration=2048
duration_time=0.040000
convergence_duration=N/A
convergence_duration_time=N/A
size=30000
pos=233138
flags=K

[packets_and_frames.frame.2]
media_type=video
stream_index=2
key_frame=1
pkt_pts=0
pkt_pts_time=0.000000
pkt_dts=0
pkt_dts_time=0.000000
best_effort_timestamp=0
best_effort_timestamp_time=0.000000
pkt_duration=2048
pkt_duration_time=0.040000
pkt_pos=233138
pkt_size=30000
width=100
height=100
pix_fmt=rgb24
sample_aspect_ratio=1\:1
pict_type=I
coded_picture_number=0
display_picture_number=0
interlaced_frame=0
top_field_first=0
repeat_pict=0

Is the same. Both pkt_size are the size of compressed frame in bytes.
See this issue ticket too


text:
Q: Send RPC call to only 1 node in Azure Service Fabric When I make an RPC (service remoting) call to a service that is deployed on multiple nodes from another service in the same application, it appears to be going to all nodes at once.  I only want it to go to one each time the call is made.
Does Service Fabric have a way to do that? How can I leverage the built-in load balancing to control where the call goes to?
This deployed on a local cluster

A: If your service is stateless and uses Singleton partitioning, calling an operation using the ServiceProxy will invoke the operation on one random service instance. Using SF remoting, you can't target a specific instance.
If your service is stateful, calling an operation using the ServiceProxy (created with a specific ServicePartitionKey) will invoke the operation on one of the replicas of your service, using the primary replica by default.


text:
Q: Columns blank after join I have 3 df like df1, df2, df3 and they read a .csv file. I want to combine df1 & df2 and then have the result do a lookup on df3 and pull the values that are the same in a certain key that's both in df3 and result. So basically a vlookup.
This is how I concatenated df1&df2:
result = pd.concat(frames,keys=['data1','data2'])

I performed the merge like this:
result = pd.merge(result, df3, left_on='ProducerID', right_index=True, how='left', sort=False)

But my results are these:
        Key_x   otherColumns    Key_y   otherColumns
L   0   5763460 NaN             NaN     NaN
L   1   5926058 NaN             NaN     NaN
L   2   5052233 NaN             NaN     NaN
L   3   5526565 NaN             NaN     NaN
L   4   5059073 NaN             NaN     NaN
L   5   5975975 NaN             NaN     NaN

I should mention, key is not in the index. I abbreviated the data. key is just a column in the middle of my data.
And these are snippets of what my data files look like:
df1
Column 1    Column 2    Column 3    Column n…   Key     Column …n
data1       data        data        data        5763460 data
data2       data        data        data        5926058 data
data1       data        data        data        5052233 data

df2
Column 1    Column 2    Column 3    Column n…   Key     Column …n
data1       data        data        data        5763460 data
data1       data        data        data        5926058 data
data2       data        data        data        5052233 data

df3
Key     Column 1    Column 2
5763460 data        data
5926058 data        data
5052233 data        data

result
Column 1    Column 2    Column 3    Column n…   Key     Column …n
data1       data        data        data        5763460 data
data1       data        data        data        5926058 data
data2       data        data        data        5052233 data

So result will look just like df1 just larger and grouped by the contents of Column 1 which are data1 and data2


text:
Q: How to get digits = ["12", "145", " 45", "12.4", "45,14", "15 645"] numbers def fix(i):
   return i.replace(",",".") and i.replace(" ","") and float(i)

ValueError: could not convert string to float: '45,14'

A: Your question in very vague. But I will give it a go for you.
["12", "145", "45", "12.4", "45,14", "15 645"]

*

*

Assuming you just want the list to be the digits only but still a string
digits = ["12", "145", "45", "12.4", "45,14", "15 645"]
new_digits = [dgt.replace(",","").replace(".","").replace(" ","") for dgt in digits]
print(new_digits)

output
["12", "145", "45", "124", "4514", "15645"]

*

If you want them as a integer then wrap it with an int().
digits = ["12", "145", "45", "12.4", "45,14", "15 645"]
new_digits = [int(dgt.replace(",","").replace(".","").replace(" ","")) for dgt in digits]
print(new_digits)

output
[12, 145, 45, 124, 4514, 15645]

*

If you want them all in one string then you could do the following.
digits = ["12", "145", "45", "12.4", "45,14", "15 645"]
out_str = ""

for number in digits:
    for single_number in number:
        if not single_number in [",","."," "]:
            out_str += single_number
print(out_str)

output
1214545124451415645

*

or if you want to return floats for each then.
digits = ["12", "145", "45", "12.4", "45,14", "15 645"]
new_digits = [float(dgt.replace(",",".").replace(" ",".")) for dgt in digits]
print(new_digits)

output
[12.0, 145.0, 45.0, 12.4, 45.14, 15.645]


text:
Q: Fast creation of data.frame Is there a way to create a data.frame faster or smarter than the one I made below?
df <- data.frame(ID = rep(c("WT", "KO"), each = 4),
                 Time = rep(c("A", "B", "C", "D"), times = 2),
                 replicate(5,sample(0:100,8,rep=TRUE)))

colnames(df)<-c("ID", "Time", c("a", "b", "c", "d", "e"))

The data.frame should still look like this
df
ID Time  a  b  c  d  e
WT    A 28 56 50 60 15
WT    B 54 77 11 67 34
WT    C 53  8 87 62 55
WT    D 30 73 47 82  1
KO    A 24 83 14 17 36
KO    B 91 83 72 41  4
KO    C 79 17 76 21 54
KO    D 41 40 77 49 92

Thanks

A: You can just use expand.grid for the non numeric unique combinations (sometimes you can even make use of built it data sets such LETTERS) and run sample only once while wrapping it up into a matrix, something like
set.seed(123)
data.frame(expand.grid(c("WT", "KO"), LETTERS[1:4]),
           matrix(sample(40), ncol = 5))
#   Var1 Var2 X1 X2 X3 X4 X5
# 1   WT    A 12 36  6 11 24
# 2   KO    A 31 15  1 27 13
# 3   WT    B 16 29  8 22 25
# 4   KO    B 33 14 21 28 26
# 5   WT    C 34 19 32  4 20
# 6   KO    C  2 38 37 35  7
# 7   WT    D 18  3 40 10  5
# 8   KO    D 30 23 17  9 39

For less specific cases, I would recommend looking into @TylerRinkers wakefield package which allows you to generate random data sets easily.

Just for general information, using data.table v 1.9.5+ you can now set new column names by reference using setnames. For, example if your new data set is called res, one could simply do
library(data.table) # v1.9.5+
setnames(res, c("ID", "Time", letters[1:5]))


text:
Q: How to import millions of records from SQL Server 2000 to Microsoft Excel 2010 I have around 3.5 million records that i want to import into a Excel 2010 file. I have tried using SQL Servers Import/Export Data Wizard and this worked but the problem was that it only copied about 65,000 out of the 3,500,000 records i need. This is due to a limit that is on Excel.
I have tried to install PowerPivot to try increase the amount of records that could be inserted into excel but with no luck. Does anyone know how i would do this?

A: I was able to do this thanks to jsobo's comment above.
I first created a blank .csv file. Then i was able to use SQL Servers DTS Import/Export Wizard to add all the fields straight from the database to the .csv file


text:
Q: Select a range in UISlider i asked me whether it is possible if i can create a uislider who has 2 handles to select a range. Just like here:

The problem i am facing is that i dont want to use a custom UIControl Subclass. I need a UISlider subclass or a other solution for this problem, because a lot of the code is based on UISlider specific propertys etc. So is there any possibility to achieve this ?

A: Look at the following example:
http://www.cocoacontrols.com/platforms/ios/controls/rangeslider

A: UISlider doesn't provide the functionality you're after, and subclassing UISlider probably won't work out. What would the value of such a control be? The value of a slider is a number, but you want it to be a range. Consider a custom control that duplicates the UISlider properties you need.

A: You can subclass UISlider, but it will be very difficult. Your class should offer quite some new properties, and the old ones won't make much sense at all.
Not sure how your code can be based much on UISlider specific things - as everything would change the meaning (i.e. ranges instead of one value).
If you really need a common base class, you could encapsulate ("has-a" relationship) the control in a custom class and let this handle the different types.
I implemented a similar control using a custom view, and it happened to be quite straight forward.


text:
Q: Upper bounds on art gallery problems using independent witnesses Given a polygon $P$, the art gallery problem looks to find a smallest set of points that sees all of $P$. One way of bounding the number of guards necessary (from below) is to find a largest set of independent witness points, which are points whose visibility polygons are pairwise disjoint. Say the size of the smallest guarding set is $G(P)$ and the size of the largest witness set is $W(P)$. Then we have the trivial lower bound on $G(P)$, that $W(P) \leq G(P)$.
In arbitrary polygons, the size of the witness set does not help much with respect to an upper bound on the size of the guard set, i.e. there are examples with $\frac{G(P)}{W(P)} = \Omega(n)$.
Does the same hold for orthogonal polygons? It seems plausible to me that, unlike general polygons, a constant factor bound exists (maybe $\frac{G(P)}{W(P)} \leq 2$?), but my literature search came up empty. Can anyone point me at a reference, or a bad example?


text:
Q: How to add a laravel's new packages to several projects in different folders by using composer? i haven't got this able to work. I have been googled this for days so hopefully someone can help me or shed light for this.
I have installed Laravel by using composer and practiced programming a simple application. Then i wanted to carry on programming another application and i copied all the folders of my previous (very first) laravel project into another folder inside the htdocs folders. I am using XAMPP on windows.
Then i did the same and have four projects in different folders. I changed the original folder name of my very first laravel app in order to keep track of what i have been programming.
So now i am stuck in image uploading in another project. I downloaded the Intervention/image package by using Composer, it did well, I typed
composer require intervention image
and it was installed successfully.
Then i ran into this error:

Symfony \ Component \ Debug \ Exception \ FatalErrorException
  (E_ERROR)  Class 'Image' not found

Then i thought that possibly composer installed it into my original laravel project. I have tested all my applications by calling this image class and i still get this error. Now i am lost, i don't know where the intervention/image package was installed :( I don't find a folder that is named intervention or something like that.
Tell me how i can find out where is composer pointing to or installing the new packages?
I have also tried configuring the intervention/image in all the projects i have according to this website: http://image.intervention.io/getting_started/installation
And it says to add the following two lines in app/config/app.php

"In the $providers array add the service providers for this package.
'Intervention\Image\ImageServiceProvider'

Add the facade of this package to the $aliases array.
'Image' => 'Intervention\Image\Facades\Image' "

And i Have done that in all the applications and i get still another error:
Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR)
Class 'Intervention\Image\ImageServiceProvider' not found

My code in the controller files looks like this so far:
//UPLOAD PICTURE
public function getUploadPicture(){
    return View::make('account.uploadpicture');
}

//POST función que sube la foto del usuario
public function postUploadPicture(){
    var_dump($image=Input::file('photo'));
    $image=Input::file('photo');
    var_dump($image->getRealPath());
    Image::make($image->getRealPath());
    die();
    return Redirect::route('account-upload-picture')
                    ->with('global','

                            <button type="button" class="close" data-dismiss="alert">×Cerrar</button>
                            ¡La foto se ha enviado exitosamente!
')
                    ->withInput();
}

So now i have three questions,

*

*how do i get to know what the default directory is of composer?

*How do i know where the Intervention/Image was installed?

*how do i add another project so that it may be able to use the
Intervention/image too as well as future projects?

A: You'll need to add the package to your composer file. In laravel's project root, open up the composer.json file and add "intervention/image": "2.*", to the require section of the json. Then run composer update to fetch the package.


text:
Q: How can I use the template parameter of a class as the template parameter of a class member? I'm trying to implement the following in C++:
template <class T>
class Inner
{
public:
    Inner(T inData){data = inData;};
    ~Inner(void){};

    T data;
};

template <class T>
class Outer
{
public:
    Outer(Inner<T> in){inner = in;};
    ~Outer(void){};

    Inner<T> inner;
};

int main(void)
{
    Inner<int> in (10);
    Outer<int> out (in);

    std::cout << out.inner.data;
}

Compiled in MSVS 2010, I get the following error:
c:\...\main.cpp(15): error C2512: 'Inner<T>' : no appropriate default constructor available
          with
          [
              T=int
          ]
          c:\users\gaff\documents\visual studio 2010\projects\pgp(c++)\pgp(c++)\main.cpp(15) : while compiling class template member function 'Outer<T>::Outer(Inner<T>)'
          with
          [
              T=int
          ]
          c:\users\gaff\documents\visual studio 2010\projects\pgp(c++)\pgp(c++)\main.cpp(24) : see reference to class template instantiation 'Outer<T>' being compiled
          with
          [
              T=int
          ]

Clearly I'm missing some basic understanding here but I have no clue how to fix this, or even if what I'm trying to achieve is possible.
For what it's worth, here is a Java implementation that compiles without any problems:
public class Inner<T> {
    public T data;

    public Inner(T inData) {
        data = inData;
    }
}

public class Outer<T> {

    public Inner<T> inner;

    public Outer(Inner<T> in) {
        inner = in;
    }
}

public class Main {
    public static void main(String args[]){
        Inner<Integer> in = new Inner<Integer>(10);
        Outer<Integer> out = new Outer<Integer>(in);

        System.out.println(out.inner.data);
    }
}

Any suggestions?
Cheers
JimmidyJoo

A: The problem is that you don't have a default constructor for inner. When the compiler initializes the object it calls the default constructor of inner before the assignment.
EDIT:
It's probably a good idea to properly implement a copy constructor and instead initialize inner like so:
Outer(Inner<T> in) : inner(in) { };

You could use the copy constructor like so:
Inner(const Inner<T> & in) : data(in.data){
}

A: You need to use an initializer list in the constructor:
Outer(Inner<T> in): inner(in) {}

otherwise the constructor has to default construct inner before it gets into the constructor.  That's impossible since there is no default constructor.


text:
Q: Wordpress pages address rewrite UPDATE
I tried using the internal wordpress rewrite. What I have to do is an address like this:
http://example.com/galleria/artist-name

sent to the gallery.php page with a variable containing the artist-name.
I used these rules as per Wordpress' documentation:
// REWRITE RULES (per gallery) {{{
add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('query_vars','wp_insertMyRewriteQueryVars');
add_filter('init','flushRules');

// Remember to flush_rules() when adding rules
function flushRules(){
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}

// Adding a new rule
function wp_insertMyRewriteRules($rules)
{
    $newrules = array();
    $newrules['(galleria)/(.*)$'] = 'index.php?pagename=gallery&galleryname=$matches[2]';
    return $newrules + $rules;
}

// Adding the id var so that WP recognizes it
function wp_insertMyRewriteQueryVars($vars)
{
    array_push($vars, 'galleryname');
    return $vars;
}

what's weird now is that on my local wordpress test install, that works fine: the gallery page is called and the galleryname variable is passed. On the real site, on the other hand, the initial URL is accepted (as in it doesn't go into a 404) BUT it changes to http://example.com/gallery (I mean it actually changes in the browser's address bar) and the variable is not defined in gallery.php.
Any idea what could possibly cause this different behavior?
Alternatively, any other way I couldn't think of which could achieve the same effect described in the first three lines is perfectly fine.

Old question
What I need to do is rewriting this address:
(1) http://localhost/wordpress/fake/text-value

to
(2) http://localhost/wordpress/gallery?somevar=text-value

Notes:

*

*the remapping must be transparent: the user always has to see address (1)

*gallery is a permalink to a wordpress page, not a real address

I basically need to rewrite the address first (to modify it) and then feed it back to mod rewrite again (to let wordpress parse it its own way).
Problems
if I simply do
RewriteRule ^fake$ http://localhost/wordpress/gallery [L]

it works but the address in the browser changes, which is no good, if I do
RewriteRule ^fake$ /wordpress/gallery [L]

I get a 404. I tried different flags instead of [L] but to no avail. How can I get this to work?
EDIT: full .htaccess
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteRule ^fake$ /wordpress/gallery [R]

RewriteBase /wordpress/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]
</IfModule>

# END WordPress

A: Try this rule:
RewriteRule ^fake/([^/]+)$ gallery?somevar=$1 [L]

A: Solved, it was the Permalink Redirect plugin which needed to be configured to skip the desired "virtual" URLs, else it would issue a 301 Permanently moved.

A: Apologies for the very-delayed answer here, but I believe what you need to do is what Gumbo suggested but with the addition of the passthrough/PT flag:

This flag forces the rewrite engine to set the uri field of the internal request_rec structure to the value of the filename field.
...
You must use this flag if you want to mix directives from different modules which allow URL-to-filename translators.

Although Wordpress (via mod_php) runs after mod_rewrite is done, it normally gets the original (pre-rewrite) uri, and it uses that to do its own internal rewriting, rather than the re-written filename value.
So try:
RewriteRule ^fake/([^/]+)$ gallery?somevar=$1 [QSA,PT]

I added QSA so that, just in case someone went to /wordpress/fake/something?page=3, it will get passed along properly.  Let me know how that works.

A: *

*Using your favorite HTML/PHP editor, open wp-admin/includes/misc.php

*Find function function got_mod_rewrite Its around line 18 or so.

*Comment out the existing function: /* this is commented out */ — You can delete this function if you are sure the solution works, but to be safe, just comment it out in case you need to put it back.

*Add the following instead:
function got_mod_rewrite() {
    $got_rewrite = true;
    return apply_filters('got_rewrite', $got_rewrite);
}

*Save and upload.


text:
Q: Why wont my dell inspiron broadcom 1350 mini wifi adapter not connect to my wifi? So I put Ubuntu on my dell inspiron recently and it will keep changing the wifi tick mark back to do not use when I click to tell it to use the device. Any answer is appreciated.

A: I service more Dell laptops than any other brand, and I probably also encounter more Broadcom WIFI adapters than any other brand.  I recently responded to another question here, essentially the same as yours but regarding a different Broadcom device.  Though my comments there did not represent the necessary advice that user needed, I'm hoping this pointer to that thread will help you today.


text:
Q: Submit operation failed - NotFound from RIA Services with Silverlight 4 on SubmitChanges() I'm using SL4 and RIA Services to build a new solution based on the Silverlight Business Application template.  Since I'm still developing, I'm just using localhost.
I'm trying to test the SubmitChanges functionality by making a single change in an associated (composition) entity and calling SubmitChanges.  I have a breakpoint in my DomainService at the entry point in the Update method.  The breakpoint is hit and everything looks okay.  At this point, I don't actually have the Update method do anything - it simply returns.  In the client-side callback, I check the SubmitOperation object for errors.  It reports:
Submit operation failed.  The remote server returned an error: NotFound.

So far I haven't found what wasn't found.
I tried using Fiddler (along with the WCF Binary plugin) and as far as I can tell, the request looks good, but according to Fiddler:
ReadResponse() failed: The server did not return a response for this request.

Hmm...  Well that can't be right because my callback breakpoint was hit.  (That's how I got the NotFound error message.)
I also tried editing my web.config file with the following:
<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  <behaviors>
    <serviceBehaviors>
      <behavior name="RIAServiceBehavior">
        <serviceMetadata httpGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="True" />
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>

That didn't provide any new information.  I'm starting to run out of ideas on how to track down the "real" problem.  Any ideas??

A: Saurabh and Dan both have good posts on debugging 'Not Found' exceptions.
Link
http://blogs.objectsharp.com/post/2010/04/13/WCF-RIA-Services-%E2%80%9CNot-Found%E2%80%9D-Error-Message.aspx
Kyle


text:
Q: JSP : getOutputStream() has already been called for this response I am using this code to download file from FTP.
I am getting exception in tomcat log as below, i am able to perform my task but my log size increases a lot.
Code:
   if (file.exists())
   {
       if (file.canRead())
       {
          // IE6 & SSL PDF Bug
          // http://forums.sun.com/thread.jspa?threadID=526451&start=15&tstart=0

           mimeType = new javax.activation.MimetypesFileTypeMap().getContentType(file);
           response.setHeader("Cache-Control","private");
           response.setHeader("Pragma","expires");
           response.setHeader("Content-Disposition", "inline; filename=\"" + org.apache.commons.io.FilenameUtils.getName(file.getAbsolutePath()) + "\"");
           response.setContentType(mimeType);
           response.setContentLength((new Long(file.length())).intValue());
           byte[] buffer = new byte[(int)org.apache.commons.io.FileUtils.ONE_KB * 64];
           output=response.getOutputStream();
           bos = new java.io.BufferedOutputStream(output, buffer.length);
           bis = new java.io.BufferedInputStream(new java.io.FileInputStream(file));
           while (bis.read(buffer) != -1)
           {
               bos.write(buffer);
           }
           bos.flush();
       }
       else{System.out.println("Cannot read from file");}
   }
   else{System.out.println("File dosen't exist");}

Error Message
    Jan 18, 2014 6:11:31 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet jsp threw exception
 java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:611)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:198)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:188)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:118)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:77)

I saw post regarding adding code to servlet, also closing the output stream but none of that worked. Please assist.

A: you shouldn't do this in JSP but you should use a Servlet (even if a jsp page is far more pratical)
however if you still want to use a jsp page, use this directive:
<%@page language="java" trimDirectiveWhitespaces="true"%>

apart from question, since you are using commons-io:
if (file.exists())
{
    if (file.canRead())
    {
       // IE6 & SSL PDF Bug
       // http://forums.sun.com/thread.jspa?threadID=526451&start=15&tstart=0

        mimeType = new javax.activation.MimetypesFileTypeMap().getContentType(file);
        response.setHeader("Cache-Control","private");
        response.setHeader("Pragma","expires");
        response.setHeader("Content-Disposition", "inline; filename=\"" + org.apache.commons.io.FilenameUtils.getName(file.getAbsolutePath()) + "\"");
        response.setContentType(mimeType);
        response.setHeader("Content-Length", String.valueOf(file.length()));

        OutputStream output = response.getOutputStream();
        FileUtils.copyFile(file, output);
        output.close();
    }
    else{System.out.println("Cannot read from file");}
}
else{System.out.println("File dosen't exist");}

A: Use a Servlet to send binary data in a response, not a JSP page. JSP pages send text output, and will invoke the getWriter method in order to send the buffered output from the JSP page.
See also this question.


text:
Q: The instantiation happened before getInstance() or when getInstance()? I'm following this tutorial for create Singleton and the owner have comment when the method below http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
public class EagerInitializedSingleton {

    private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();

    //private constructor to avoid client applications to use constructor
    private EagerInitializedSingleton(){}

    public static EagerInitializedSingleton getInstance(){
        return instance;
    }
}

If your singleton class is not using a lot of resources, this is  the
  approach to use. But in most of the scenarios, Singleton classes are
  created for resources such as File System, Database connections etc
  and we should avoid the instantiation until unless client calls the
  getInstance method.

The Problem Is:
They say we should avoid the instantiation until unless client calls the getInstance method
BUT as I know in  this code the instantiation (of object instance) always happened when class EagerInitializedSingleton load, and EagerInitializedSingleton just only load when we call EagerInitializedSingleton.getInstance()
=> The instantiation will happened on time with getInstance() and never before getInstance()
Reference:
Static variables are initialized only once , at the start of the execution(when the Classloader load the class for the first time) .
(from https://stackoverflow.com/a/8704607/5381331)
So when are classes loaded?
There are exactly two cases:
 - when the new bytecode is executed (for example, FooClass f = new FooClass();)
 - and when the bytecodes make a static reference to a class (for example, System.out)
(from http://www.javaworld.com/article/2077260/learn-java/learn-java-the-basics-of-java-class-loaders.html)
Am I wrong or correct. Please give me some sugestion.

A: In this case with that specific code, you are probably correct.
However, if you had static methods of EagerInitializedSingleton, or static non-final members of EagerInitializedSingleton referenced somewhere in your code base prior to the invocation of getInstance, the instance variable of EagerInitializedSingleton would initialize.
Same with a reflective invocation of Class.forName on your EagerInitializedSingleton class.
Note (and forgive the obvious here) that there are alternative ways of declaring a singleton, including lazy-initialization or enums.

A: I think the problem is when a class gets loaded without the need to get the instance, but for some other reason. You assume that class will be used the first time when user will want to get an instance of that singleton, but it may happen for some other reason, he may just call a class loader for something, or use some 3rd party software to validate a class, anything that comes to mind that involves loading a class but not getting an instance of a singleton.

A:
They say we should avoid the instantiation until unless client calls
  the getInstance method

The solution is lazy loading.
From wikipedia, Initialization-on-demand holder idiom

When the class Something is loaded by the JVM, the class goes through
  initialization. Since the class does not have any static variables to
  initialize, the initialization completes trivially. The static class
  definition LazyHolder within it is not initialized until the JVM
  determines that LazyHolder must be executed. The static class
  LazyHolder is only executed when the static method getInstance is
  invoked on the class Something, and the first time this happens the
  JVM will load and initialize the LazyHolder class.

public class Something {
  private Something() {}

  private static class LazyHolder {
    private static final Something INSTANCE = new Something();
  }

  public static Something getInstance() {
    return LazyHolder.INSTANCE;
  }
}


text:
Q: Which node_modules my project actually use? We had the following problem:
The project is install under /home/node/project
where project is a soft link to /home/node/deploy/project{version}
The package.json is under /home/node/
We did npm i in /home/node/project which should have found the package.json under /home/node/ and build the node_module has expected.
But for some unknown reason, about a month ago, someone created a package.json under /home/node/deploy
Therefor the npm i build a new node_module under /home/node/deploy which was defected
Although we suspected that the code is using the wrong node_module we couldn't figure out which node_module the code actually use and wasted long time until we realize that a defected node_module was created in the wrong directory
So I would like to know if there is a way to know which node_modules my project actually use at run time?

A: Delete one of the node_modules folders and run your code. If your code is running without any errors, then it may mean that it is using the other node_modules folder.


text:
Q: How to interrupt Python program on user input? I am writing a program which executes in some standard fashion, unless the user inputs something in terminal, in which case the program should change the behavior, e.g.
while True:
    # do something here

def interrupt(user_input):
    if user_input == "some command":
        sys.exit(0) # e.g.

How to achieve this by not having input() in while loop?

A: The simplest interpretation here is to use a daemon thread.
To achieve this in Python, you can make use of multi-threading. For that, there is the threading module.
Your daemon would run in the background, by setting daemon=True when creating the thread.
Below is a simple example of that in action. Your main logic would go in the main function. The while True infinite loop listens for user input and terminates the program once the user input matches some predefined value ("kill" in this case).
import sys
import threading

def main():
    print('Main program')
    while True:
        pass
        # Rest of main program

main_thread = threading.Thread(name='main program',
                               target=main, daemon=True)
main_thread.start()
while True:
    if input().lower() == 'kill':
        print('Terminating program')
        # Add some possible cleanup code here
        sys.exit(0)

Take note of this important information from the Python documentation about how daemonic threads are stopped:

Daemon threads are abruptly stopped at shutdown. Their resources (such
as open files, database transactions, etc.) may not be released
properly. If you want your threads to stop gracefully, make them
non-daemonic and use a suitable signalling mechanism such as an Event.

That said, this approach may suffice for your purposes. Depending on your program logic, if some cleanup code is needed, it could be done before exiting -- since once the sys.exit(0) is called, the daemonic thread will be killed abruptly.
A more general solution, however, is to make use of threading.Event.
This is quite a distinct approach to the above in that we create a regular, non-daemonic thread and pass an Event to it. This time, instead of abruptly exiting the program on user input, we set the internal flag of the Event.
In parallel, instead of a while True infinite loop, the main function uses the non-blocking is_set() to break the loop once the Event is set.
import threading

def main(e):
    print('Main program')
    while not e.is_set():
        pass
        # Rest of main program
    print('Exiting')
    # Add some possible cleanup code here

e = threading.Event()

main_thread = threading.Thread(name='main program',
                               target=main, args=(e,))
main_thread.start()

while True:
    if input().lower() == 'kill':
        print('Terminating program')
        e.set()
        break

main_thread.join()

This has two advantages over the daemonic approach described:

*

*You could easily have multiple Events and have your program behave in different ways, depending on those events. There is also the blocking Event.wait() you can use instead of Event.is_set().

*Any cleanup code can instead be managed directly by the main() function.


text:
Q: splitting text files based column wise So I have an invoice that I need to make a report out of. It is on average to be about 250 pages long. So I'm trying to create a script that would extract the specific value of the invoice and make a report. Here's my problem:

*

*the invoice is in pdf format with it spanning two column. In Linux command, I want to use 'pdftotext' Linux command to convert into multiple text files (with each txt file representing each pdf page). How do I do that

*I recognize that 'pdftotext' command splits it left part of the page and right part of the page by having 21 spaces in between. How do I the right side of the data(identified after reading at least 21 spaces in a row) to the end of the file

*Since the file is large and I only last few page of the files, how do I delete all those text files in a script (not manually) until I read a keyword (let's just say the keyword = Start Invoice)?

I know this is a lot of questions, but I'm confused in what Linux command can do. Can you guys guide me to the right direction? Thanks
PS: I'm using CentOS 5.2

A: What about:
pdftotext YOUR.pdf | sed 's/^\([^ ]\+\) \{21\}.*/\1/' > OUTPUT
pdftotext YOUR.pdf | sed 's/.* \{21\}\(.*\)/\1/' >> OUTPUT

But you should check out pdftotext's -raw and -layout options too. And there are more ways to do it...


text:
Q: Line numbers and go to line I have a quiz and on the final round, I would like it to end if it gets an incorrect value
I have an if loop, but I would like my final else values to have a go to line line number code as it is a long code. In order to use this function, how could I view line numbers (I use Portable Python Scripter).
print("PLEASE NOTE: Answers are case-sensitive, so start all answers with a capital letter.")
print("Getting full marks (5/5) in each round will allow you to complete the next round.")
#==============================================================================
singer = input("Who is your favourite singer?")
if singer == "Harry Styles" or "Harry":
    print("Great choice!")
else:
    print(singer +" is good, but Harry Styles is better")
#==============================================================================
ans = input("Do you want to do a Harry Styles quiz?")
if ans == "No":
    print("How rude!")
elif ans == "Yes":
#==============================================================================
    q1 = input("What boyband was Harry Styles in?")
    if q1 == "One Direction":
        print("Correct!")
        score = 1
    elif q1 == "1D":
        print("Correct!")
        score = 1
    elif q1 == "White Eskimo":
        print("Correct!")
        score = 1
    else:
        print("Incorrect")
        score = 0
#==============================================================================
    q2 = input("What is Harry's birthday (write in format dd/mm/yyyy)")
    if q2 == "01/02/1990":
        print("Correct!")
        score = score + 1
    else:
        print("Incorrect")
#==============================================================================
    q3 = input("What is Harry's favourite film?")
    if q3 == "Love, Actually":
        print("Correct!")
        score = score + 1
    elif q3 == "Love Actually":
         print("Correct!")
         score = score + 1
    else:
        print("Incorrect")
#==============================================================================
    q4 = input("What war film did Harry star in?")
    if q4 == "Dunkirk":
        print("Correct!")
        score = score + 1
    else:
        print("Incorrect")
#==============================================================================
    q5 = input("What is Harry's mum's first name?")
    if q5 == "Anne":
        print("Correct!")
        score = score + 1
    else:
        print("Incorrect")
#==============================================================================
    if score < 5:
        ps = str(score)
        print("You achieved " + ps)
    if score ==  5:
        print("Well done! You got everything correct!")
        print("Entering quickfire round...")
#==============================================================================
        score =  0
        print("Instructions:")
        print("Your score has been reset to 0")
        print("If you get a question incorrect, you will lose 1 point")
        print("If you achieve below 0, you wil end the game.")
#==============================================================================
        while score <= 0:
            qf1 = input("What is Harry's 2nd album called?")
            if qf1 == "Fine Line":
                print("Correct")
                score = score + 1
                print(score)
            else:
                print("Incorrect")
                score = score - 1
                print(score)
#==============================================================================
            qf2 = input("How old was Harry when he went on the X-Factor?")
            if qf2 == "16":
                print("Correct")
                score = score + 1
                print(score)
            elif qf2 == "Sixteen":
                print("Correct")
                score = score + 1
                print(score)
            else:
                print("Incorrect")
                score = score - 1
                print(score)
#==============================================================================
            qf3 = input("Finish the quote: 'This is a family show. _________?'")
            if qf3 == "Or is it?":
                print("Correct")
                score = score + 1
                print(score)
            elif qf3 == "Or is it":
                print("Correct")
                score = score + 1
                print(score)
            else:
                print("Incorrect")
                score = score - 1
                print(score)
#==============================================================================
            qf4 = input("What is Harry's middle name?'")
            if qf4 == "Edward":
                print("Correct")
                score = score + 1
                print(score)
            else:
                print("Incorrect")
                score = score - 1
                print(score)
#==============================================================================
            qf5 = input("What is Harry's blood type?'")
            if qf5 == "B+":
                print("Correct")
                score = score + 1
                print(score)
            elif qf5 == "B positive":
                print("Correct")
                score = score + 1
                print(score)
            else:
                print("Incorrect")
                score = score - 1
                print(score)
#==============================================================================
        if score < 0:
            print("GAME OVER!")
#==============================================================================
        if score > 0:
            if score < 5:
                ps = str(score)
        if score == 5:
            print("Wow, that's full marks! Well done!")
#==============================================================================
            print("Entering Death Row...")
            score =  0
            print("Instructions:")
            print("Your score has been reset to 0")
            print("If you get a question incorrect, you will end the game")
#==============================================================================
            d1 = input("What characer does Harry play in the MCU (Marvel Cinematic Universe)?")
            if d1 == "Starfox" or "Eros":
                print("Correct!")
                score = score + 1
#==============================================================================
                d2 = input("What does Harry say the best thing a girl can wear is?")
                if d2 == "A smile" or "Smile":
                    print("Correct!")
                    score = score + 1
#==============================================================================
                    d3 = input("What did Harry dress up as for 2021's 'Harryween'?")
                    if d3 == "Alice" or "Alice in Wonderland" or "A clown" or "Clown":
                        print("Correct!")
                        score = score + 1
#==============================================================================
                        d4 = input("Which singer does Harry have a crush on?")
                        if d4 == "Adele":
                            print("Correct!")
                            score = score + 1
#==============================================================================
                            d5 = input("How many nipples does Harry have?")
                            if d5 == "Four" or "4":
                                print("Correct!")
                                score = score + 1
#==============================================================================
                                if score == 5:
                                    print("Oh ma gawd! You got everything correct!")
                                    print("I think you dropped this []")
                                    print("Get your certificate here: [https://drive.google.com/file/d/1k-PJEQmqW_rv56vSId0PDo6etuC_up_G/view]")
#==============================================================================
                            else:
                                ps = str(score)
                                print("Incorrect")
                                print("You achieved " + score)
                        else:
                            ps = str(score)
                            print("Incorrect")
                            print("You achieved " + score)
                    else:
                        ps = str(score)
                        print("Incorrect")
                        print("You achieved " + score)
                else:
                    ps = str(score)
                    print("Incorrect")
                    print("You achieved " + score)
            else:
                print("Incorrect")
#==============================================================================
else:
    termination = (ans.upper())
    print("ERROR! CANNOT COMPUTE! UNKNOWN VARIABLE: [" + termination +"]")
    print("TERMINATING QUIZ!") ```

A: Using loops and functions can help you make this code quite a bit shorter and eliminate a lot of the need for copy+pasted if/else.  Here's a quick rewrite of the initial quiz section with the outline of a main() function to give you the idea:
def first_round():
    """Ask the first round questions, return cumulative score."""
    score = 0
    for question, answers in [
        ("What boyband was Harry Styles in?",
            {"One Direction", "White Eskimo"}),
        ("What is Harry's birthday (write in format dd/mm/yyy)",
            {"01/02/1990"}),
        ("What is Harry's favourite film?",
            {"Love, Actually", "Love Actually"}),
        ("What war film did Harry star in?",
            {"Dunkirk"}),
        ("What is Harry's mum's first name?",
            {"Anne"}),
    ]:
        if input(question) in answers:
            print("Correct!")
            score += 1
        else:
            print("Incorrect")
    return score

def main():
    # do intro stuff here

    score = first_round()
    if score < 5:
        print(f"You achieved {score}")
        return  # Game over!

    print("Well done! You got everything correct!")
    print("Entering quickfire round...")

    # continue on with score = quickfire_round()...

main()

Putting code in functions means that when it's time to end, you can just return and have the rest of the function continue at the outer level of indentation instead of having to go into deeper and deeper nested if/elif/else statements to continue the program.  Using loops (like in the first_round function above) means that you don't need to copy and paste the same code over and over either.
Taking the pattern above and applying it to the Death Round, we might have something like:
def death_round():
    """Ask the death round questions -- first wrong answer ends it!"""
    score = 0
    for question, answers in [
        ("What characer does Harry play in the MCU (Marvel Cinematic Universe)?",
            {"Starfox", "Eros"}),
        ("What does Harry say the best thing a girl can wear is?",
            {"A smile", "Smile"}),
        ("What did Harry dress up as for 2021's 'Harryween'?",
            {"Alice", "Alice in Wonderland", "A clown", "Clown"}),
        ("Which singer does Harry have a crush on?",
            {"Adelete"}),
        ("How many nipples does Harry have?",
            {"Four", "4"}),
    ]:
        if input(question) in answers:
            print("Correct!")
            score += 1
        else:
            print("Incorrect")
            return score  # sudden death!
    return score

Note the return in the "Incorrect" case, which is the one way this function differs from first_round, and is also what makes it so you don't need a goto or five different nested else statements to keep track of the five different times you might end the game -- as soon as there's a wrong answer, the function returns, whereupon main can look at the final score and do different things based on its value.
One more thing to think about as you work on your quiz -- right now it's very sensitive to exact phrasing and casing, even though you've provided multiple correct options.  For example:
What does Harry say the best thing a girl can wear is?Her smile
Incorrect

Here's one approach to fixing it that will make it so that any answer which contains the word "smile" will be accepted, regardless of case:
for question, answers in [
    ("What does Harry say the best thing a girl can wear is?",
        {"smile"}),
    ("What did Harry dress up as for 2021's 'Harryween'?",
        {"alice", "clown"}),
]:
    answer = input(question).lower()
    if any(a in answer for a in answers):
        print("Correct!")
    else:
        print("Incorrect")

What does Harry say the best thing a girl can wear is? Just a smile
Correct!
What did Harry dress up as for 2021's 'Harryween'? A fabulous clown
Correct!


text:
Q: Convert jquery function to javascript I'm trying to push my Javascript knowledge and improve for my current job as a designer-developer. The other developer and I cooperated on this jQuery to alter Squarespace's default menu behavior, which is really weird. But we're loading the entire jQuery library just to accomplish this one thing.
I'd like to rewrite the code to run in plain vanilla javascript so that I don't have to load the library on every website we make, but I'm not experienced enough in Javascript to just wing through this.
Here is the code:
$(function () {
    if ($(window).width() > 640) {
        $(function () {
            $(".folder-parent a").each(function () {
                $(this).next().find("a").first().hide();
            });
            $(".folder-parent a").click(function () {
                window.location = $(this).next().find("a").first().attr("href");
            });
        });
    }
});

I see some potential issues. First off, I know the class selector will have to be rewritten, or is there another way around that? I don't have the option of adding IDs so I can use getElementsById.
Can Javascript hop through the DOM (next, find) and so on?
I'll put up my own attempt at rewriting this code, but I was wondering if y'all had any pointers for converting code, or any pitfalls to avoid, or things like that. Thank you very much!
Andrew
EDIT: Here is my attempt in vanilla Javascript. This is literally the first function I've ever written that's not from a tutorial, so it didn't work. What am I doing wrong? I guess I left some jQuery mixed in.
// Function to change the default menu behavior of Squarespace. Written minus jQuery!
function fixSquarespaceNav {
    if (document.documentElement.offsetWidth > 640) {
        var navElement = document.querySelectorAll(".folder-parent a");
        foreach (navElement) {
            this.next().find("a").first().style.display = "none";
        }
        navElement.onclick=function(){
            window.location = this.next().find("a").first().attr("href");
        }; /* navElement */
    }
}

A: A more or less literal translation is
function fixSquarespaceNav() {
    if (document.documentElement.offsetWidth > 640) {
        var navElements = document.querySelectorAll(".folder-parent a");
        for(var i=0, l=navElements.length; i<l; ++i)
            navElements[i]
                .nextElementSibling
                .getElementsByTagName('a')[0]
                .style.display = "none";
        for(var i=0, l=navElements.length; i<l; ++i)
            navElements[i].onclick = function(){
                window.location =
                    this
                    .nextElementSibling
                    .getElementsByTagName('a')[0]
                    .getAttribute('href');
            };
    }
}

But you can use
(function() {
    function getAnchor(el) {
        return el.nextElementSibling.getElementsByTagName('a')[0];
    }
    function handler() { window.location = getAnchor(this).href; }
    return function fixSquarespaceNav() {
        var navElements = document.querySelectorAll(".folder-parent a");
        for(var i=0, l=navElements.length; i<l; ++i) {
            getAnchor(navElements[i]).style.display = "none";
            navElements[i].onclick = handler;
        }
    }
})();


text:
Q: Issues in running virtual threads program on intellij with java19 I am trying to run below simple program with virtual threads on my intellij with java19 version selected.
Code
public class VTSimple {
    public static void main(String[] args) {
        Runnable runnable = () -> System.out.println("Inside Runnable");
        Thread.startVirtualThread(runnable);
    }
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.java19</groupId>
    <artifactId>java19-explore</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>19</maven.compiler.source>
        <maven.compiler.target>19</maven.compiler.target>
    </properties>

</project>

Project Settings
SDK - 19
Language Level - X Experimental Features as last version shown was 17(preview) in Language Level dropdown Also Tried SDK Default Option as well.
Error
When I ran the program it gave me below error
java: invalid source release 18 with --enable-preview
  (preview language features are only supported for release 19)

Few Trials
I tried to add --enable-preview in VM Options of this small program and as well as compiler settings in preferences but it didn't work.
Edit 1

Setup Details :
Mac OS Air M1 : 12.1 Monterey
Intellij Version : IntelliJ IDEA 2021.3.3 (Community Edition) Build #IC-213.7172.25, built on March 15, 2022
Java Version : openjdk 19.0.1 2022-10-18
OpenJDK Runtime Environment (build 19.0.1+10-21)
OpenJDK 64-Bit Server VM (build 19.0.1+10-21, mixed mode, sharing)
Edit 2
Updated Intellij to version IntelliJ IDEA 2022.2.3 (Community Edition) and java version 19 was showing in language level.
But still there is an error
java: ofVirtual() is a preview API and is disabled by default.
  (use --enable-preview to enable preview APIs)

Note : I have already passed --enable-preview in VM Options of program and Compiler settings in preferences.

A: You need to use IntelliJ IDEA 2022.2 or newer for Java 19 support.

A: --enable-preview should be in VM options, NOT  program arguments

You still need to have those settings in Java Compiler

And the project settings:

Also, you can run from the command line
java --enable-preview --source 19 Main.java

Sample code:

with the following results:


text:
Q: Taking webpage screenshot on completion of a Cucumber Step Definition I'm currently researching a way in which I can implement a screen capture method in my acceptance test suite in Scala Cucumber after each step definition is completed in the scenario.
I have already implemented a method that will take a screenshot of a webpage if one of the automation test fails by invoking the method in the after hooks class. This does work fine but this will only capture the web page once the entire scenario has been completed.
I wasn't sure if there was something like before and after hooks that could be applied to the steps instead of the scenario.
Hooks.scala
@After
def tearDown(result: Scenario){

if (result.isFailed) {
  ifCurrentDriverTakesSnapshot {
    takesSnapshot =>
    Snapshotter.takeErrorSnapshot(takesSnapshot, result)
  }
}

Snapshotter.Scala
def takeErrorSnapshot(takesScreenshot: TakesScreenshot, result: Scenario)
  = {
  try {
    val screenshot = takesScreenshot.getScreenshotAs(OutputType.BYTES)
    result.embed(screenshot, "image/png")
  }
  catch {
    case e: WebDriverException =>
    e.printStackTrace(System.err)
  }
}

I would like to be able to do this in a class or method that can be called after each new page is opened or after each step definition. I could right a step definition that would handle the screen capture but I would like to do in a better way as I have 100's of test scenarios so it would be better to avoid adding a step for this in between every step definition as they have done in the below link.
Cucumber Java screenshots
If anyone could share some light on the matter i'd greatly appreciate it as I'm struggling to find much on the subject.
Thanks!!!


text:
Q: what is the winapi function declaration conventions? what is the diffrence between these six functions?
LoadLibrary
LoadLibraryA
LoadLibraryEx
LoadLibraryExA
LoadLibraryExW
LoadLibraryW

what is the meaning of each suffix in the winapi and what is the difference between all of those functions?

A: LoadLibrary and LoadLibraryEx are macros which are defined depending on whether your project is compiled with unicode support. If so, they point to LoadLibraryW and LoadLibraryExW, otherwise they point to LoadLibraryA and LoadLibraryExA.
Typically, you are expected to write code using versions without A or W in the end and let compiler definitions make all the magic for you.
The Ex suffix is a standard way of denoting an "EXtended" function: one that is similar to the regular version, but provides additional functionality. Generally, they were added in a newer version of Windows and may not always be available (although most of them are so old now that they were added back in Windows 3.1 or 95).
The exact difference between functions, as mentioned before, should always be checked on MSDN.

A: A means ANSI; W means Wide (Unicode).
The A versions do not support Unicode strings; they're relics from Win9X.
The suffix-less version will expand to the A or W versions at compile-time, depending on whether the symbol UNICODE is defined.
The Ex versions are newer versions of the API method with additional functionality; consult the documentation for more details.

A: A - ansi
W - unicode
Ex - extended version of same function, for example some additional parameters


text:
Q: How can I count characters UITextView shows? how can I learn total number of characters a UITextView shows in its specific contentSize after UILineBreakModeWordWrap applied.
I will use different strings everytime as the text of UITextView.
The strings are much longer than UITextView with its specified area can contain. The visible characters will be different for every different string because of the different length of spaces at the end of the lines.
And I want to learn the number of characters visible in my UITextView.

A: Use this method from NSString:
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode

*

*You calculate first how long the height of the UITextView should be to fit the whole text.

*Using proportions you find out how long your string should be to fit the actual size.

*a) If that string fits the current size you can add characters one by one and check again the size until it doesn't fit anymore -> the limit is what you're looking for.

*b) If that string doesn't fit the current size then you remove characters from it one by one until it fits -> again, this limit is what you're looking for in this case.

It is a very intensive method but I think it's the only one (You can optimize it by adding/removing half of the remaining string instead of adding/removing characters).


text:
Q: Do I need to use ninject.mvc extension anymore? I see there is an extension for Ninject integration with asp.net-mvc but it looks like I can integrate Ninject with mvc fine without this extension.  For example:
public class NinjectDependencyResolver : IDependencyResolver
    {
        private readonly IResolutionRoot _resolutionRoot;

    public NinjectDependencyResolver(IResolutionRoot resolutionRoot)
    {
        _resolutionRoot = resolutionRoot;
    }

    public object GetService(Type serviceType)
    {
        return _resolutionRoot.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _resolutionRoot.GetAll(serviceType);
    }
}

public class MvcApplication : HttpApplication
{
    void Application_Start()
    {
        var modules = new INinjectModule[] { new ServiceModule() };
        var kernel = new StandardKernel(modules);

        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));

Is this some legacy extension or is it still relevant?  I see recent updates to the source code so I was a bit confused

A: You can implement your own Dependency Resolver. So yes you dont need it. You can integrate Ninject quite easily without the extension. But the question is why should you do this? The Ninject.MVC3 extension provides everything to add support for Ninject without having to implement an own Dependency Resolver. This has several advantages:

*

*Unlike the implementation you are proposing, the implementation of this extension is correct and proved to work in many applications.

*It is mantained together with Ninject core. In case Ninject core changes all the necessary changes will be done for you. E.g. Ninject 3.0.0 core does not have InRequestScope anymore, but with Ninject.MVC3 you still have this scope.

*This extension is much more than a Dependency Resolver. Read the documentation!

*It runs side aside with other web technologies and the configuration can be shared. E.g. MVC4 Web API, WCF, WebForms


text:
Q: SASS not compiling (watching) anymore when using serve after Ionic update I have recently updated ionic and its libs, but that has changed many things for me.
Right now, I can make some changes in the HTML and my livereload just shows them. When I do this in a certain SCSS file, nothing happens at all. So the ionic serve --lab command is just useless for me.
This is my gulpfile.js
var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var sh = require('shelljs');

var paths = {
  sass: ['./scss/**/*.scss']
};

gulp.task('default', ['sass']);

gulp.task('sass', function(done) {
  gulp.src('./scss/ionic.app.scss')
    .pipe(sass())
    .on('error', sass.logError)
    .pipe(gulp.dest('./www/css/'))
    .pipe(minifyCss({
      keepSpecialComments: 0
    }))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(gulp.dest('./www/css/'))
    .on('end', done);
});

gulp.task('watch', function() {
  gulp.watch(paths.sass, ['sass']);
});

And this is my local environment:
Cordova CLI: You have been opted out of telemetry. To change this, run: cordova telemetry on.
6.3.1

Gulp version:  CLI version 3.9.1
Gulp local:   Local version 3.9.1
Ionic Framework Version: 1.3.1-nightly-4219
Ionic CLI Version: 2.1.0-beta.3
Ionic App Lib Version: 2.1.0-beta.1
ios-deploy version: 1.9.0
ios-sim version: 5.0.8
OS: Mac OS X El Capitan
Node Version: v6.6.0
Xcode version: Xcode 8.0 Build version 8A218a

Any idea what goes wrong or what I should do? I already tried ionic setup sass, but that just works for one time. I do not want to that everytime I change the code. It looks like it's not watching my SCSS file anymore, but I don't know why, because I haven't changed my gulpfile.js at all.

A: Okay, I've found the solution, but it's actually very sad that the transition between ionic 1.x and ionic 2.x is just so badly documentated and not working flawlessly.
Anyway, what I did is:
Add this to my gulpfile.js
gulp.task('serve:before', ['default','watch']);

And also change my ionic.config.js file to:
{
  "name": "HereComesTheNameOfYourApp",
  "app_id": "YOURIDNUMBERHERE",
  "v2": false,
  "typescript": false,
  "watch": {
    "sass": [
      "scss/**/*.scss"
    ],
    "html": [
      "www/**/*.html"
    ],
    "livereload": [
      "www/**/*.html",
      "www/**/*.js",
      "www/**/*.css"
    ]
  }
}

Hope it will help someone else as well.

A: It is a bug with Ionic, so what you just need to do is running two command prompt:

*

*ionic run serve

*gulp sass


text:
Q: running hbase shell command giving following error hbase shell
This file has been superceded by packaging our ruby files into a jar
  and using jruby's bootstrapping to invoke them. If you need to
  source this file fo some reason it is now named 'jar-bootstrap.rb' and is
  located in the root of the file hbase-shell.jar and in the source tree at
  'hbase-shell/src/main/ruby'

HBase 2.5.2


text:
Q: Java - Json array to json object This seems quite simple but i'm struggling to transform this:
{
    "myList": [{
        "id": 1,
        "type": "EnergyBox",
        "properties": ["Name : Eb1", "Prop2 : Val1", "PropN : ValN"]
    }, {
        "id": 2,
        "type": "EnergyBox",
        "properties": ["Name : Eb2", "Prop2 : Val2", "Prop3 : Val3"]
    }]
}

into this:
{
    "myList": [{
        "id": 1,
        "type": "EnergyBox",
        "properties": {
            "Name": "Eb1",
            "Prop2": "Val1",
            "PropN": "ValN"
        }
    }, {
        "id": 2,
        "type": "EnergyBox",
        "properties": {
            "Name": "Eb2",
            "Prop2": "Val2",
            "Prop3": "Val3"
        }
    }]
}

I'm using Java 8, Jackson and Simplejson to parse the data, but somehow, and after many hours of trying, still not working.

A: Is it OK that key-value in properties like one string?
For that purpose this should work:
        JSONParser parser = new JSONParser();
        JSONObject json = (JSONObject) parser.parse(jsonString);
        JSONArray array = (JSONArray) json.get("myList");
        for( int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);
            JSONArray jsonArray = (JSONArray) object.get("properties");
            JSONObject newJObj = new JSONObject();
            for(int j = 0; j < jsonArray.size(); j++) {
                String[] keyValue = jsonArray.get(j).toString().split(" : ");
                newJObj.put(keyValue[0], keyValue[1]);
            }
            newJObj.toJSONString();
            object.put("properties", newJObj);
        }
        json.toJSONString();

A: I tried to convert the Json as per your requirement, try the following code.
public void test() throws JsonParseException, JsonMappingException, IOException {

    String json = "{"+
                        "\"myList\": [{"+
                        "\"id\": 1,"+
                        "\"type\": \"EnergyBox\","+
                        "\"properties\": [\"Name : Eb1\", \"Prop2 : Val1\", \"PropN : ValN\"]"+
                    "}, {"+
                        "\"id\": 2,"+
                        "\"type\": \"EnergyBox\","+
                        "\"properties\": [\"Name : Eb2\", \"Prop2 : Val2\", \"Prop3 : Val3\"]"+
                    "}]"+
                "}";

    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(json);
    JsonNode myList = root.get("myList");
    myList.forEach(n -> {
        System.out.println(n);
        System.out.println(n.get("properties"));
        ObjectNode updatedProperties = mapper.createObjectNode();
        n.get("properties").forEach(p -> {
            String[] vals = p.textValue().split(":");
            updatedProperties.put(vals[0].trim(), vals[1].trim());
        });
        ((ObjectNode)n).put("properties", updatedProperties);
    });

    System.out.println(myList);

}

A:            JSONObject response= Array.getJSONObject(insert_your_Response);

       try {
            JSONArray Array = response.getJSONArray("myList");

            assert Array != null;
            for (int k = 0; k < Array.length(); k++) {

                try {
                    JSONObject object1 = Array.getJSONObject(k);
                    int  id = object1.getInt("id");
                    String type = object1.getString("type");
                    JSONObject  propertiesObject=object1.getJSONObject("properties");

                    String Name = propertiesObject.getString("Name");
                    String Prop2 = propertiesObject.getString("Prop2");
                    String Prop3 = propertiesObject.getString("Prop3");

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


text:
Q: How to release tensors from memory when not in need anymore? I have hypothetical graph which has a series of computations as follows:
a_0 = tf.placeholder()
a_1 = some_op_1(a_0)
a_2 = some_op_2(a_1)
a_3 = some_op_3(a_2)

Observe that when computing a_3; a_0 and a_1 are not needed and hence they can be discarded prior to allocating memory for a_3. Is there some way to ask TensorFlow to perform this memory optimization (agree that there is some cost in time)?
Please note that this is not the same as this question about allocating memory only when needed.
EDIT: This network will not be trained, so don't worry about backprop.

A: TensorFlow uses reference counting to release the memory used by a tensor as soon as it is no longer used. The values of a_0 and a_1 will be deleted as soon as there are no more references to them, and in the latest builds of TensorFlow (post-1.0 nightly builds) some operations will even reuse the input buffer for the output if they have the same shape and element type.


text:
Q: remove quotes from specific field - integer between quotes I want to remove quotes from specific field where there is an integer between quotes.
From this line : "AAA","99"
to this line :  "AAA",99

A: Using sed:
s='"AAA","99"'
sed 's/"\([0-9]*\)"/\1/g' <<< "$s"
"AAA",99

A: Try this with GNU sed:
echo '"AAA","99"' | sed -E 's/"([0-9]+)"$/\1/'

Output:

"AAA",99

A: With awk:
awk -F , 'BEGIN { OFS = FS } $2 ~ /^"[0-9]+"$/ { gsub(/"/, "", $2) } 1'

That works as follows:
BEGIN { OFS = FS }  # Delimit output the same way as the input

$2 ~ /^"[0-9]+"$/ { # if the second field ($2) consists of only numbers encased
                    # by double quotes (i.e., matches the regex ^"[0-9]"$)
  gsub(/"/, "", $2) # remove the quotes from it
}
1                   # print in any case

To make this work for any (and not just a specific field), do the replacement in a loop:
awk -F , 'BEGIN { OFS = FS } { for(i = 1; i <= NF; ++i) if($i ~ /^"[0-9]+"$/) { gsub(/"/, "", $i) } } 1'

The changed bit here is
{                              # Do this unconditionally in every line:
  for(i = 1; i <= NF; ++i) {   # wade through all the fields
    if($i ~ /^"[0-9]+"$/) {    # then do with them the same thing as before.
      gsub(/"/, "", $i)
    }
  }
}


text:
Q: How do I indicate OpenACC to sequentially execute one instruction inside a parallel loop? I would like the 'r_m[i] /= lines_samples;' line to be executed once, by one thread I mean. Do I have to put a special pragma or do anything for the compiler to understand it?
Here is the code:
    #pragma acc parallel loop
    for(i=0; i<bands; i++)
    {
        #pragma acc loop seq // This may be a reduction, not a seq, who knows? ^^
        for(j=0; j<lines_samples; j++)
            r_m[i] += image_vector[i*lines_samples+j];

        r_m[i] /= lines_samples;

        #pragma acc loop
        for(j=0; j<lines_samples; j++)
            R_o[i*lines_samples+j] = image_vector[i*lines_samples+j] - r_m[i];
    }

Thank you a lot!

A: Assuming the loops are scheduled with the outer loop being "gang" and inner loop as "vector", this line would be executed once per gang (i.e. only on thread in the gang).  So it will work as you expect.
Depending on the trip count of the first "j" loop, you may or may not use a reduction.  Reductions do have overhead, so if the trip count is small, then it may be better to leave it as sequential.  Otherwise, I suggest using a temp scalar for the reductions since as it is now, would require an array reduction which incurs more overhead.
Something like:
float rmi = r_m[i];
#pragma acc loop reduction(+:rmi)
for(j=0; j<lines_samples; j++)
    rmi += image_vector[i*lines_samples+j];

r_m[i] = rm1/lines_samples;


text:
Q: Swift 5.1 . Paginate firestore documents x amount of times using a UITableView I can currently get all the documents from a firestore collection ( it has around 20 documents total ). I want to paginate the request into a UITableView ( eg. the first request will create 3 tableView rows and every subsequent request creates 3 more. ).
The tableview methods: numberOfRowsInSection and cellForRowAt are already set up and are working if there is no pagination ( if the entire collection is loaded in 1 go ).
import Firebase

class tableViewList: UITableViewController {

var queryArray: [QueryDocumentSnapshot] = []

override func viewDidLoad() {

loadDocuments()
}

func loadDocuments() {
let documents = Firestore.firestore().collection("COLLECTION NAME").order(by:
"CITY", descending: false).limit(to: 3)
documents.addSnapshotListener { [weak self] (querySnapshot, err) in
guard let strongSelf = self else {return}
if err != nil {
print("NOT WORKING")
} else {
strongSelf.queryArray = querySnapshot?.documents  {
for fields in strongSelf.queryArray {
let data = fields.data()
// Get document fields..... ( got this to work )

DispatchQueue.main.async {
strongSelf.tableView.reloadData()
}
}
}
}
}

// Start of the issue ( paginate 3 subsequent documents )
guard let lastSequence = querySnapshot?.documents.last else {return}
let nextSequence = Firestore.firestore().collection("COLLECTION
NAME").order(by:
"CITY", descending: false).start(afterDocument: lastSequence)

// This is where I am stuck on how to load more documents ( and
// tableView cells )

    }

}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
    return queryArray.count

}

// the cellForRow is not important since it's out of the question
// scope
    override func tableView(_ tableView: UITableView, cellForRowAt
indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier:
"ListCell", for: indexPath) as! ListCell
}

}

// I researched online this func ( willDisplay ) can create new
// tableView cells for the pagination, but I cannot understand it
// properly ). Not sure if this func is required.
override func tableView(_ tableView: UITableView, willDisplay cell:
UITableViewCell, forRowAt indexPath: IndexPath) {

// Any help will be appreciated. thanks.